Skip to main content

oak_core/
lib.rs

1pub mod change_set;
2pub mod chunking;
3pub mod diff;
4pub mod error;
5pub mod hash;
6pub mod hash_format;
7pub mod ignore;
8pub mod merge;
9/// Wire protocol DTOs for the push/pull/clone sync protocol (shared by the
10/// CLI client and the hosted server). Not gated behind
11/// `local-repo` — server-side consumers need it with `default-features = false`.
12pub mod protocol;
13/// Sparse-checkout cone matching (Perforce-style partial clones). Pure path
14/// logic with no I/O, so it is available to both the CLI client and any
15/// server-side consumer without the `local-repo` feature.
16pub mod sparse;
17pub mod tree;
18/// Views: pruned, hash-verifiable slices of a repository (partial clones and
19/// mounts, restricted readers). Pure tree logic, no I/O.
20pub mod view;
21
22// Client-side local repository, gated behind the default `local-repo` feature.
23#[cfg(feature = "local-repo")]
24pub mod git;
25#[cfg(feature = "local-repo")]
26pub mod sqlite;
27#[cfg(feature = "local-repo")]
28pub mod traits;
29
30pub use change_set::{
31    CanonicalChangeSetV1, CanonicalPathChangeV1, ChangeScopeV1, ChangeStateV1,
32    CHANGE_SET_OBJECT_FORMAT_V1,
33};
34pub use chunking::{
35    blob_chunk_mapping, chunk_content, reassemble_chunks, stream_chunk_content, BlobChunkMapping,
36    ChunkInfo,
37};
38#[cfg(feature = "local-repo")]
39pub use chunking::{chunk_decode, chunk_decode_limited, chunk_encode};
40pub use diff::{
41    binary_or_large_notice, binary_or_oversize_notice, inline_diff_ranges, is_binary, DiffLine,
42    FileDiff, Hunk, DEFAULT_CONTEXT_LINES, MAX_TEXT_DIFF_BYTES,
43};
44pub use error::{
45    CommitPhaseError, DescriptionStaleState, ErrorCode, ExitCode, FinishBlocker, FinishPhaseError,
46    FinishPreflightError, MissingApproval, OakError, OakErrorKind, Result, RootRefusal,
47    WorktreeTransition,
48};
49pub use hash::{hash_bytes, hash_string, Hash, HashKind};
50pub use hash_format::HashFormat;
51pub use ignore::{
52    is_system_metadata_path, root_dirs, IgnorePatterns, ROOT_DIRS_FILE, ROOT_STATE_FILE,
53    TRACKED_OAK_FILES,
54};
55pub use merge::{
56    three_way_merge_manifests, three_way_merge_text, three_way_merge_trees, MergeConflict,
57    MergeOutcome, TextMerge, TreeMergeOutcome,
58};
59pub use sparse::SparseCone;
60pub use tree::{
61    build_tree, collect_tree_objects, diff_tree_entries, diff_trees, edit_tree, flatten_tree,
62    is_metadata_dir_component, normalize_path, resolve_path, subtree_at_path, validate_entry_name,
63    validate_tree_path, validate_worktree_path, worktree_path_problem, BuiltTree, Tree, TreeEntry,
64    TreeEntryKind,
65};
66pub use view::{
67    derive_view_commit, graft_tree, prune_tree, DerivedViewCommit, ViewSpec, VIEW_PROTOCOL,
68};
69
70// Client-side storage: the synchronous `Repository` trait, its local SQLite
71// backend, and a read-only git backend. Merged in from the former
72// `oak-storage` crate so this one crate carries both the data model and a
73// local repository implementation. Gated behind the default `local-repo`
74// feature.
75#[cfg(feature = "local-repo")]
76pub use git::GitRepository;
77#[cfg(feature = "local-repo")]
78pub use sqlite::{
79    BulkImporter, ChangeCaptureProvenance, CompactStats, SqliteRepository, StoredBlobReader,
80    StoredChangeCapture,
81};
82#[cfg(feature = "local-repo")]
83pub use traits::{BlobSource, Repository, StatCacheEntry};
84
85use chrono::{DateTime, Utc};
86use std::collections::{HashMap, HashSet, VecDeque};
87
88/// Files larger than this threshold are transferred separately during
89/// push/pull for better performance and memory efficiency.
90pub const LARGE_FILE_THRESHOLD: u64 = 10 * 1024 * 1024; // 10 MB
91use serde::{Deserialize, Serialize};
92
93/// A content-addressed blob (file content)
94#[derive(Debug, Clone, Serialize, Deserialize)]
95pub struct Blob {
96    pub hash: Hash,
97    pub content: Vec<u8>,
98    pub size: u64,
99}
100
101impl Blob {
102    /// Create a new blob from content
103    pub fn new(content: Vec<u8>) -> Self {
104        let hash = hash_bytes(&content);
105        let size = content.len() as u64;
106        Blob {
107            hash,
108            content,
109            size,
110        }
111    }
112
113    /// Create a blob from a string
114    pub fn from_string(s: &str) -> Self {
115        Self::new(s.as_bytes().to_vec())
116    }
117
118    /// Create a blob from a string (alias for from_string)
119    #[allow(clippy::should_implement_trait)]
120    pub fn from_str(s: &str) -> Self {
121        Self::from_string(s)
122    }
123
124    /// The zero-byte blob — every empty file in every repo shares this one
125    /// object.
126    pub fn empty() -> Self {
127        Self::new(Vec::new())
128    }
129
130    /// Hash of zero-byte content (`af1349b9…`, BLAKE3 of the empty input).
131    ///
132    /// Under the v1 content-addressing format this value is *also*
133    /// [`Tree::empty_hash`] and the hash of an empty chunk, because v1 hashes
134    /// every object kind's raw bytes with no domain prefix — see
135    /// [`hash_format`] for why that is a weakness v2 fixes. The three values
136    /// coincide today but the *meanings* never did, so blob-side code must
137    /// use this constant and tree-side code `Tree::empty_hash`: under a
138    /// domain-separated format they diverge and both call sites stay correct.
139    pub fn empty_hash() -> Hash {
140        hash_format::hash_blob(HashFormat::V1, b"")
141    }
142
143    /// Is `hash` the hash of zero-byte content?
144    ///
145    /// This is the one blob hash whose content is fully determined by the
146    /// hash itself, which is what makes [`ensure_empty_blob`] sound.
147    pub fn is_empty_hash(hash: &Hash) -> bool {
148        hash == &Self::empty_hash()
149    }
150}
151
152/// Store the zero-byte blob locally if `hash` names it; report whether it did.
153///
154/// A blob missing from local storage normally means data loss — the bytes
155/// exist only where they were pushed, and writing a file without them would
156/// produce a working tree that silently disagrees with its manifest. The
157/// empty blob is the single exception: its content is *implied* by its hash
158/// (there is exactly one byte string that hashes to [`Blob::empty_hash`], and
159/// it is the empty one), so the client can always reconstruct it without the
160/// server having shipped anything.
161///
162/// That exception is load-bearing in practice. Servers whose blob storage was
163/// migrated with a `octet_length(content) > 0` filter have a metadata-only
164/// row for the empty blob: `blobs/check` reports it present while pull omits
165/// it, so the user can neither clone nor repair by re-pushing. Synthesizing
166/// it client-side unblocks those repos without weakening the missing-blob
167/// protection for any hash whose bytes are *not* derivable.
168///
169/// Returns `false` — without touching storage — for any other hash, so
170/// callers can keep their existing hard error in the `false` arm.
171#[cfg(feature = "local-repo")]
172pub fn ensure_empty_blob(repo: &dyn Repository, hash: &Hash) -> Result<bool> {
173    if !Blob::is_empty_hash(hash) {
174        return Ok(false);
175    }
176    repo.store_blob(&Blob::empty())?;
177    Ok(true)
178}
179
180/// Run [`ensure_empty_blob`] for every entry of `manifest`, so a subsequent
181/// "is every blob present?" sweep sees the empty blob as available.
182///
183/// Cheap when there is nothing to do: manifests that reference no empty file
184/// never touch storage, and one that references several (two empty files in
185/// different directories are the *same* blob) writes once.
186#[cfg(feature = "local-repo")]
187pub fn ensure_empty_blobs_in_manifest(repo: &dyn Repository, manifest: &Manifest) -> Result<()> {
188    if manifest
189        .entries
190        .iter()
191        .any(|e| Blob::is_empty_hash(&e.blob_hash))
192        // A read first: status/commit/merge call this on every run, and
193        // re-storing a present blob still opens a write transaction.
194        && !repo.has_blob(&Blob::empty_hash())?
195    {
196        repo.store_blob(&Blob::empty())?;
197    }
198    Ok(())
199}
200
201/// File mode/permissions
202#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
203pub enum FileMode {
204    /// Regular file (644)
205    #[default]
206    Regular,
207    /// Executable file (755)
208    Executable,
209    /// Symbolic link
210    Symlink,
211}
212
213/// An entry in a manifest (a file at a specific path)
214#[derive(Debug, Clone, Serialize, Deserialize)]
215pub struct ManifestEntry {
216    pub path: String,
217    pub blob_hash: Hash,
218    pub mode: FileMode,
219}
220
221/// A manifest represents the complete state of the repository at a point in time
222#[derive(Debug, Clone, Serialize, Deserialize)]
223pub struct Manifest {
224    pub hash: Hash,
225    pub entries: Vec<ManifestEntry>,
226}
227
228impl Manifest {
229    /// Create a manifest from entries, computing the hash as the **root tree
230    /// hash** of the equivalent nested tree. This makes `manifest.hash`
231    /// interchangeable with the tree storage produced by [`tree::build_tree`]:
232    /// callers that store via `put_tree(entries)` and callers that store via
233    /// `Manifest::new(entries).hash` end up with the same content-addressed key.
234    pub fn new(mut entries: Vec<ManifestEntry>) -> Self {
235        // Sort entries by path for deterministic ordering of the flat view.
236        entries.sort_by(|a, b| a.path.cmp(&b.path));
237        // Unchecked: the hash is only a diff identity here and no tree object
238        // is stored. Storage paths (`put_tree`/`put_manifest`)
239        // go through the validating `tree::build_tree`.
240        let hash = tree::build_tree_unchecked(&entries).root_hash;
241        Manifest { hash, entries }
242    }
243
244    /// Create an empty manifest
245    pub fn empty() -> Self {
246        Manifest {
247            hash: tree::Tree::empty_hash(),
248            entries: Vec::new(),
249        }
250    }
251
252    /// Get an entry by path
253    pub fn get(&self, path: &str) -> Option<&ManifestEntry> {
254        self.entries.iter().find(|e| e.path == path)
255    }
256
257    /// Compare with another manifest and return changes (with default rename detection)
258    pub fn diff(&self, other: &Manifest) -> Vec<FileChange> {
259        self.diff_with_renames(other, &RenameConfig::default())
260    }
261
262    /// Compare with another manifest and return changes, detecting renames
263    /// using the provided configuration.
264    ///
265    /// Only detects renames where the old and new blob hashes are identical
266    /// (pure renames with no edits). To catch rename-with-edit, post-process
267    /// the result with [`detect_renames_by_content`] — that pass needs blob
268    /// content, which a pure manifest-level diff doesn't have.
269    pub fn diff_with_renames(&self, other: &Manifest, _config: &RenameConfig) -> Vec<FileChange> {
270        self.diff_entries_with_renames(&other.entries)
271    }
272
273    /// Compare with another manifest with *full* rename detection: exact
274    /// blob-hash renames from [`Manifest::diff_with_renames`], then
275    /// content-similarity promotion of remaining Delete+Add pairs via
276    /// [`detect_renames_by_content`].
277    ///
278    /// This is the diff every user-facing change set should go through so
279    /// `oak diff`, `oak branch diff`, `oak status`, and `oak commit` agree on
280    /// rename-with-edit. `get_content` loads blob bytes by hash (returning
281    /// `Ok(None)` for missing blobs, which skips that candidate); the
282    /// `config` caps (`max_file_bytes`, `max_candidates`) bound how much
283    /// content is ever loaded.
284    pub fn diff_with_content_renames<F>(
285        &self,
286        other: &Manifest,
287        get_content: F,
288        config: &RenameConfig,
289    ) -> Result<Vec<FileChange>>
290    where
291        F: FnMut(&Hash) -> Result<Option<Vec<u8>>>,
292    {
293        self.diff_entries_with_content_renames(&other.entries, get_content, config)
294    }
295
296    /// Entries-based variant of [`Manifest::diff_with_content_renames`], for
297    /// status-like callers that already resolved the working tree to manifest
298    /// entries (see [`Manifest::diff_entries_with_renames`]).
299    pub fn diff_entries_with_content_renames<F>(
300        &self,
301        other_entries: &[ManifestEntry],
302        get_content: F,
303        config: &RenameConfig,
304    ) -> Result<Vec<FileChange>>
305    where
306        F: FnMut(&Hash) -> Result<Option<Vec<u8>>>,
307    {
308        let mut changes = self.diff_entries_with_renames(other_entries);
309        detect_renames_by_content(&mut changes, get_content, config)?;
310        Ok(changes)
311    }
312
313    /// Compare with a set of entries without first constructing a full
314    /// [`Manifest`] for them.
315    ///
316    /// This is useful for status-like callers that already resolved the working
317    /// tree to manifest entries and only need the change set. It avoids sorting
318    /// and hashing the entire new tree before diffing, while preserving the same
319    /// exact-hash rename behavior as [`Manifest::diff_with_renames`].
320    pub fn diff_entries_with_renames(&self, other_entries: &[ManifestEntry]) -> Vec<FileChange> {
321        let mut changes = Vec::new();
322        let mut deleted: Vec<(&str, &ManifestEntry)> = Vec::new();
323        let mut added: Vec<(&str, &ManifestEntry)> = Vec::new();
324
325        // Build one lookup map for the old manifest, then classify each current
326        // entry as added/modified while recording seen paths. The older
327        // implementation also built a full new-manifest path map; status callers
328        // already have the current entries, so that extra map and full-manifest
329        // construction are avoidable.
330        let self_map: HashMap<&str, &ManifestEntry> =
331            self.entries.iter().map(|e| (e.path.as_str(), e)).collect();
332        let mut seen_other: HashSet<&str> = HashSet::with_capacity(other_entries.len());
333
334        // Find added and modified files.
335        for other_entry in other_entries {
336            let path = other_entry.path.as_str();
337            seen_other.insert(path);
338            match self_map.get(path) {
339                None => {
340                    added.push((path, other_entry));
341                }
342                Some(entry) => {
343                    if entry.blob_hash != other_entry.blob_hash || entry.mode != other_entry.mode {
344                        changes.push(FileChange {
345                            path: path.to_string(),
346                            change_type: ChangeType::Modified,
347                            old_blob_hash: Some(entry.blob_hash.clone()),
348                            new_blob_hash: Some(other_entry.blob_hash.clone()),
349                            old_path: None,
350                            old_mode: Some(entry.mode),
351                            new_mode: Some(other_entry.mode),
352                        });
353                    }
354                }
355            }
356        }
357
358        // Find removed files.
359        for entry in &self.entries {
360            let path = entry.path.as_str();
361            if !seen_other.contains(path) {
362                deleted.push((path, entry));
363            }
364        }
365        added.sort_by(|(a, _), (b, _)| a.cmp(b));
366
367        // Rename detection: exact blob hash matches only. Rename-with-edit
368        // is recovered later by detect_renames_by_content, which has access
369        // to blob content.
370        // Preserve the old first-match behavior without scanning every add
371        // for every delete.
372        let mut added_by_hash: HashMap<&Hash, VecDeque<usize>> = HashMap::new();
373        for (idx, (_, add_entry)) in added.iter().enumerate() {
374            added_by_hash
375                .entry(&add_entry.blob_hash)
376                .or_default()
377                .push_back(idx);
378        }
379
380        let mut matched_added = vec![false; added.len()];
381        for (del_path, del_entry) in &deleted {
382            match added_by_hash
383                .get_mut(&del_entry.blob_hash)
384                .and_then(VecDeque::pop_front)
385            {
386                Some(add_idx) => {
387                    let (add_path, add_entry) = added[add_idx];
388                    changes.push(FileChange {
389                        path: add_path.to_string(),
390                        change_type: ChangeType::Renamed,
391                        old_blob_hash: Some(del_entry.blob_hash.clone()),
392                        new_blob_hash: Some(add_entry.blob_hash.clone()),
393                        old_path: Some(del_path.to_string()),
394                        old_mode: Some(del_entry.mode),
395                        new_mode: Some(add_entry.mode),
396                    });
397                    matched_added[add_idx] = true;
398                }
399                None => {
400                    changes.push(FileChange {
401                        path: del_path.to_string(),
402                        change_type: ChangeType::Deleted,
403                        old_blob_hash: Some(del_entry.blob_hash.clone()),
404                        new_blob_hash: None,
405                        old_path: None,
406                        old_mode: Some(del_entry.mode),
407                        new_mode: None,
408                    });
409                }
410            }
411        }
412
413        for (idx, (add_path, add_entry)) in added.iter().enumerate() {
414            if !matched_added[idx] {
415                changes.push(FileChange {
416                    path: add_path.to_string(),
417                    change_type: ChangeType::Added,
418                    old_blob_hash: None,
419                    new_blob_hash: Some(add_entry.blob_hash.clone()),
420                    old_path: None,
421                    old_mode: None,
422                    new_mode: Some(add_entry.mode),
423                });
424            }
425        }
426
427        // Sort by path for consistent ordering
428        changes.sort_by(|a, b| a.path.cmp(&b.path));
429        changes
430    }
431}
432
433/// Type of change to a file
434#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
435pub enum ChangeType {
436    Added,
437    Modified,
438    Deleted,
439    Renamed,
440}
441
442impl std::fmt::Display for ChangeType {
443    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
444        match self {
445            ChangeType::Added => write!(f, "A"),
446            ChangeType::Modified => write!(f, "M"),
447            ChangeType::Deleted => write!(f, "D"),
448            ChangeType::Renamed => write!(f, "R"),
449        }
450    }
451}
452
453/// A file change in a commit
454#[derive(Debug, Clone, Serialize, Deserialize)]
455pub struct FileChange {
456    pub path: String,
457    pub change_type: ChangeType,
458    pub old_blob_hash: Option<Hash>,
459    pub new_blob_hash: Option<Hash>,
460    /// For renames, the original path before renaming
461    #[serde(default, skip_serializing_if = "Option::is_none")]
462    pub old_path: Option<String>,
463    /// File mode before the change. `None` for additions, or when the
464    /// producer didn't carry mode through (e.g. a FileChange built from a
465    /// wire payload that omits mode). Populated by [`Manifest::diff_with_renames`].
466    #[serde(default, skip_serializing_if = "Option::is_none")]
467    pub old_mode: Option<FileMode>,
468    /// File mode after the change. `None` for deletions, or when the
469    /// producer didn't carry mode through.
470    #[serde(default, skip_serializing_if = "Option::is_none")]
471    pub new_mode: Option<FileMode>,
472}
473
474/// Validate that a commit's file-change records describe exactly the
475/// transition from `parent` to `current`.
476///
477/// The representation is semantic: a rename may change content and mode, and
478/// independent records may form an overwrite or rename cycle. Validation is
479/// therefore order-independent: every record claims an immutable old-side
480/// parent path and/or new-side current path, and those claims must exactly
481/// cover the paths whose entries changed.
482pub fn validate_manifest_transition(
483    parent: &Manifest,
484    current: &Manifest,
485    changes: &[FileChange],
486) -> std::result::Result<(), String> {
487    let parent_entries: std::collections::BTreeMap<String, (Hash, FileMode)> = parent
488        .entries
489        .iter()
490        .map(|entry| (entry.path.clone(), (entry.blob_hash.clone(), entry.mode)))
491        .collect();
492    let current_entries: std::collections::BTreeMap<String, (Hash, FileMode)> = current
493        .entries
494        .iter()
495        .map(|entry| (entry.path.clone(), (entry.blob_hash.clone(), entry.mode)))
496        .collect();
497    if parent_entries.len() != parent.entries.len()
498        || current_entries.len() != current.entries.len()
499    {
500        return Err("manifest contains duplicate paths".to_string());
501    }
502
503    let expected_old: std::collections::BTreeSet<String> = parent_entries
504        .iter()
505        .filter(|(path, entry)| current_entries.get(*path) != Some(*entry))
506        .map(|(path, _)| path.clone())
507        .collect();
508    let expected_new: std::collections::BTreeSet<String> = current_entries
509        .iter()
510        .filter(|(path, entry)| parent_entries.get(*path) != Some(*entry))
511        .map(|(path, _)| path.clone())
512        .collect();
513    let mut claimed_old = std::collections::BTreeSet::new();
514    let mut claimed_new = std::collections::BTreeSet::new();
515
516    let claim_old = |path: &str,
517                     hash: Option<&Hash>,
518                     mode: Option<FileMode>,
519                     claimed: &mut std::collections::BTreeSet<String>|
520     -> std::result::Result<(), String> {
521        let hash = hash.ok_or_else(|| format!("old-side path {path:?} has no blob"))?;
522        let entry = parent_entries
523            .get(path)
524            .ok_or_else(|| format!("old-side path {path:?} is absent from parent"))?;
525        if entry.0 != *hash || mode.is_some_and(|claimed_mode| claimed_mode != entry.1) {
526            return Err(format!(
527                "old-side path {path:?} claims blob {hash} but does not match parent blob {}",
528                entry.0
529            ));
530        }
531        if !claimed.insert(path.to_string()) {
532            return Err(format!("old-side path {path:?} is claimed more than once"));
533        }
534        Ok(())
535    };
536    let claim_new = |path: &str,
537                     hash: Option<&Hash>,
538                     mode: Option<FileMode>,
539                     claimed: &mut std::collections::BTreeSet<String>|
540     -> std::result::Result<(), String> {
541        let hash = hash.ok_or_else(|| format!("new-side path {path:?} has no blob"))?;
542        let entry = current_entries
543            .get(path)
544            .ok_or_else(|| format!("new-side path {path:?} is absent from current"))?;
545        if entry.0 != *hash || mode.is_some_and(|claimed_mode| claimed_mode != entry.1) {
546            return Err(format!(
547                "new-side path {path:?} claims blob {hash} but does not match current blob {}",
548                entry.0
549            ));
550        }
551        if !claimed.insert(path.to_string()) {
552            return Err(format!("new-side path {path:?} is claimed more than once"));
553        }
554        Ok(())
555    };
556
557    for change in changes {
558        match change.change_type {
559            ChangeType::Added => {
560                if change.old_blob_hash.is_some()
561                    || change.old_path.is_some()
562                    || change.old_mode.is_some()
563                {
564                    return Err(format!(
565                        "addition {:?} has invalid old-side state",
566                        change.path
567                    ));
568                }
569                claim_new(
570                    &change.path,
571                    change.new_blob_hash.as_ref(),
572                    change.new_mode,
573                    &mut claimed_new,
574                )?;
575            }
576            ChangeType::Deleted => {
577                if change.new_blob_hash.is_some()
578                    || change.old_path.is_some()
579                    || change.new_mode.is_some()
580                {
581                    return Err(format!(
582                        "deletion {:?} has invalid new-side state",
583                        change.path
584                    ));
585                }
586                claim_old(
587                    &change.path,
588                    change.old_blob_hash.as_ref(),
589                    change.old_mode,
590                    &mut claimed_old,
591                )?;
592            }
593            ChangeType::Renamed => {
594                let old_path = change
595                    .old_path
596                    .as_ref()
597                    .ok_or_else(|| format!("rename {:?} has no old_path", change.path))?;
598                if old_path == &change.path {
599                    return Err(format!(
600                        "rename source and destination are both {old_path:?}"
601                    ));
602                }
603                claim_old(
604                    old_path,
605                    change.old_blob_hash.as_ref(),
606                    change.old_mode,
607                    &mut claimed_old,
608                )?;
609                claim_new(
610                    &change.path,
611                    change.new_blob_hash.as_ref(),
612                    change.new_mode,
613                    &mut claimed_new,
614                )?;
615            }
616            ChangeType::Modified => {
617                if change.old_path.is_some() {
618                    return Err(format!(
619                        "modification {:?} must not carry old_path",
620                        change.path
621                    ));
622                }
623                claim_old(
624                    &change.path,
625                    change.old_blob_hash.as_ref(),
626                    change.old_mode,
627                    &mut claimed_old,
628                )?;
629                claim_new(
630                    &change.path,
631                    change.new_blob_hash.as_ref(),
632                    change.new_mode,
633                    &mut claimed_new,
634                )?;
635            }
636        }
637    }
638
639    if claimed_old != expected_old || claimed_new != expected_new {
640        return Err("file changes do not describe the complete manifest transition".to_string());
641    }
642    Ok(())
643}
644
645/// Configuration for rename detection heuristics
646#[derive(Debug, Clone)]
647pub struct RenameConfig {
648    /// Minimum similarity ratio (0.0-1.0) for [`detect_renames_by_content`]
649    /// to pair a delete+add as a rename. Exact blob-hash matches are always
650    /// detected by [`Manifest::diff_with_renames`] regardless of this value.
651    pub similarity_threshold: f64,
652
653    /// Per-file size cap (bytes) for content-similarity comparison. Files
654    /// larger than this on either side of a pair are skipped — rename
655    /// detection only fires when both contents fit in memory. Default: 1 MiB.
656    pub max_file_bytes: usize,
657
658    /// Maximum number of (delete + add) candidates to consider in
659    /// [`detect_renames_by_content`]. Past this, the pass bails out without
660    /// running similarity scoring — this prevents the O(D*A) pair scan from
661    /// pathologically slowing huge refactor commits. Default: 1000.
662    pub max_candidates: usize,
663}
664
665impl Default for RenameConfig {
666    fn default() -> Self {
667        RenameConfig {
668            similarity_threshold: 0.5,
669            max_file_bytes: 1 << 20,
670            max_candidates: 1000,
671        }
672    }
673}
674
675/// Compute a content-similarity score between two byte slices (0.0-1.0).
676///
677/// Uses line-based Jaccard: returns `|A ∩ B| / |A ∪ B|` over the set of
678/// distinct lines on each side. Binary inputs (anything with a NUL byte
679/// in the first 8 KiB) and empty inputs score 0.0 — those fall back to
680/// plain add/delete unless their blob hashes were already identical.
681pub fn content_similarity(old: &[u8], new: &[u8]) -> f64 {
682    if old.is_empty() || new.is_empty() {
683        return 0.0;
684    }
685    const BINARY_SNIFF: usize = 8192;
686    if old.iter().take(BINARY_SNIFF).any(|b| *b == 0)
687        || new.iter().take(BINARY_SNIFF).any(|b| *b == 0)
688    {
689        return 0.0;
690    }
691
692    fn line_hashes(content: &[u8]) -> HashSet<u64> {
693        use std::collections::hash_map::DefaultHasher;
694        use std::hash::{Hash as _, Hasher};
695        content
696            .split(|b| *b == b'\n')
697            .map(|line| {
698                let mut h = DefaultHasher::new();
699                line.hash(&mut h);
700                h.finish()
701            })
702            .collect()
703    }
704
705    let a = line_hashes(old);
706    let b = line_hashes(new);
707    let inter = a.intersection(&b).count();
708    let union = a.len() + b.len() - inter;
709    if union == 0 {
710        0.0
711    } else {
712        inter as f64 / union as f64
713    }
714}
715
716/// Promote Add+Delete pairs in `changes` to Renamed when their contents are
717/// similar enough. `get_content` is called with each candidate's blob hash;
718/// returning `Ok(None)` (missing blob) silently skips that candidate.
719///
720/// Greedy best-similarity-first matching: the highest-scoring pair is locked
721/// in first, then the next non-conflicting pair, and so on. Pairs whose
722/// similarity is below `config.similarity_threshold` are never matched.
723///
724/// Bails out without scanning when the candidate count exceeds
725/// `config.max_candidates` — content-similarity rename detection is O(D*A)
726/// in the candidate counts, and that bound stops a 50 000-file move from
727/// stalling `oak commit`.
728pub fn detect_renames_by_content<F>(
729    changes: &mut Vec<FileChange>,
730    mut get_content: F,
731    config: &RenameConfig,
732) -> Result<()>
733where
734    F: FnMut(&Hash) -> Result<Option<Vec<u8>>>,
735{
736    let mut deleted_idxs: Vec<usize> = Vec::new();
737    let mut added_idxs: Vec<usize> = Vec::new();
738    for (i, c) in changes.iter().enumerate() {
739        match c.change_type {
740            ChangeType::Deleted => deleted_idxs.push(i),
741            ChangeType::Added => added_idxs.push(i),
742            _ => {}
743        }
744    }
745    if deleted_idxs.is_empty() || added_idxs.is_empty() {
746        return Ok(());
747    }
748    if deleted_idxs.len() + added_idxs.len() > config.max_candidates {
749        return Ok(());
750    }
751
752    let max_bytes = config.max_file_bytes;
753
754    fn fetch_for<F>(
755        idx: usize,
756        hash: Option<&Hash>,
757        max_bytes: usize,
758        get_content: &mut F,
759    ) -> Result<Option<(usize, Hash, Vec<u8>)>>
760    where
761        F: FnMut(&Hash) -> Result<Option<Vec<u8>>>,
762    {
763        let Some(h) = hash else { return Ok(None) };
764        let Some(bytes) = get_content(h)? else {
765            return Ok(None);
766        };
767        if bytes.len() > max_bytes {
768            return Ok(None);
769        }
770        Ok(Some((idx, h.clone(), bytes)))
771    }
772
773    let mut del_contents: Vec<(usize, Hash, Vec<u8>)> = Vec::new();
774    for &di in &deleted_idxs {
775        if let Some(entry) = fetch_for(
776            di,
777            changes[di].old_blob_hash.as_ref(),
778            max_bytes,
779            &mut get_content,
780        )? {
781            del_contents.push(entry);
782        }
783    }
784    let mut add_contents: Vec<(usize, Hash, Vec<u8>)> = Vec::new();
785    for &ai in &added_idxs {
786        if let Some(entry) = fetch_for(
787            ai,
788            changes[ai].new_blob_hash.as_ref(),
789            max_bytes,
790            &mut get_content,
791        )? {
792            add_contents.push(entry);
793        }
794    }
795
796    let mut scores: Vec<(usize, usize, f64)> = Vec::new();
797    for (di, _, del_bytes) in &del_contents {
798        for (ai, _, add_bytes) in &add_contents {
799            let s = content_similarity(del_bytes, add_bytes);
800            if s >= config.similarity_threshold {
801                scores.push((*di, *ai, s));
802            }
803        }
804    }
805    scores.sort_by(|a, b| b.2.partial_cmp(&a.2).unwrap_or(std::cmp::Ordering::Equal));
806
807    let mut used_del: HashSet<usize> = HashSet::new();
808    let mut used_add: HashSet<usize> = HashSet::new();
809    let mut renames: Vec<FileChange> = Vec::new();
810    for (di, ai, _) in &scores {
811        if used_del.contains(di) || used_add.contains(ai) {
812            continue;
813        }
814        let del = &changes[*di];
815        let add = &changes[*ai];
816        renames.push(FileChange {
817            path: add.path.clone(),
818            change_type: ChangeType::Renamed,
819            old_blob_hash: del.old_blob_hash.clone(),
820            new_blob_hash: add.new_blob_hash.clone(),
821            old_path: Some(del.path.clone()),
822            old_mode: del.old_mode,
823            new_mode: add.new_mode,
824        });
825        used_del.insert(*di);
826        used_add.insert(*ai);
827    }
828
829    if renames.is_empty() {
830        return Ok(());
831    }
832
833    let to_drop: HashSet<usize> = used_del.iter().chain(used_add.iter()).cloned().collect();
834    let kept: Vec<FileChange> = std::mem::take(changes)
835        .into_iter()
836        .enumerate()
837        .filter_map(|(i, c)| if to_drop.contains(&i) { None } else { Some(c) })
838        .collect();
839    *changes = kept;
840    changes.extend(renames);
841    changes.sort_by(|a, b| a.path.cmp(&b.path));
842    Ok(())
843}
844
845/// A commit within a branch.
846///
847/// # Commit messages and the new model
848///
849/// As of the "branch descriptions are the source of truth" refactor, commit
850/// messages no longer exist for local commits or feature-branch commits on
851/// the server. The `message` field is `Some(_)` only for commits on `main`
852/// that were produced by a squash-merge — and in that case the message is
853/// the merged branch's description. Everything else is `None`.
854#[derive(Debug, Clone, Serialize, Deserialize)]
855pub struct Commit {
856    pub hash: Hash,
857    pub branch_name: String,
858    pub parent_hash: Option<Hash>,
859    pub merge_parent_hash: Option<Hash>,
860    pub manifest_hash: Hash,
861    pub author: String,
862    /// `Some(_)` only on main-branch squash-merge commits (where the value is
863    /// the merged branch's description). `None` for every local commit and
864    /// every feature-branch commit on the server.
865    #[serde(default)]
866    pub message: Option<String>,
867    pub timestamp: DateTime<Utc>,
868    pub files: Vec<FileChange>,
869}
870
871impl Commit {
872    /// Create a new commit, computing the hash.
873    ///
874    /// The timestamp is truncated to microsecond precision before hashing.
875    /// The hash preimage embeds `timestamp.to_rfc3339()`, and the
876    /// lowest-precision store a commit row must survive is the server's
877    /// Postgres `TIMESTAMPTZ` (microseconds) — a nanosecond-precision
878    /// timestamp (Linux `Utc::now()`) would hash all nine digits, get
879    /// truncated on store, and leave a row that can never reproduce its own
880    /// hash. See [`Commit::rehydrate_verified`] for how already-stored
881    /// nanosecond-hashed commits are still verified.
882    pub fn new(
883        branch_name: String,
884        parent_hash: Option<Hash>,
885        merge_parent_hash: Option<Hash>,
886        manifest_hash: Hash,
887        author: String,
888        message: Option<String>,
889        files: Vec<FileChange>,
890    ) -> Result<Self> {
891        Self::with_timestamp(
892            branch_name,
893            parent_hash,
894            merge_parent_hash,
895            manifest_hash,
896            author,
897            message,
898            files,
899            truncate_to_micros(Utc::now()),
900        )
901    }
902
903    /// Create a commit at a specific timestamp (instead of `Utc::now()`).
904    /// Used when replaying commits from another VCS — `oak clone <git-url>`
905    /// imports git history and needs the original commit dates preserved.
906    ///
907    /// The hash preimage joins its fields with `\n` (see
908    /// [`hash_format::hash_commit`]), so branch name and author must be
909    /// `\n`/`\t`/`\0`-free or two distinct commits could hash identically.
910    /// Both are Oak-generated or config values, so rejecting them here never
911    /// refuses previously legal data. The message — the one field that may
912    /// legitimately contain newlines — stays unambiguous because every
913    /// neighboring field is now control-character-free.
914    #[allow(clippy::too_many_arguments)]
915    pub fn with_timestamp(
916        branch_name: String,
917        parent_hash: Option<Hash>,
918        merge_parent_hash: Option<Hash>,
919        manifest_hash: Hash,
920        author: String,
921        message: Option<String>,
922        files: Vec<FileChange>,
923        timestamp: DateTime<Utc>,
924    ) -> Result<Self> {
925        validate_commit_field("branch name", &branch_name)?;
926        validate_commit_field("author", &author)?;
927
928        // `None` message hashes like `Some("")` in v1 — that's part of the
929        // on-the-wire hash derivation. Fine: both represent "no human-written
930        // message," and we don't intentionally produce `Some("")` anywhere.
931        let hash = hash_format::hash_commit(
932            hash_format::HashFormat::V1,
933            &hash_format::CommitFields {
934                branch_name: &branch_name,
935                parent_hash: parent_hash.as_ref(),
936                merge_parent_hash: merge_parent_hash.as_ref(),
937                manifest_hash: &manifest_hash,
938                author: &author,
939                message: message.as_deref(),
940                timestamp: &timestamp,
941                files: &files,
942            },
943        );
944
945        Ok(Commit {
946            hash,
947            branch_name,
948            parent_hash,
949            merge_parent_hash,
950            manifest_hash,
951            author,
952            message,
953            timestamp,
954            files,
955        })
956    }
957
958    /// Reconstruct a commit from stored/wire fields, verifying that the
959    /// fields reproduce `claimed_hash` — with tolerance for
960    /// microsecond-truncated timestamps.
961    ///
962    /// Server-side Postgres stores commit timestamps as `TIMESTAMPTZ`
963    /// (microsecond precision), but every commit created on a
964    /// nanosecond-resolution clock before [`Commit::new`] started truncating
965    /// (every squash-merge the Linux server ever made) hashed all nine
966    /// subsecond digits into its preimage. The stored row therefore can't
967    /// reproduce its own hash from its own fields.
968    ///
969    /// When the exact fields don't reproduce `claimed_hash` and the
970    /// timestamp carries no sub-microsecond digits, this restores each
971    /// possible lost nanosecond tail (`1..=999`) and accepts the one that
972    /// reproduces the claimed hash — recovering, not trusting, the original
973    /// preimage: a match proves the fields are byte-identical to what was
974    /// hashed, minus precision the store dropped. The returned commit
975    /// carries the recovered timestamp, so re-storing it locally yields an
976    /// exactly self-verifying row.
977    ///
978    /// A second legacy class is also tolerated: commits hashed before
979    /// `merge_parent_hash` entered the v1 preimage verify against the frozen
980    /// 6-field preimage ([`hash_format::hash_commit_v1_pre_merge_parent`]),
981    /// strictly gated on the commit having no merge parent.
982    #[allow(clippy::too_many_arguments)]
983    pub fn rehydrate_verified(
984        claimed_hash: &Hash,
985        branch_name: String,
986        parent_hash: Option<Hash>,
987        merge_parent_hash: Option<Hash>,
988        manifest_hash: Hash,
989        author: String,
990        message: Option<String>,
991        files: Vec<FileChange>,
992        timestamp: DateTime<Utc>,
993    ) -> Result<Self> {
994        validate_commit_field("branch name", &branch_name)?;
995        validate_commit_field("author", &author)?;
996
997        let fields = hash_format::CommitFields {
998            branch_name: &branch_name,
999            parent_hash: parent_hash.as_ref(),
1000            merge_parent_hash: merge_parent_hash.as_ref(),
1001            manifest_hash: &manifest_hash,
1002            author: &author,
1003            message: message.as_deref(),
1004            timestamp: &timestamp,
1005            files: &files,
1006        };
1007        let exact = hash_format::hash_commit(hash_format::HashFormat::V1, &fields);
1008
1009        let verified_timestamp = if &exact == claimed_hash {
1010            Some(timestamp)
1011        } else if timestamp.timestamp_subsec_nanos().is_multiple_of(1_000) {
1012            // Microsecond-precision timestamp: try restoring a truncated
1013            // nanosecond tail. ~1000 BLAKE3 hashes of a few hundred bytes —
1014            // well under a millisecond, and only on the mismatch path.
1015            (1..1_000).find_map(|tail| {
1016                let candidate = timestamp + chrono::Duration::nanoseconds(tail);
1017                let hash = hash_format::hash_commit(
1018                    hash_format::HashFormat::V1,
1019                    &hash_format::CommitFields {
1020                        timestamp: &candidate,
1021                        ..fields
1022                    },
1023                );
1024                (&hash == claimed_hash).then_some(candidate)
1025            })
1026        } else {
1027            None
1028        };
1029
1030        // Second legacy class: commits hashed before `merge_parent_hash`
1031        // entered the v1 preimage (~April 2026 and earlier) used a 6-field
1032        // preimage with no merge_parent line at all. Their timestamps
1033        // reproduce exactly, so no nanosecond-tail search is needed here.
1034        //
1035        // Strictly gated on `merge_parent_hash.is_none()`: every commit of
1036        // that era has no merge parent, and the gate removes the only
1037        // theoretical two-preimage ambiguity — a commit *with* a merge
1038        // parent can only ever verify under today's 7-field rule. Accepting
1039        // the 6-field match is safe because both preimages are versions of
1040        // the same trusted v1 scheme over the same fields; a match still
1041        // proves the fields are byte-identical to what was originally
1042        // hashed.
1043        let verified_timestamp = verified_timestamp.or_else(|| {
1044            (merge_parent_hash.is_none()
1045                && &hash_format::hash_commit_v1_pre_merge_parent(&fields) == claimed_hash)
1046                .then_some(timestamp)
1047        });
1048
1049        let Some(timestamp) = verified_timestamp else {
1050            return Err(OakError::InvalidHash(format!(
1051                "commit hash mismatch: peer claimed {claimed_hash}, canonical fields hash to {exact}; {}",
1052                describe_commit_preimage(&fields)
1053            )));
1054        };
1055
1056        Ok(Commit {
1057            hash: claimed_hash.clone(),
1058            branch_name,
1059            parent_hash,
1060            merge_parent_hash,
1061            manifest_hash,
1062            author,
1063            message,
1064            timestamp,
1065            files,
1066        })
1067    }
1068
1069    /// Check that this commit's own fields reproduce its hash, under the
1070    /// same rules as [`Commit::rehydrate_verified`]. Most readers trust rows
1071    /// from the local store; this is the check for those that must not
1072    /// (repair passes, integrity inspection). File rows are not part of the
1073    /// v1 preimage, so they are not cloned into the check.
1074    pub fn verify_fields(&self) -> Result<()> {
1075        Commit::rehydrate_verified(
1076            &self.hash,
1077            self.branch_name.clone(),
1078            self.parent_hash.clone(),
1079            self.merge_parent_hash.clone(),
1080            self.manifest_hash.clone(),
1081            self.author.clone(),
1082            self.message.clone(),
1083            Vec::new(),
1084            self.timestamp,
1085        )
1086        .map(|_| ())
1087    }
1088}
1089
1090/// Diagnostic rendering of the fields a commit-hash check hashed and the
1091/// rules it tried (fb-104), so a mismatch can be attributed to a field
1092/// instead of reported as two opaque hashes. The message is summarized by
1093/// length and digest rather than echoed, keeping the error bounded.
1094fn describe_commit_preimage(fields: &hash_format::CommitFields<'_>) -> String {
1095    let optional = |hash: Option<&Hash>| hash.map_or_else(|| "none".to_string(), Hash::to_string);
1096    let message = match fields.message {
1097        Some(message) => format!(
1098            "{} bytes, blake3 {}",
1099            message.len(),
1100            hash_bytes(message.as_bytes()).short()
1101        ),
1102        None => "none".to_string(),
1103    };
1104    let legacy_rule = if fields.merge_parent_hash.is_none() {
1105        "v1 6-field pre-merge-parent preimage"
1106    } else {
1107        "v1 6-field pre-merge-parent preimage (skipped: commit has a merge parent)"
1108    };
1109    let tail_rule = if fields
1110        .timestamp
1111        .timestamp_subsec_nanos()
1112        .is_multiple_of(1_000)
1113    {
1114        "v1 with restored nanosecond timestamp tails 1..999"
1115    } else {
1116        "v1 nanosecond-tail restoration (skipped: timestamp is not microsecond-truncated)"
1117    };
1118    format!(
1119        "hashed fields: branch_name={:?}, parent={}, merge_parent={}, manifest={}, author={:?}, message=[{message}], timestamp={}; rules tried: v1 7-field preimage, {tail_rule}, {legacy_rule}",
1120        fields.branch_name,
1121        optional(fields.parent_hash),
1122        optional(fields.merge_parent_hash),
1123        fields.manifest_hash,
1124        fields.author,
1125        fields.timestamp.to_rfc3339(),
1126    )
1127}
1128
1129/// Truncate a timestamp to microsecond precision — the precision of the
1130/// lowest-fidelity store a commit row must survive (Postgres `TIMESTAMPTZ`).
1131/// Hash preimages must only ever embed timestamps every store can reproduce.
1132pub fn truncate_to_micros(ts: DateTime<Utc>) -> DateTime<Utc> {
1133    ts - chrono::Duration::nanoseconds((ts.timestamp_subsec_nanos() % 1_000) as i64)
1134}
1135
1136/// Reject control characters in a commit-hash preimage field. The preimage is
1137/// `\n`-joined, so control characters here can make serialized commit metadata
1138/// ambiguous or non-printable. See [`Commit::with_timestamp`].
1139fn validate_commit_field(field: &str, value: &str) -> Result<()> {
1140    if value.chars().any(char::is_control) {
1141        return Err(OakError::InvalidArgument(format!(
1142            "commit {field} {value:?} contains a control character"
1143        )));
1144    }
1145    Ok(())
1146}
1147
1148/// Explicit audit reason recorded when a branch is closed via `oak close`.
1149#[derive(Debug, Clone, PartialEq, Eq)]
1150pub enum CloseReason {
1151    Superseded,
1152    Stale,
1153    Duplicate,
1154    Other(String),
1155}
1156
1157impl CloseReason {
1158    pub fn as_str(&self) -> &str {
1159        match self {
1160            CloseReason::Superseded => "superseded",
1161            CloseReason::Stale => "stale",
1162            CloseReason::Duplicate => "duplicate",
1163            CloseReason::Other(reason) => reason.as_str(),
1164        }
1165    }
1166
1167    pub fn parse(s: &str) -> Result<Self> {
1168        if s.trim() != s || s.is_empty() || s.chars().any(char::is_control) {
1169            return Err(OakError::InvalidArgument(
1170                "close reason cannot be empty, have leading/trailing whitespace, or contain control characters"
1171                    .to_string(),
1172            ));
1173        }
1174        match s {
1175            "superseded" => Ok(CloseReason::Superseded),
1176            "stale" => Ok(CloseReason::Stale),
1177            "duplicate" => Ok(CloseReason::Duplicate),
1178            _ => Ok(CloseReason::Other(s.to_string())),
1179        }
1180    }
1181}
1182
1183impl Serialize for CloseReason {
1184    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
1185    where
1186        S: serde::Serializer,
1187    {
1188        serializer.serialize_str(self.as_str())
1189    }
1190}
1191
1192impl<'de> Deserialize<'de> for CloseReason {
1193    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1194    where
1195        D: serde::Deserializer<'de>,
1196    {
1197        let value = String::deserialize(deserializer)?;
1198        CloseReason::parse(&value).map_err(serde::de::Error::custom)
1199    }
1200}
1201
1202/// Status of a branch
1203#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1204pub enum BranchStatus {
1205    Open,
1206    Closed,
1207}
1208
1209impl BranchStatus {
1210    /// Canonical lowercase name used in DB rows and JSON wire formats.
1211    pub fn as_str(&self) -> &'static str {
1212        match self {
1213            BranchStatus::Open => "open",
1214            BranchStatus::Closed => "closed",
1215        }
1216    }
1217
1218    /// Parse a status string from a DB row or wire payload. Unknown values
1219    /// fall back to `Open` (matching the pre-existing behavior at every
1220    /// storage backend that previously did `_ => Open`).
1221    pub fn from_db_str(s: &str) -> Self {
1222        match s {
1223            "closed" => BranchStatus::Closed,
1224            _ => BranchStatus::Open,
1225        }
1226    }
1227}
1228
1229impl std::fmt::Display for BranchStatus {
1230    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1231        f.write_str(self.as_str())
1232    }
1233}
1234
1235/// A branch (container for commits)
1236#[derive(Debug, Clone, Serialize, Deserialize)]
1237pub struct Branch {
1238    pub name: String,
1239    pub description: Option<String>,
1240    pub parent_branch: Option<String>,
1241    pub status: BranchStatus,
1242    /// User/agent-provided close reason; never inferred from prose.
1243    #[serde(default)]
1244    pub close_reason: Option<CloseReason>,
1245    pub created_at: DateTime<Utc>,
1246}
1247
1248impl Branch {
1249    /// Create a new branch
1250    pub fn new(name: String, description: Option<String>, parent_branch: Option<String>) -> Self {
1251        Branch {
1252            name,
1253            description,
1254            parent_branch,
1255            status: BranchStatus::Open,
1256            close_reason: None,
1257            created_at: Utc::now(),
1258        }
1259    }
1260}
1261
1262/// Stable code for a stored branch row whose metadata cannot be decoded.
1263pub const BRANCH_METADATA_UNREADABLE: &str = "branch_metadata_unreadable";
1264
1265/// A stored branch row that exists but whose metadata cannot be decoded
1266/// (for example a corrupt `created_at`). Listing callers get one of these
1267/// per bad row instead of the whole listing failing (fb-118).
1268#[derive(Debug, Clone, PartialEq, Eq)]
1269pub struct UnreadableBranch {
1270    pub name: String,
1271    /// Raw stored lifecycle status; decodable independently of the bad column.
1272    pub status: BranchStatus,
1273    /// The column that could not be decoded (`created_at`, `close_reason`).
1274    pub column: &'static str,
1275}
1276
1277impl UnreadableBranch {
1278    pub fn code(&self) -> &'static str {
1279        BRANCH_METADATA_UNREADABLE
1280    }
1281
1282    /// The typed error a strict read of this row reports. Names the branch
1283    /// and column only; never echoes the stored value or parser internals.
1284    pub fn to_error(&self) -> OakError {
1285        OakError::Database(format!(
1286            "{}: branch '{}' has an unreadable {} value in local storage",
1287            BRANCH_METADATA_UNREADABLE, self.name, self.column
1288        ))
1289    }
1290}
1291
1292/// Decode a stored branch/tag timestamp.
1293///
1294/// Oak writes RFC 3339, but legacy rows written through the SQLite column
1295/// default (`datetime('now')`, e.g. `2026-01-02 03:04:05`) or by older
1296/// writers use SQLite's space-separated UTC form. Those are unambiguous UTC
1297/// instants and decode losslessly. Anything else returns `None`; callers
1298/// must treat it as unreadable, never as a fabricated time (fb-118).
1299pub fn parse_stored_timestamp(value: &str) -> Option<DateTime<Utc>> {
1300    let value = value.trim();
1301    if let Ok(parsed) = DateTime::parse_from_rfc3339(value) {
1302        return Some(parsed.with_timezone(&Utc));
1303    }
1304    for format in ["%Y-%m-%d %H:%M:%S%.f", "%Y-%m-%dT%H:%M:%S%.f"] {
1305        if let Ok(naive) = chrono::NaiveDateTime::parse_from_str(value, format) {
1306            return Some(naive.and_utc());
1307        }
1308    }
1309    None
1310}
1311
1312/// The repository trunk. Every branch ultimately lands here: a branch either
1313/// parents directly onto the trunk, or is *stacked* on another open branch
1314/// whose chain of parents ends at the trunk (`main <- a <- b`). Stacks land
1315/// bottom-up: when a stacked branch's parent merges (or closes), the server
1316/// restacks it onto the parent's own parent, so it eventually parents onto
1317/// the trunk again.
1318pub const DEFAULT_BRANCH: &str = "main";
1319
1320/// How deep a stack may be (branches between the trunk and the tip,
1321/// inclusive). Bounds parent-chain walks against corrupt or cyclic metadata.
1322pub const MAX_STACK_DEPTH: usize = 32;
1323
1324/// Why a proposed parent is not a legal place to stack a branch.
1325#[derive(Debug, Clone, PartialEq, Eq)]
1326pub enum StackParentError {
1327    /// The parent name is empty.
1328    Empty,
1329    /// A branch can't be its own parent.
1330    SelfParent,
1331    /// The parent branch isn't known.
1332    Missing(String),
1333    /// The parent branch is closed (merged or abandoned).
1334    Closed(String),
1335    /// Following parents from the proposed parent comes back to the branch
1336    /// (or loops), so the stack would never reach the trunk.
1337    Cycle(Vec<String>),
1338    /// The chain is longer than [`MAX_STACK_DEPTH`].
1339    TooDeep,
1340}
1341
1342impl std::fmt::Display for StackParentError {
1343    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1344        match self {
1345            Self::Empty => write!(f, "the parent branch name is empty"),
1346            Self::SelfParent => write!(f, "a branch can't be stacked on itself"),
1347            Self::Missing(p) => write!(f, "parent branch '{p}' doesn't exist"),
1348            Self::Closed(p) => write!(
1349                f,
1350                "parent branch '{p}' is closed; stack on an open branch (or on '{DEFAULT_BRANCH}')"
1351            ),
1352            Self::Cycle(chain) => write!(
1353                f,
1354                "stacking would create a cycle ({}); every stack must end at '{DEFAULT_BRANCH}'",
1355                chain.join(" -> ")
1356            ),
1357            Self::TooDeep => write!(
1358                f,
1359                "the stack would be deeper than {MAX_STACK_DEPTH} branches"
1360            ),
1361        }
1362    }
1363}
1364
1365/// What [`validate_stack_parent`] needs to know about one branch.
1366#[derive(Debug, Clone, PartialEq, Eq)]
1367pub struct StackNode {
1368    pub parent_branch: Option<String>,
1369    pub open: bool,
1370}
1371
1372/// Check that `branch` may be parented onto `parent`.
1373///
1374/// `None` and the trunk are always fine. Otherwise the parent must exist and
1375/// be open, and following parents from it (via `lookup`, which returns `None`
1376/// for an unknown branch) must reach the trunk without revisiting `branch` or
1377/// any other branch. Ancestors above the parent only need to exist; a closed
1378/// ancestor is tolerated because the server restacks its children lazily.
1379pub fn validate_stack_parent(
1380    branch: &str,
1381    parent: Option<&str>,
1382    mut lookup: impl FnMut(&str) -> Option<StackNode>,
1383) -> std::result::Result<(), StackParentError> {
1384    let Some(parent) = parent else {
1385        return Ok(());
1386    };
1387    if parent == DEFAULT_BRANCH {
1388        return Ok(());
1389    }
1390    if parent.is_empty() {
1391        return Err(StackParentError::Empty);
1392    }
1393    if parent == branch {
1394        return Err(StackParentError::SelfParent);
1395    }
1396    let node = lookup(parent).ok_or_else(|| StackParentError::Missing(parent.to_string()))?;
1397    if !node.open {
1398        return Err(StackParentError::Closed(parent.to_string()));
1399    }
1400    let mut chain = vec![branch.to_string(), parent.to_string()];
1401    let mut next = node.parent_branch;
1402    while let Some(name) = next {
1403        if name == DEFAULT_BRANCH {
1404            return Ok(());
1405        }
1406        if chain.contains(&name) {
1407            chain.push(name);
1408            return Err(StackParentError::Cycle(chain));
1409        }
1410        if chain.len() > MAX_STACK_DEPTH {
1411            return Err(StackParentError::TooDeep);
1412        }
1413        chain.push(name.clone());
1414        next = match lookup(&name) {
1415            Some(node) => node.parent_branch,
1416            // An ancestor we can't see (not fetched locally): the server
1417            // validated it when it was pushed. Stop here.
1418            None => return Ok(()),
1419        };
1420    }
1421    Ok(())
1422}
1423
1424/// A single rename event in the server's append-only rename log.
1425/// Returned in pull responses so other clients can replay the rename
1426/// against their local repo before applying new commits.
1427#[derive(Debug, Clone, Serialize, Deserialize)]
1428pub struct BranchRename {
1429    pub id: i64,
1430    pub old_name: String,
1431    pub new_name: String,
1432    pub renamed_at: DateTime<Utc>,
1433}
1434
1435/// Repository metadata key-value pairs
1436#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1437pub enum MetadataKey {
1438    Head,
1439    RemoteUrl,
1440    RepoName,
1441    RepoOwner,
1442    CurrentBranch,
1443    ApiKey,
1444    /// Normalized origin (`scheme://host[:port]`) the repository `ApiKey` was
1445    /// issued by. A repository key is only ever presented to this origin, so
1446    /// retargeting the remote (`oak push -r`, `OAK_REMOTE`, `--remote`) can
1447    /// never ship this checkout's key to another server. Absent on
1448    /// checkouts written by older clients: consumers then bind the key to the
1449    /// stored `RemoteUrl`, and the CLI pins it here before any rewrite of
1450    /// `RemoteUrl`.
1451    ApiKeyOrigin,
1452    LastRenameId,
1453    MainLastCheckedAt,
1454    /// The last verified observation of the remote `main` head:
1455    /// `"<unix_secs> <head-hash>"` (an empty hash when the remote `main` had
1456    /// no head). The head is stored WITH its own timestamp so a reader can
1457    /// tell whether the timestamp still describes the local `main` it is
1458    /// looking at; binaries that predate this key ignore it and keep using
1459    /// `MainLastCheckedAt` alone.
1460    MainLastObservedHead,
1461    /// Non-empty when the last attempted verified fetch of server-owned `main`
1462    /// failed integrity checks. Checkout-free review/diff must not silently use
1463    /// stale local `main` evidence while this is set.
1464    MainLastFetchIntegrityError,
1465    /// The `main` head whose snapshot was last verified to have every blob
1466    /// local. Blobs are never deleted, so a later pull at that head skips the
1467    /// whole-snapshot check, and a pull to a newer head checks only the blobs
1468    /// that changed since this one. Any other head is checked in full.
1469    MainHydratedHead,
1470    /// The root tree hash whose every blob was last verified to be local
1471    /// (no sparse cone, nothing withheld or adjudicated lost). Blobs are never
1472    /// deleted, so status/commit/merge resolving that tree again skip the
1473    /// per-entry presence check. Any other tree is checked in full.
1474    HydratedTree,
1475    /// Repo-level content-addressing format (see [`crate::hash_format`]).
1476    /// Absent means v1; nothing writes this key yet — v2 is prepared but
1477    /// cannot be enabled until an explicit migration ships.
1478    HashFormat,
1479    /// Active sparse-checkout cone: a newline-separated list of path prefixes
1480    /// the working tree is scoped to (see [`crate::sparse`]). Absent or empty
1481    /// means a full (non-sparse) checkout. Written by `oak clone --path` and
1482    /// `oak sparse`.
1483    SparsePaths,
1484    /// The view this checkout holds: a [`ViewSpec`] in canonical form. Its
1485    /// commits are view commits; the CLI sends the view on every request so
1486    /// the server answers in them. Absent means a full checkout. Written by
1487    /// `oak clone ORG/REPO --path DIR` against a server that serves views.
1488    ViewSpec,
1489    /// Blob hashes the server has withheld from this clone because path-based
1490    /// permissions deny the user (newline-separated). Recorded from pull/clone
1491    /// responses so status/commit can tell "restricted, never materialized"
1492    /// apart from a real deletion. A hash that later becomes locally present
1493    /// (access granted, then pulled) is simply ignored by consumers — they
1494    /// check blob absence before treating a path as restricted.
1495    RestrictedBlobs,
1496    /// Blob hashes whose bytes an operator explicitly adjudicated as
1497    /// permanently unavailable legacy content. Kept separate from access
1498    /// restrictions so the repository remains visibly degraded.
1499    KnownLostBlobs,
1500    /// JSON marker `{"branch","parent","deferred_at"}` written by
1501    /// `oak pull --branch-only`: the named branch was refreshed from its
1502    /// remote without converging with its parent. Cleared (set empty) by the
1503    /// next pull that completes the parent sync. Consumers must ignore it
1504    /// when empty, unparseable, or naming a different branch.
1505    ParentSyncDeferred,
1506}
1507
1508impl MetadataKey {
1509    pub fn as_str(&self) -> &'static str {
1510        match self {
1511            MetadataKey::Head => "head",
1512            MetadataKey::RemoteUrl => "remote_url",
1513            MetadataKey::RepoName => "repo_name",
1514            MetadataKey::RepoOwner => "repo_owner",
1515            MetadataKey::CurrentBranch => "current_branch",
1516            MetadataKey::ApiKey => "api_key",
1517            MetadataKey::ApiKeyOrigin => "api_key_origin",
1518            MetadataKey::LastRenameId => "last_rename_id",
1519            MetadataKey::MainLastCheckedAt => "main_last_checked_at",
1520            MetadataKey::MainLastObservedHead => "main_last_observed_head",
1521            MetadataKey::MainLastFetchIntegrityError => "main_last_fetch_integrity_error",
1522            MetadataKey::MainHydratedHead => "main_hydrated_head",
1523            MetadataKey::HydratedTree => "hydrated_tree",
1524            MetadataKey::HashFormat => "hash_format",
1525            MetadataKey::SparsePaths => "sparse_paths",
1526            MetadataKey::ViewSpec => "view_spec",
1527            MetadataKey::RestrictedBlobs => "restricted_blobs",
1528            MetadataKey::KnownLostBlobs => "known_lost_blobs",
1529            MetadataKey::ParentSyncDeferred => "parent_sync_deferred",
1530        }
1531    }
1532}
1533
1534impl std::fmt::Display for MetadataKey {
1535    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1536        write!(f, "{}", self.as_str())
1537    }
1538}
1539
1540#[cfg(test)]
1541mod tests {
1542    use super::*;
1543
1544    fn stack_lookup<'a>(
1545        rows: &'a [(&'a str, Option<&'a str>, bool)],
1546    ) -> impl FnMut(&str) -> Option<StackNode> + 'a {
1547        move |name| {
1548            rows.iter()
1549                .find(|(n, _, _)| *n == name)
1550                .map(|(_, parent, open)| StackNode {
1551                    parent_branch: parent.map(str::to_string),
1552                    open: *open,
1553                })
1554        }
1555    }
1556
1557    #[test]
1558    fn stack_parent_trunk_and_none_always_allowed() {
1559        assert_eq!(validate_stack_parent("b", None, |_| None), Ok(()));
1560        assert_eq!(
1561            validate_stack_parent("b", Some(DEFAULT_BRANCH), |_| None),
1562            Ok(())
1563        );
1564    }
1565
1566    #[test]
1567    fn stack_parent_accepts_open_chain_to_trunk() {
1568        let rows = [("a", Some("main"), true), ("b", Some("a"), true)];
1569        assert_eq!(
1570            validate_stack_parent("c", Some("b"), stack_lookup(&rows)),
1571            Ok(())
1572        );
1573    }
1574
1575    #[test]
1576    fn stack_parent_rejects_bad_parents() {
1577        let rows = [
1578            ("a", Some("main"), true),
1579            ("gone", Some("main"), false),
1580            ("b", Some("a"), true),
1581        ];
1582        assert_eq!(
1583            validate_stack_parent("x", Some(""), stack_lookup(&rows)),
1584            Err(StackParentError::Empty)
1585        );
1586        assert_eq!(
1587            validate_stack_parent("a", Some("a"), stack_lookup(&rows)),
1588            Err(StackParentError::SelfParent)
1589        );
1590        assert_eq!(
1591            validate_stack_parent("x", Some("nope"), stack_lookup(&rows)),
1592            Err(StackParentError::Missing("nope".into()))
1593        );
1594        assert_eq!(
1595            validate_stack_parent("x", Some("gone"), stack_lookup(&rows)),
1596            Err(StackParentError::Closed("gone".into()))
1597        );
1598        // Re-parenting `a` onto its own child `b` loops.
1599        assert!(matches!(
1600            validate_stack_parent("a", Some("b"), stack_lookup(&rows)),
1601            Err(StackParentError::Cycle(_))
1602        ));
1603    }
1604
1605    #[test]
1606    fn stack_parent_rejects_runaway_chains() {
1607        let names: Vec<String> = (0..=MAX_STACK_DEPTH + 1).map(|i| format!("b{i}")).collect();
1608        let rows: Vec<(&str, Option<&str>, bool)> = names
1609            .iter()
1610            .enumerate()
1611            .map(|(i, n)| {
1612                let parent = if i == 0 {
1613                    "main"
1614                } else {
1615                    names[i - 1].as_str()
1616                };
1617                (n.as_str(), Some(parent), true)
1618            })
1619            .collect();
1620        let tip = names.last().unwrap().as_str();
1621        assert_eq!(
1622            validate_stack_parent("new", Some(tip), stack_lookup(&rows)),
1623            Err(StackParentError::TooDeep)
1624        );
1625    }
1626
1627    #[test]
1628    fn test_blob_creation() {
1629        let content = b"hello world".to_vec();
1630        let blob = Blob::new(content.clone());
1631        assert_eq!(blob.content, content);
1632        assert_eq!(blob.size, 11);
1633    }
1634
1635    #[test]
1636    fn test_blob_hash_determinism() {
1637        let blob1 = Blob::from_str("test content");
1638        let blob2 = Blob::from_str("test content");
1639        assert_eq!(blob1.hash, blob2.hash);
1640    }
1641
1642    /// `ensure_empty_blob` reconstructs exactly one blob and never guesses at
1643    /// any other: a hash whose bytes aren't implied by the hash must be left
1644    /// missing so the caller's hard error still fires.
1645    #[cfg(feature = "local-repo")]
1646    #[test]
1647    fn ensure_empty_blob_only_synthesizes_the_empty_blob() {
1648        let dir = tempfile::tempdir().unwrap();
1649        let repo = SqliteRepository::open(&dir.path().join("t.db")).unwrap();
1650
1651        let absent = Blob::from_str("bytes only the pusher ever had").hash;
1652        assert!(!ensure_empty_blob(&repo, &absent).unwrap());
1653        assert!(!repo.has_blob(&absent).unwrap());
1654
1655        assert!(ensure_empty_blob(&repo, &Blob::empty_hash()).unwrap());
1656        let stored = repo.get_blob(&Blob::empty_hash()).unwrap().unwrap();
1657        assert_eq!(stored.size, 0);
1658        assert!(stored.content.is_empty());
1659        // Idempotent — a second call is a harmless re-insert, not an error.
1660        assert!(ensure_empty_blob(&repo, &Blob::empty_hash()).unwrap());
1661    }
1662
1663    /// Two empty files in different directories share one blob, so a manifest
1664    /// sweep writes it once and leaves ordinary entries alone.
1665    #[cfg(feature = "local-repo")]
1666    #[test]
1667    fn ensure_empty_blobs_in_manifest_covers_deduped_entries() {
1668        let dir = tempfile::tempdir().unwrap();
1669        let repo = SqliteRepository::open(&dir.path().join("t.db")).unwrap();
1670
1671        let other = Blob::from_str("real content").hash;
1672        let manifest = Manifest::new(vec![
1673            ManifestEntry {
1674                path: "docs/EMPTY".to_string(),
1675                blob_hash: Blob::empty_hash(),
1676                mode: FileMode::Regular,
1677            },
1678            ManifestEntry {
1679                path: "src/EMPTY".to_string(),
1680                blob_hash: Blob::empty_hash(),
1681                mode: FileMode::Regular,
1682            },
1683            ManifestEntry {
1684                path: "README.md".to_string(),
1685                blob_hash: other.clone(),
1686                mode: FileMode::Regular,
1687            },
1688        ]);
1689
1690        ensure_empty_blobs_in_manifest(&repo, &manifest).unwrap();
1691        assert!(repo.has_blob(&Blob::empty_hash()).unwrap());
1692        assert!(
1693            !repo.has_blob(&other).unwrap(),
1694            "only the empty blob is derivable; everything else must stay missing"
1695        );
1696    }
1697
1698    #[test]
1699    fn test_manifest_hash_determinism() {
1700        let entries = vec![
1701            ManifestEntry {
1702                path: "file1.txt".to_string(),
1703                blob_hash: hash_string("content1"),
1704                mode: FileMode::Regular,
1705            },
1706            ManifestEntry {
1707                path: "file2.txt".to_string(),
1708                blob_hash: hash_string("content2"),
1709                mode: FileMode::Regular,
1710            },
1711        ];
1712
1713        let manifest1 = Manifest::new(entries.clone());
1714        let manifest2 = Manifest::new(entries);
1715        assert_eq!(manifest1.hash, manifest2.hash);
1716    }
1717
1718    #[test]
1719    fn test_manifest_diff_added() {
1720        let old = Manifest::empty();
1721        let new = Manifest::new(vec![ManifestEntry {
1722            path: "new.txt".to_string(),
1723            blob_hash: hash_string("content"),
1724            mode: FileMode::Regular,
1725        }]);
1726
1727        let changes = old.diff(&new);
1728        assert_eq!(changes.len(), 1);
1729        assert_eq!(changes[0].change_type, ChangeType::Added);
1730    }
1731
1732    #[test]
1733    fn test_manifest_diff_deleted() {
1734        let old = Manifest::new(vec![ManifestEntry {
1735            path: "old.txt".to_string(),
1736            blob_hash: hash_string("content"),
1737            mode: FileMode::Regular,
1738        }]);
1739        let new = Manifest::empty();
1740
1741        let changes = old.diff(&new);
1742        assert_eq!(changes.len(), 1);
1743        assert_eq!(changes[0].change_type, ChangeType::Deleted);
1744    }
1745
1746    #[test]
1747    fn test_manifest_diff_modified() {
1748        let old = Manifest::new(vec![ManifestEntry {
1749            path: "file.txt".to_string(),
1750            blob_hash: hash_string("old content"),
1751            mode: FileMode::Regular,
1752        }]);
1753        let new = Manifest::new(vec![ManifestEntry {
1754            path: "file.txt".to_string(),
1755            blob_hash: hash_string("new content"),
1756            mode: FileMode::Regular,
1757        }]);
1758
1759        let changes = old.diff(&new);
1760        assert_eq!(changes.len(), 1);
1761        assert_eq!(changes[0].change_type, ChangeType::Modified);
1762    }
1763
1764    #[test]
1765    fn test_commit_creation() {
1766        let commit = Commit::new(
1767            "main".to_string(),
1768            None,
1769            None,
1770            hash_string("manifest"),
1771            "author".to_string(),
1772            Some("test message".to_string()),
1773            vec![],
1774        )
1775        .unwrap();
1776        assert_eq!(commit.branch_name, "main");
1777        assert!(commit.parent_hash.is_none());
1778        assert!(commit.merge_parent_hash.is_none());
1779    }
1780
1781    #[test]
1782    fn test_commit_rejects_control_chars_in_branch_and_author() {
1783        for (branch, author) in [
1784            ("main\nevil", "author"),
1785            ("main\tevil", "author"),
1786            ("main\0evil", "author"),
1787            ("main\u{1b}evil", "author"),
1788            ("main\u{7f}evil", "author"),
1789            ("main", "author\nevil"),
1790            ("main", "author\tevil"),
1791            ("main", "author\0evil"),
1792            ("main", "author\u{1b}evil"),
1793            ("main", "author\u{7f}evil"),
1794        ] {
1795            let err = Commit::new(
1796                branch.to_string(),
1797                None,
1798                None,
1799                hash_string("manifest"),
1800                author.to_string(),
1801                None,
1802                vec![],
1803            )
1804            .unwrap_err();
1805            assert!(
1806                matches!(err, OakError::InvalidArgument(_)),
1807                "({branch:?}, {author:?}) should be rejected, got {err:?}"
1808            );
1809        }
1810        // Multi-line messages stay legal — the message is the one free-form
1811        // field, and its neighbors being control-char-free keeps the
1812        // preimage unambiguous.
1813        assert!(Commit::new(
1814            "main".to_string(),
1815            None,
1816            None,
1817            hash_string("manifest"),
1818            "author".to_string(),
1819            Some("line one\nline two".to_string()),
1820            vec![],
1821        )
1822        .is_ok());
1823    }
1824
1825    /// A pre-merge_parent-era commit (6-field legacy v1 preimage, no merge
1826    /// parent) must rehydrate against its claimed hash — the fix that lets
1827    /// post-verification binaries clone repos rooted in April-2026-era
1828    /// history (e.g. oak/oakspace's root commit f15a1608).
1829    #[test]
1830    fn test_rehydrate_accepts_legacy_pre_merge_parent_preimage() {
1831        let timestamp = chrono::DateTime::parse_from_rfc3339("2026-04-12T09:30:00.123456+00:00")
1832            .unwrap()
1833            .with_timezone(&Utc);
1834        let parent = hash_string("parent commit");
1835        let manifest = hash_string("manifest");
1836
1837        // The frozen 6-field legacy preimage, rendered by hand so the test
1838        // pins the byte format independently of the production hasher.
1839        let legacy_preimage = format!(
1840            "main\n{}\n{}\nauthor@example.com\na legacy commit\n{}",
1841            parent,
1842            manifest,
1843            timestamp.to_rfc3339()
1844        );
1845        let claimed = hash_bytes(legacy_preimage.as_bytes());
1846        assert_eq!(
1847            claimed,
1848            hash_format::hash_commit_v1_pre_merge_parent(&hash_format::CommitFields {
1849                branch_name: "main",
1850                parent_hash: Some(&parent),
1851                merge_parent_hash: None,
1852                manifest_hash: &manifest,
1853                author: "author@example.com",
1854                message: Some("a legacy commit"),
1855                timestamp: &timestamp,
1856                files: &[],
1857            }),
1858            "legacy hasher must reproduce the hand-rendered 6-field preimage"
1859        );
1860
1861        // No merge parent → accepted, claimed hash and timestamp preserved.
1862        let commit = Commit::rehydrate_verified(
1863            &claimed,
1864            "main".to_string(),
1865            Some(parent.clone()),
1866            None,
1867            manifest.clone(),
1868            "author@example.com".to_string(),
1869            Some("a legacy commit".to_string()),
1870            vec![],
1871            timestamp,
1872        )
1873        .expect("legacy 6-field commit without merge parent must verify");
1874        assert_eq!(commit.hash, claimed);
1875        assert_eq!(commit.timestamp, timestamp);
1876
1877        // With a merge parent the legacy path is gated off: the same claimed
1878        // hash must be rejected even though the 6-field render ignores the
1879        // merge parent entirely.
1880        let err = Commit::rehydrate_verified(
1881            &claimed,
1882            "main".to_string(),
1883            Some(parent.clone()),
1884            Some(hash_string("merge parent")),
1885            manifest.clone(),
1886            "author@example.com".to_string(),
1887            Some("a legacy commit".to_string()),
1888            vec![],
1889            timestamp,
1890        )
1891        .expect_err("legacy preimage must not verify a commit with a merge parent");
1892        assert!(
1893            matches!(&err, OakError::InvalidHash(m) if m.contains("commit hash mismatch")),
1894            "expected a commit hash mismatch, got {err:?}"
1895        );
1896
1897        // A claimed hash matching neither preimage is still rejected.
1898        let err = Commit::rehydrate_verified(
1899            &hash_string("some unrelated hash"),
1900            "main".to_string(),
1901            Some(parent.clone()),
1902            None,
1903            manifest.clone(),
1904            "author@example.com".to_string(),
1905            Some("a legacy commit".to_string()),
1906            vec![],
1907            timestamp,
1908        )
1909        .expect_err("a hash matching neither preimage must be rejected");
1910        assert!(
1911            matches!(&err, OakError::InvalidHash(m) if m.contains("commit hash mismatch")),
1912            "expected a commit hash mismatch, got {err:?}"
1913        );
1914        // fb-104: the mismatch names the hashed field values and the rules
1915        // tried, but never echoes the message body.
1916        let OakError::InvalidHash(message) = &err else {
1917            unreachable!()
1918        };
1919        for expected in [
1920            "branch_name=\"main\"".to_string(),
1921            "author=\"author@example.com\"".to_string(),
1922            format!("parent={parent}"),
1923            "merge_parent=none".to_string(),
1924            format!("manifest={manifest}"),
1925            format!("timestamp={}", timestamp.to_rfc3339()),
1926            "message=[15 bytes, blake3 ".to_string(),
1927            "rules tried: v1 7-field preimage".to_string(),
1928            "v1 6-field pre-merge-parent preimage".to_string(),
1929        ] {
1930            assert!(
1931                message.contains(&expected),
1932                "missing {expected:?} in {message}"
1933            );
1934        }
1935        assert!(!message.contains("a legacy commit"), "{message}");
1936    }
1937
1938    #[test]
1939    fn test_branch_creation() {
1940        let br = Branch::new("feature-x".to_string(), Some("A feature".to_string()), None);
1941        assert_eq!(br.name, "feature-x");
1942        assert_eq!(br.status, BranchStatus::Open);
1943        assert!(br.parent_branch.is_none());
1944    }
1945
1946    #[test]
1947    fn test_manifest_diff_no_changes() {
1948        let entries = vec![ManifestEntry {
1949            path: "file.txt".to_string(),
1950            blob_hash: hash_string("content"),
1951            mode: FileMode::Regular,
1952        }];
1953        let m1 = Manifest::new(entries.clone());
1954        let m2 = Manifest::new(entries);
1955        let changes = m1.diff(&m2);
1956        assert!(changes.is_empty());
1957    }
1958
1959    #[test]
1960    fn test_manifest_diff_multiple_changes() {
1961        let old = Manifest::new(vec![
1962            ManifestEntry {
1963                path: "a.txt".to_string(),
1964                blob_hash: hash_string("a"),
1965                mode: FileMode::Regular,
1966            },
1967            ManifestEntry {
1968                path: "b.txt".to_string(),
1969                blob_hash: hash_string("b"),
1970                mode: FileMode::Regular,
1971            },
1972        ]);
1973        let new = Manifest::new(vec![
1974            ManifestEntry {
1975                path: "b.txt".to_string(),
1976                blob_hash: hash_string("b_modified"),
1977                mode: FileMode::Regular,
1978            },
1979            ManifestEntry {
1980                path: "c.txt".to_string(),
1981                blob_hash: hash_string("c"),
1982                mode: FileMode::Regular,
1983            },
1984        ]);
1985        let changes = old.diff(&new);
1986        assert_eq!(changes.len(), 3);
1987        // a.txt deleted, b.txt modified, c.txt added
1988        assert!(changes
1989            .iter()
1990            .any(|c| c.path == "a.txt" && c.change_type == ChangeType::Deleted));
1991        assert!(changes
1992            .iter()
1993            .any(|c| c.path == "b.txt" && c.change_type == ChangeType::Modified));
1994        assert!(changes
1995            .iter()
1996            .any(|c| c.path == "c.txt" && c.change_type == ChangeType::Added));
1997    }
1998
1999    #[test]
2000    fn test_manifest_diff_mode_only_change() {
2001        let hash = hash_string("content");
2002        let old = Manifest::new(vec![ManifestEntry {
2003            path: "script.sh".to_string(),
2004            blob_hash: hash.clone(),
2005            mode: FileMode::Regular,
2006        }]);
2007        let new = Manifest::new(vec![ManifestEntry {
2008            path: "script.sh".to_string(),
2009            blob_hash: hash.clone(),
2010            mode: FileMode::Executable,
2011        }]);
2012        let changes = old.diff(&new);
2013        assert_eq!(changes.len(), 1);
2014        assert_eq!(changes[0].path, "script.sh");
2015        assert_eq!(changes[0].change_type, ChangeType::Modified);
2016        assert_eq!(changes[0].old_blob_hash, Some(hash.clone()));
2017        assert_eq!(changes[0].new_blob_hash, Some(hash));
2018    }
2019
2020    #[test]
2021    fn test_filemode_default() {
2022        let mode: FileMode = Default::default();
2023        assert_eq!(mode, FileMode::Regular);
2024    }
2025
2026    #[test]
2027    fn test_metadata_key_as_str() {
2028        assert_eq!(MetadataKey::Head.as_str(), "head");
2029        assert_eq!(MetadataKey::RemoteUrl.as_str(), "remote_url");
2030        assert_eq!(MetadataKey::RepoName.as_str(), "repo_name");
2031        assert_eq!(MetadataKey::CurrentBranch.as_str(), "current_branch");
2032        assert_eq!(MetadataKey::ApiKey.as_str(), "api_key");
2033        assert_eq!(
2034            MetadataKey::MainLastCheckedAt.as_str(),
2035            "main_last_checked_at"
2036        );
2037        assert_eq!(
2038            MetadataKey::MainLastObservedHead.as_str(),
2039            "main_last_observed_head"
2040        );
2041        assert_eq!(
2042            MetadataKey::MainLastFetchIntegrityError.as_str(),
2043            "main_last_fetch_integrity_error"
2044        );
2045        assert_eq!(MetadataKey::RestrictedBlobs.as_str(), "restricted_blobs");
2046        assert_eq!(MetadataKey::KnownLostBlobs.as_str(), "known_lost_blobs");
2047    }
2048
2049    #[test]
2050    fn test_metadata_key_display() {
2051        assert_eq!(MetadataKey::Head.to_string(), "head");
2052    }
2053
2054    #[test]
2055    fn test_change_type_display() {
2056        assert_eq!(ChangeType::Added.to_string(), "A");
2057        assert_eq!(ChangeType::Modified.to_string(), "M");
2058        assert_eq!(ChangeType::Deleted.to_string(), "D");
2059        assert_eq!(ChangeType::Renamed.to_string(), "R");
2060    }
2061
2062    #[test]
2063    fn test_branch_status_display() {
2064        assert_eq!(BranchStatus::Open.to_string(), "open");
2065        assert_eq!(BranchStatus::Closed.to_string(), "closed");
2066    }
2067
2068    #[test]
2069    fn test_manifest_get() {
2070        let hash = hash_string("content");
2071        let manifest = Manifest::new(vec![ManifestEntry {
2072            path: "file.txt".to_string(),
2073            blob_hash: hash.clone(),
2074            mode: FileMode::Regular,
2075        }]);
2076        assert!(manifest.get("file.txt").is_some());
2077        assert!(manifest.get("nonexistent.txt").is_none());
2078    }
2079
2080    #[test]
2081    fn test_manifest_empty() {
2082        let empty = Manifest::empty();
2083        assert!(empty.entries.is_empty());
2084    }
2085
2086    #[test]
2087    fn test_blob_from_string() {
2088        let blob = Blob::from_string("hello");
2089        assert_eq!(blob.content, b"hello");
2090        assert_eq!(blob.size, 5);
2091    }
2092
2093    #[test]
2094    fn test_manifest_diff_exact_rename() {
2095        let content_hash = hash_string("same content");
2096        let old = Manifest::new(vec![ManifestEntry {
2097            path: "old_name.txt".to_string(),
2098            blob_hash: content_hash.clone(),
2099            mode: FileMode::Regular,
2100        }]);
2101        let new = Manifest::new(vec![ManifestEntry {
2102            path: "new_name.txt".to_string(),
2103            blob_hash: content_hash,
2104            mode: FileMode::Regular,
2105        }]);
2106
2107        let changes = old.diff(&new);
2108        assert_eq!(changes.len(), 1);
2109        assert_eq!(changes[0].change_type, ChangeType::Renamed);
2110        assert_eq!(changes[0].path, "new_name.txt");
2111        assert_eq!(changes[0].old_path.as_deref(), Some("old_name.txt"));
2112    }
2113
2114    #[test]
2115    fn test_manifest_diff_only_exact_renames() {
2116        // Manifest-level diff only catches identical-hash renames.
2117        // Content-similarity rename detection lives in detect_renames_by_content.
2118        let old = Manifest::new(vec![ManifestEntry {
2119            path: "src/player.rs".to_string(),
2120            blob_hash: hash_string("old code"),
2121            mode: FileMode::Regular,
2122        }]);
2123        let new = Manifest::new(vec![ManifestEntry {
2124            path: "lib/player.rs".to_string(),
2125            blob_hash: hash_string("new code"),
2126            mode: FileMode::Regular,
2127        }]);
2128
2129        let changes = old.diff(&new);
2130        assert_eq!(changes.len(), 2);
2131        assert!(changes.iter().any(|c| c.change_type == ChangeType::Deleted));
2132        assert!(changes.iter().any(|c| c.change_type == ChangeType::Added));
2133    }
2134
2135    #[test]
2136    fn test_manifest_diff_exact_renames_with_duplicate_hashes() {
2137        let shared = hash_string("same content");
2138        let old = Manifest::new(vec![
2139            ManifestEntry {
2140                path: "old/a.txt".to_string(),
2141                blob_hash: shared.clone(),
2142                mode: FileMode::Regular,
2143            },
2144            ManifestEntry {
2145                path: "old/b.txt".to_string(),
2146                blob_hash: shared.clone(),
2147                mode: FileMode::Executable,
2148            },
2149            ManifestEntry {
2150                path: "old/deleted.txt".to_string(),
2151                blob_hash: hash_string("deleted"),
2152                mode: FileMode::Regular,
2153            },
2154        ]);
2155        let new = Manifest::new(vec![
2156            ManifestEntry {
2157                path: "new/a.txt".to_string(),
2158                blob_hash: shared.clone(),
2159                mode: FileMode::Regular,
2160            },
2161            ManifestEntry {
2162                path: "new/b.txt".to_string(),
2163                blob_hash: shared,
2164                mode: FileMode::Regular,
2165            },
2166            ManifestEntry {
2167                path: "new/added.txt".to_string(),
2168                blob_hash: hash_string("added"),
2169                mode: FileMode::Regular,
2170            },
2171        ]);
2172
2173        let changes = old.diff(&new);
2174        assert_eq!(changes.len(), 4);
2175        assert_eq!(
2176            changes
2177                .iter()
2178                .filter(|c| c.change_type == ChangeType::Renamed)
2179                .count(),
2180            2
2181        );
2182        assert!(changes
2183            .iter()
2184            .any(|c| c.path == "old/deleted.txt" && c.change_type == ChangeType::Deleted));
2185        assert!(changes
2186            .iter()
2187            .any(|c| c.path == "new/added.txt" && c.change_type == ChangeType::Added));
2188    }
2189
2190    #[test]
2191    fn test_manifest_diff_entries_matches_manifest_diff_without_new_manifest() {
2192        let unchanged = hash_string("unchanged");
2193        let edited_old = hash_string("old");
2194        let edited_new = hash_string("new");
2195        let renamed = hash_string("renamed");
2196        let old = Manifest::new(vec![
2197            ManifestEntry {
2198                path: "a.txt".to_string(),
2199                blob_hash: unchanged.clone(),
2200                mode: FileMode::Regular,
2201            },
2202            ManifestEntry {
2203                path: "b.txt".to_string(),
2204                blob_hash: edited_old,
2205                mode: FileMode::Regular,
2206            },
2207            ManifestEntry {
2208                path: "gone.txt".to_string(),
2209                blob_hash: hash_string("gone"),
2210                mode: FileMode::Regular,
2211            },
2212            ManifestEntry {
2213                path: "old-name.txt".to_string(),
2214                blob_hash: renamed.clone(),
2215                mode: FileMode::Regular,
2216            },
2217        ]);
2218        let scanned_entries = vec![
2219            ManifestEntry {
2220                path: "new-name.txt".to_string(),
2221                blob_hash: renamed,
2222                mode: FileMode::Regular,
2223            },
2224            ManifestEntry {
2225                path: "added.txt".to_string(),
2226                blob_hash: hash_string("added"),
2227                mode: FileMode::Regular,
2228            },
2229            ManifestEntry {
2230                path: "b.txt".to_string(),
2231                blob_hash: edited_new,
2232                mode: FileMode::Regular,
2233            },
2234            ManifestEntry {
2235                path: "a.txt".to_string(),
2236                blob_hash: unchanged,
2237                mode: FileMode::Regular,
2238            },
2239        ];
2240        let new = Manifest::new(scanned_entries.clone());
2241
2242        let expected = old.diff(&new);
2243        let actual = old.diff_entries_with_renames(&scanned_entries);
2244        assert_eq!(
2245            expected
2246                .iter()
2247                .map(|c| (&c.path, c.change_type, c.old_path.as_deref()))
2248                .collect::<Vec<_>>(),
2249            actual
2250                .iter()
2251                .map(|c| (&c.path, c.change_type, c.old_path.as_deref()))
2252                .collect::<Vec<_>>()
2253        );
2254    }
2255
2256    #[test]
2257    fn test_content_similarity_identical() {
2258        let bytes = b"line one\nline two\nline three";
2259        assert!((content_similarity(bytes, bytes) - 1.0).abs() < 1e-9);
2260    }
2261
2262    #[test]
2263    fn test_content_similarity_partial_overlap() {
2264        let old = b"line one\nline two\nline three\nline four";
2265        let new = b"line one\nline two\nline three\nline five";
2266        // 3 shared lines, 5 unique lines total -> 3/5 = 0.6
2267        let s = content_similarity(old, new);
2268        assert!((s - 0.6).abs() < 1e-9, "got {s}");
2269    }
2270
2271    #[test]
2272    fn test_content_similarity_disjoint() {
2273        let old = b"alpha\nbeta\ngamma";
2274        let new = b"one\ntwo\nthree";
2275        assert_eq!(content_similarity(old, new), 0.0);
2276    }
2277
2278    #[test]
2279    fn test_content_similarity_binary_returns_zero() {
2280        // NUL byte in input -> treated as binary -> 0.0
2281        let old = b"some\0binary";
2282        let new = b"some\0binary";
2283        assert_eq!(content_similarity(old, new), 0.0);
2284    }
2285
2286    #[test]
2287    fn test_content_similarity_empty_returns_zero() {
2288        assert_eq!(content_similarity(b"", b"anything"), 0.0);
2289        assert_eq!(content_similarity(b"anything", b""), 0.0);
2290    }
2291
2292    #[test]
2293    fn test_detect_renames_by_content_promotes_pair() {
2294        let del_hash = hash_string("old code");
2295        let add_hash = hash_string("edited code");
2296        let mut changes = vec![
2297            FileChange {
2298                path: "src/foo.rs".to_string(),
2299                change_type: ChangeType::Deleted,
2300                old_blob_hash: Some(del_hash.clone()),
2301                new_blob_hash: None,
2302                old_path: None,
2303                old_mode: None,
2304                new_mode: None,
2305            },
2306            FileChange {
2307                path: "lib/foo.rs".to_string(),
2308                change_type: ChangeType::Added,
2309                old_blob_hash: None,
2310                new_blob_hash: Some(add_hash.clone()),
2311                old_path: None,
2312                old_mode: None,
2313                new_mode: None,
2314            },
2315        ];
2316
2317        // Old has 4 lines; new shares 3 of them (60% Jaccard) → above 0.5 default.
2318        let del_bytes = b"alpha\nbeta\ngamma\ndelta".to_vec();
2319        let add_bytes = b"alpha\nbeta\ngamma\nepsilon".to_vec();
2320
2321        let get_content = |h: &Hash| -> Result<Option<Vec<u8>>> {
2322            if *h == del_hash {
2323                Ok(Some(del_bytes.clone()))
2324            } else if *h == add_hash {
2325                Ok(Some(add_bytes.clone()))
2326            } else {
2327                Ok(None)
2328            }
2329        };
2330
2331        detect_renames_by_content(&mut changes, get_content, &RenameConfig::default()).unwrap();
2332
2333        assert_eq!(changes.len(), 1);
2334        assert_eq!(changes[0].change_type, ChangeType::Renamed);
2335        assert_eq!(changes[0].path, "lib/foo.rs");
2336        assert_eq!(changes[0].old_path.as_deref(), Some("src/foo.rs"));
2337    }
2338
2339    #[test]
2340    fn test_detect_renames_by_content_skips_dissimilar() {
2341        let del_hash = hash_string("a");
2342        let add_hash = hash_string("b");
2343        let mut changes = vec![
2344            FileChange {
2345                path: "old.rs".to_string(),
2346                change_type: ChangeType::Deleted,
2347                old_blob_hash: Some(del_hash.clone()),
2348                new_blob_hash: None,
2349                old_path: None,
2350                old_mode: None,
2351                new_mode: None,
2352            },
2353            FileChange {
2354                path: "new.rs".to_string(),
2355                change_type: ChangeType::Added,
2356                old_blob_hash: None,
2357                new_blob_hash: Some(add_hash.clone()),
2358                old_path: None,
2359                old_mode: None,
2360                new_mode: None,
2361            },
2362        ];
2363
2364        let get_content = |h: &Hash| -> Result<Option<Vec<u8>>> {
2365            if *h == del_hash {
2366                Ok(Some(b"one\ntwo\nthree".to_vec()))
2367            } else {
2368                Ok(Some(b"forty\nfifty\nsixty".to_vec()))
2369            }
2370        };
2371
2372        detect_renames_by_content(&mut changes, get_content, &RenameConfig::default()).unwrap();
2373
2374        // Below threshold — original Added/Deleted pair preserved.
2375        assert_eq!(changes.len(), 2);
2376        assert!(changes.iter().any(|c| c.change_type == ChangeType::Added));
2377        assert!(changes.iter().any(|c| c.change_type == ChangeType::Deleted));
2378    }
2379
2380    #[test]
2381    fn test_detect_renames_by_content_greedy_best_match() {
2382        // Two adds, one delete. The add with higher similarity should win.
2383        let del_hash = hash_string("d");
2384        let add_hash_high = hash_string("ah");
2385        let add_hash_low = hash_string("al");
2386        let mut changes = vec![
2387            FileChange {
2388                path: "src/lib.rs".to_string(),
2389                change_type: ChangeType::Deleted,
2390                old_blob_hash: Some(del_hash.clone()),
2391                new_blob_hash: None,
2392                old_path: None,
2393                old_mode: None,
2394                new_mode: None,
2395            },
2396            FileChange {
2397                path: "src/match_high.rs".to_string(),
2398                change_type: ChangeType::Added,
2399                old_blob_hash: None,
2400                new_blob_hash: Some(add_hash_high.clone()),
2401                old_path: None,
2402                old_mode: None,
2403                new_mode: None,
2404            },
2405            FileChange {
2406                path: "src/match_low.rs".to_string(),
2407                change_type: ChangeType::Added,
2408                old_blob_hash: None,
2409                new_blob_hash: Some(add_hash_low.clone()),
2410                old_path: None,
2411                old_mode: None,
2412                new_mode: None,
2413            },
2414        ];
2415
2416        let get_content = |h: &Hash| -> Result<Option<Vec<u8>>> {
2417            if *h == del_hash {
2418                Ok(Some(b"a\nb\nc\nd".to_vec()))
2419            } else if *h == add_hash_high {
2420                Ok(Some(b"a\nb\nc\nz".to_vec())) // 3/5 = 0.6
2421            } else {
2422                Ok(Some(b"a\nx\ny\nz".to_vec())) // 1/7 ≈ 0.14
2423            }
2424        };
2425
2426        detect_renames_by_content(&mut changes, get_content, &RenameConfig::default()).unwrap();
2427
2428        // The high-similarity add gets paired as Renamed; the low one stays Added.
2429        let renamed: Vec<_> = changes
2430            .iter()
2431            .filter(|c| c.change_type == ChangeType::Renamed)
2432            .collect();
2433        assert_eq!(renamed.len(), 1);
2434        assert_eq!(renamed[0].path, "src/match_high.rs");
2435        assert!(changes
2436            .iter()
2437            .any(|c| c.path == "src/match_low.rs" && c.change_type == ChangeType::Added));
2438    }
2439
2440    #[test]
2441    fn test_detect_renames_by_content_respects_max_candidates() {
2442        // With max_candidates = 1, pass refuses to run when D + A > 1.
2443        let del_hash = hash_string("d");
2444        let add_hash = hash_string("a");
2445        let mut changes = vec![
2446            FileChange {
2447                path: "old.rs".to_string(),
2448                change_type: ChangeType::Deleted,
2449                old_blob_hash: Some(del_hash.clone()),
2450                new_blob_hash: None,
2451                old_path: None,
2452                old_mode: None,
2453                new_mode: None,
2454            },
2455            FileChange {
2456                path: "new.rs".to_string(),
2457                change_type: ChangeType::Added,
2458                old_blob_hash: None,
2459                new_blob_hash: Some(add_hash.clone()),
2460                old_path: None,
2461                old_mode: None,
2462                new_mode: None,
2463            },
2464        ];
2465
2466        let get_content =
2467            |_: &Hash| -> Result<Option<Vec<u8>>> { Ok(Some(b"a\nb\nc\nd\ne".to_vec())) };
2468
2469        let config = RenameConfig {
2470            max_candidates: 1,
2471            ..RenameConfig::default()
2472        };
2473        detect_renames_by_content(&mut changes, get_content, &config).unwrap();
2474        assert_eq!(changes.len(), 2);
2475        assert!(!changes.iter().any(|c| c.change_type == ChangeType::Renamed));
2476    }
2477
2478    /// Build a manifest from `(path, content)` pairs plus a blob store the
2479    /// content-rename diff can load from.
2480    fn manifest_with_blobs(files: &[(&str, &str)]) -> (Manifest, HashMap<Hash, Vec<u8>>) {
2481        let mut blobs = HashMap::new();
2482        let entries = files
2483            .iter()
2484            .map(|(path, content)| {
2485                let blob_hash = hash_string(content);
2486                blobs.insert(blob_hash.clone(), content.as_bytes().to_vec());
2487                ManifestEntry {
2488                    path: (*path).to_string(),
2489                    blob_hash,
2490                    mode: FileMode::Regular,
2491                }
2492            })
2493            .collect();
2494        (Manifest::new(entries), blobs)
2495    }
2496
2497    fn blob_loader(
2498        blobs: &HashMap<Hash, Vec<u8>>,
2499    ) -> impl FnMut(&Hash) -> Result<Option<Vec<u8>>> + '_ {
2500        move |h: &Hash| Ok(blobs.get(h).cloned())
2501    }
2502
2503    #[test]
2504    fn test_diff_with_content_renames_detects_rename_with_edit() {
2505        // 5 of 6 lines shared -> similarity 5/7 ≈ 0.71, above the 0.5 default.
2506        let (old, mut blobs) = manifest_with_blobs(&[(
2507            "src/old_name.rs",
2508            "line one\nline two\nline three\nline four\nline five\nline six\n",
2509        )]);
2510        let (new, new_blobs) = manifest_with_blobs(&[(
2511            "src/new_name.rs",
2512            "line one\nline two\nline three\nline four\nline five\nline changed\n",
2513        )]);
2514        blobs.extend(new_blobs);
2515
2516        let changes = old
2517            .diff_with_content_renames(&new, blob_loader(&blobs), &RenameConfig::default())
2518            .unwrap();
2519
2520        assert_eq!(changes.len(), 1, "expected one rename, got {changes:?}");
2521        assert_eq!(changes[0].change_type, ChangeType::Renamed);
2522        assert_eq!(changes[0].path, "src/new_name.rs");
2523        assert_eq!(changes[0].old_path.as_deref(), Some("src/old_name.rs"));
2524        assert!(changes[0].old_blob_hash.is_some());
2525        assert!(changes[0].new_blob_hash.is_some());
2526    }
2527
2528    #[test]
2529    fn semantic_manifest_transition_accepts_rename_with_edit() {
2530        let old_hash = hash_bytes(b"before\n");
2531        let new_hash = hash_bytes(b"after\n");
2532        let parent = Manifest::new(vec![ManifestEntry {
2533            path: "old.txt".to_string(),
2534            blob_hash: old_hash.clone(),
2535            mode: FileMode::Regular,
2536        }]);
2537        let current = Manifest::new(vec![ManifestEntry {
2538            path: "new.txt".to_string(),
2539            blob_hash: new_hash.clone(),
2540            mode: FileMode::Executable,
2541        }]);
2542        let changes = vec![FileChange {
2543            path: "new.txt".to_string(),
2544            change_type: ChangeType::Renamed,
2545            old_blob_hash: Some(old_hash),
2546            new_blob_hash: Some(new_hash),
2547            old_path: Some("old.txt".to_string()),
2548            old_mode: Some(FileMode::Regular),
2549            new_mode: Some(FileMode::Executable),
2550        }];
2551
2552        validate_manifest_transition(&parent, &current, &changes)
2553            .expect("rename+edit is one valid representation of the exact transition");
2554    }
2555
2556    #[test]
2557    fn semantic_manifest_transition_accepts_equivalent_delete_and_add() {
2558        let old_hash = hash_bytes(b"before\n");
2559        let new_hash = hash_bytes(b"after\n");
2560        let parent = Manifest::new(vec![ManifestEntry {
2561            path: "old.txt".to_string(),
2562            blob_hash: old_hash.clone(),
2563            mode: FileMode::Regular,
2564        }]);
2565        let current = Manifest::new(vec![ManifestEntry {
2566            path: "new.txt".to_string(),
2567            blob_hash: new_hash.clone(),
2568            mode: FileMode::Regular,
2569        }]);
2570        let changes = vec![
2571            FileChange {
2572                path: "old.txt".to_string(),
2573                change_type: ChangeType::Deleted,
2574                old_blob_hash: Some(old_hash),
2575                new_blob_hash: None,
2576                old_path: None,
2577                old_mode: Some(FileMode::Regular),
2578                new_mode: None,
2579            },
2580            FileChange {
2581                path: "new.txt".to_string(),
2582                change_type: ChangeType::Added,
2583                old_blob_hash: None,
2584                new_blob_hash: Some(new_hash),
2585                old_path: None,
2586                old_mode: None,
2587                new_mode: Some(FileMode::Regular),
2588            },
2589        ];
2590
2591        validate_manifest_transition(&parent, &current, &changes)
2592            .expect("delete+add is an equivalent valid representation");
2593    }
2594
2595    #[test]
2596    fn semantic_manifest_transition_accepts_content_and_mode_modification() {
2597        let old_hash = hash_bytes(b"before\n");
2598        let new_hash = hash_bytes(b"after\n");
2599        let parent = Manifest::new(vec![ManifestEntry {
2600            path: "script".to_string(),
2601            blob_hash: old_hash.clone(),
2602            mode: FileMode::Regular,
2603        }]);
2604        let current = Manifest::new(vec![ManifestEntry {
2605            path: "script".to_string(),
2606            blob_hash: new_hash.clone(),
2607            mode: FileMode::Executable,
2608        }]);
2609        let changes = vec![FileChange {
2610            path: "script".to_string(),
2611            change_type: ChangeType::Modified,
2612            old_blob_hash: Some(old_hash),
2613            new_blob_hash: Some(new_hash),
2614            old_path: None,
2615            old_mode: Some(FileMode::Regular),
2616            new_mode: Some(FileMode::Executable),
2617        }];
2618
2619        validate_manifest_transition(&parent, &current, &changes)
2620            .expect("content+mode modification describes the exact transition");
2621    }
2622
2623    #[test]
2624    fn semantic_manifest_transition_rejects_forged_duplicate_and_incomplete_records() {
2625        let old_hash = hash_bytes(b"before\n");
2626        let new_hash = hash_bytes(b"after\n");
2627        let parent = Manifest::new(vec![ManifestEntry {
2628            path: "file".to_string(),
2629            blob_hash: old_hash.clone(),
2630            mode: FileMode::Regular,
2631        }]);
2632        let current = Manifest::new(vec![ManifestEntry {
2633            path: "file".to_string(),
2634            blob_hash: new_hash.clone(),
2635            mode: FileMode::Executable,
2636        }]);
2637        let valid = FileChange {
2638            path: "file".to_string(),
2639            change_type: ChangeType::Modified,
2640            old_blob_hash: Some(old_hash.clone()),
2641            new_blob_hash: Some(new_hash),
2642            old_path: None,
2643            old_mode: Some(FileMode::Regular),
2644            new_mode: Some(FileMode::Executable),
2645        };
2646
2647        let mut forged = valid.clone();
2648        forged.old_blob_hash = Some(hash_bytes(b"forged"));
2649        assert!(validate_manifest_transition(&parent, &current, &[forged]).is_err());
2650
2651        let mut wrong_mode = valid.clone();
2652        wrong_mode.new_mode = Some(FileMode::Symlink);
2653        assert!(validate_manifest_transition(&parent, &current, &[wrong_mode]).is_err());
2654
2655        assert!(validate_manifest_transition(&parent, &current, &[valid.clone(), valid]).is_err());
2656        assert!(validate_manifest_transition(&parent, &current, &[]).is_err());
2657    }
2658
2659    #[test]
2660    fn semantic_manifest_transition_is_independent_of_overwrite_record_order() {
2661        let a_hash = hash_bytes(b"a\n");
2662        let b_hash = hash_bytes(b"b\n");
2663        let parent = Manifest::new(vec![
2664            ManifestEntry {
2665                path: "a".to_string(),
2666                blob_hash: a_hash.clone(),
2667                mode: FileMode::Regular,
2668            },
2669            ManifestEntry {
2670                path: "b".to_string(),
2671                blob_hash: b_hash.clone(),
2672                mode: FileMode::Regular,
2673            },
2674        ]);
2675        let current = Manifest::new(vec![ManifestEntry {
2676            path: "b".to_string(),
2677            blob_hash: a_hash.clone(),
2678            mode: FileMode::Regular,
2679        }]);
2680        let rename = FileChange {
2681            path: "b".to_string(),
2682            change_type: ChangeType::Renamed,
2683            old_blob_hash: Some(a_hash),
2684            new_blob_hash: Some(current.entries[0].blob_hash.clone()),
2685            old_path: Some("a".to_string()),
2686            old_mode: Some(FileMode::Regular),
2687            new_mode: Some(FileMode::Regular),
2688        };
2689        let delete = FileChange {
2690            path: "b".to_string(),
2691            change_type: ChangeType::Deleted,
2692            old_blob_hash: Some(b_hash),
2693            new_blob_hash: None,
2694            old_path: None,
2695            old_mode: Some(FileMode::Regular),
2696            new_mode: None,
2697        };
2698
2699        validate_manifest_transition(&parent, &current, &[rename.clone(), delete.clone()])
2700            .expect("rename before destination deletion is semantically valid");
2701        validate_manifest_transition(&parent, &current, &[delete, rename])
2702            .expect("reversing the same records must remain valid");
2703    }
2704
2705    #[test]
2706    fn semantic_manifest_transition_accepts_rename_cycle() {
2707        let a_hash = hash_bytes(b"a\n");
2708        let b_hash = hash_bytes(b"b\n");
2709        let parent = Manifest::new(vec![
2710            ManifestEntry {
2711                path: "a".to_string(),
2712                blob_hash: a_hash.clone(),
2713                mode: FileMode::Regular,
2714            },
2715            ManifestEntry {
2716                path: "b".to_string(),
2717                blob_hash: b_hash.clone(),
2718                mode: FileMode::Executable,
2719            },
2720        ]);
2721        let current = Manifest::new(vec![
2722            ManifestEntry {
2723                path: "a".to_string(),
2724                blob_hash: b_hash.clone(),
2725                mode: FileMode::Executable,
2726            },
2727            ManifestEntry {
2728                path: "b".to_string(),
2729                blob_hash: a_hash.clone(),
2730                mode: FileMode::Regular,
2731            },
2732        ]);
2733        let changes = vec![
2734            FileChange {
2735                path: "b".to_string(),
2736                change_type: ChangeType::Renamed,
2737                old_blob_hash: Some(a_hash.clone()),
2738                new_blob_hash: Some(a_hash),
2739                old_path: Some("a".to_string()),
2740                old_mode: Some(FileMode::Regular),
2741                new_mode: Some(FileMode::Regular),
2742            },
2743            FileChange {
2744                path: "a".to_string(),
2745                change_type: ChangeType::Renamed,
2746                old_blob_hash: Some(b_hash.clone()),
2747                new_blob_hash: Some(b_hash),
2748                old_path: Some("b".to_string()),
2749                old_mode: Some(FileMode::Executable),
2750                new_mode: Some(FileMode::Executable),
2751            },
2752        ];
2753
2754        validate_manifest_transition(&parent, &current, &changes)
2755            .expect("a two-path rename cycle is an order-independent transition");
2756    }
2757
2758    #[test]
2759    fn test_diff_with_content_renames_below_threshold_stays_delete_add() {
2760        let (old, mut blobs) =
2761            manifest_with_blobs(&[("a.txt", "alpha\nbeta\ngamma\ndelta\nepsilon\n")]);
2762        let (new, new_blobs) = manifest_with_blobs(&[("b.txt", "one\ntwo\nthree\nfour\nfive\n")]);
2763        blobs.extend(new_blobs);
2764
2765        let changes = old
2766            .diff_with_content_renames(&new, blob_loader(&blobs), &RenameConfig::default())
2767            .unwrap();
2768
2769        assert_eq!(changes.len(), 2, "expected D+A, got {changes:?}");
2770        assert!(changes
2771            .iter()
2772            .any(|c| c.path == "a.txt" && c.change_type == ChangeType::Deleted));
2773        assert!(changes
2774            .iter()
2775            .any(|c| c.path == "b.txt" && c.change_type == ChangeType::Added));
2776    }
2777
2778    #[test]
2779    fn test_diff_with_content_renames_respects_size_cap() {
2780        // Nearly identical contents, but larger than max_file_bytes on both
2781        // sides — the pass must not pair them (and must not need their bytes).
2782        let big_old = "shared line\n".repeat(100);
2783        let big_new = format!("{}{}", "shared line\n".repeat(99), "edited line\n");
2784        let (old, mut blobs) = manifest_with_blobs(&[("old_big.txt", big_old.as_str())]);
2785        let (new, new_blobs) = manifest_with_blobs(&[("new_big.txt", big_new.as_str())]);
2786        blobs.extend(new_blobs);
2787
2788        let config = RenameConfig {
2789            max_file_bytes: 64,
2790            ..RenameConfig::default()
2791        };
2792        let changes = old
2793            .diff_with_content_renames(&new, blob_loader(&blobs), &config)
2794            .unwrap();
2795
2796        assert_eq!(changes.len(), 2, "expected D+A, got {changes:?}");
2797        assert!(!changes.iter().any(|c| c.change_type == ChangeType::Renamed));
2798    }
2799
2800    #[test]
2801    fn test_diff_with_content_renames_respects_max_candidates() {
2802        let (old, mut blobs) = manifest_with_blobs(&[
2803            ("old_a.txt", "a1\na2\na3\na4\n"),
2804            ("old_b.txt", "b1\nb2\nb3\nb4\n"),
2805        ]);
2806        let (new, new_blobs) = manifest_with_blobs(&[
2807            ("new_a.txt", "a1\na2\na3\nedited\n"),
2808            ("new_b.txt", "b1\nb2\nb3\nedited\n"),
2809        ]);
2810        blobs.extend(new_blobs);
2811
2812        // 2 deletes + 2 adds = 4 candidates > 3 -> the content pass bails out.
2813        let config = RenameConfig {
2814            max_candidates: 3,
2815            ..RenameConfig::default()
2816        };
2817        let changes = old
2818            .diff_with_content_renames(&new, blob_loader(&blobs), &config)
2819            .unwrap();
2820
2821        assert_eq!(changes.len(), 4, "expected 2xD + 2xA, got {changes:?}");
2822        assert!(!changes.iter().any(|c| c.change_type == ChangeType::Renamed));
2823
2824        // With the cap lifted, the same pairs are promoted to renames.
2825        let changes = old
2826            .diff_with_content_renames(&new, blob_loader(&blobs), &RenameConfig::default())
2827            .unwrap();
2828        assert_eq!(
2829            changes
2830                .iter()
2831                .filter(|c| c.change_type == ChangeType::Renamed)
2832                .count(),
2833            2,
2834            "expected both pairs renamed, got {changes:?}"
2835        );
2836    }
2837}