Skip to main content

oak_core/
view.rs

1//! Views — pruned, hash-verifiable slices of a repository.
2//!
3//! A **view** is a set of path prefixes to include, minus prefixes to exclude,
4//! plus a few *spine file* names (`AGENTS.md`, `CLAUDE.md`) kept in every
5//! directory on the way down to an included prefix. It is what a partial
6//! clone or mount (`--path DIR`), or a reader who can't see a restricted
7//! subtree, receives.
8//!
9//! Unlike a [`crate::SparseCone`], which withholds blob *content* but ships
10//! every tree, a view **prunes the trees themselves**: out-of-view names are
11//! absent, not just empty. That's possible without weakening hash
12//! verification because the pruned tree is served under its own commit
13//! (a *view commit*, see [`derive_view_commit`]) whose `manifest_hash` is the
14//! pruned root, so the client verifies it like any other commit.
15//!
16//! Pruning is cheap: every directory wholly inside the view keeps its
17//! existing hash, so only the spine directories between the root and each
18//! included prefix are rebuilt — O(depth × prefixes), not O(files).
19//! [`graft_tree`] is the inverse used on push: it splices a view's in-view
20//! content back into the full tree and refuses anything outside the view.
21
22use crate::error::{OakError, Result};
23use crate::hash::{hash_bytes, Hash};
24use crate::sparse::normalize_prefix;
25use crate::tree::{child_path, dir_hash, load_tree, validate_entry_name, validate_tree_path};
26use crate::tree::{BuiltTree, Tree, TreeEntry, TreeEntryKind};
27use crate::{Commit, FileChange};
28use std::collections::{BTreeMap, HashSet};
29
30/// Wire version of view requests (`view_protocol=view_v1`). A server that
31/// doesn't echo it back in `effective_view` doesn't understand views, and the
32/// client falls back to the full-tree protocol.
33pub const VIEW_PROTOCOL: &str = "view_v1";
34
35/// Spine files every view carries by default.
36pub const DEFAULT_SPINE_FILES: [&str; 2] = ["AGENTS.md", "CLAUDE.md"];
37
38/// The message a view commit carries when its source commit also changed
39/// paths the viewer can't read, so the real message could describe them.
40pub const REDACTED_VIEW_MESSAGE: &str = "(also changes paths outside your view)";
41
42/// Does `prefix` cover `path`? The empty prefix (the repo root) covers
43/// everything; otherwise `path` must equal `prefix` or sit beneath it on a
44/// `/` boundary. Both arguments must already be normalized.
45fn prefix_covers(prefix: &str, path: &str) -> bool {
46    prefix.is_empty()
47        || path == prefix
48        || (path.len() > prefix.len()
49            && path.as_bytes()[prefix.len()] == b'/'
50            && path.starts_with(prefix))
51}
52
53/// How much of a directory a view keeps.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55enum DirState {
56    /// Nothing at or below the directory is in view.
57    Outside,
58    /// The whole directory is in view; its hash is reused as-is.
59    Full,
60    /// Some of it is: walk the entries.
61    Partial,
62}
63
64/// A normalized view: included prefixes, excluded prefixes, and spine file
65/// names. Construct with [`ViewSpec::new`]; two specs selecting the same
66/// paths normalize to the same value and the same [`ViewSpec::id`].
67#[derive(Debug, Clone, PartialEq, Eq, Hash)]
68pub struct ViewSpec {
69    /// Sorted, none covered by another include or by an exclude. `""` is the
70    /// whole repo.
71    include: Vec<String>,
72    /// Sorted, each beneath some include, none covered by another exclude.
73    exclude: Vec<String>,
74    /// Sorted, deduplicated basenames.
75    spine_files: Vec<String>,
76}
77
78impl ViewSpec {
79    /// Build a normalized view. Prefixes are normalized like sparse-cone
80    /// prefixes (`/apps/web/` → `apps/web`); `""` (or `/`) includes the whole
81    /// repo. Redundant entries are dropped: an include covered by another
82    /// include or by an exclude, and an exclude that no include reaches or
83    /// that another exclude covers.
84    ///
85    /// Errors on an invalid path, an exclude of the whole repo, a spine name
86    /// that isn't a single path component, or a view left including nothing.
87    pub fn new<I, E, S>(include: I, exclude: E, spine_files: S) -> Result<ViewSpec>
88    where
89        I: IntoIterator,
90        I::Item: AsRef<str>,
91        E: IntoIterator,
92        E::Item: AsRef<str>,
93        S: IntoIterator,
94        S::Item: AsRef<str>,
95    {
96        let include = normalize_all(include)?;
97        let mut exclude = normalize_all(exclude)?;
98        if exclude.iter().any(|e| e.is_empty()) {
99            return Err(OakError::InvalidPath(
100                "a view can't exclude the whole repository".to_string(),
101            ));
102        }
103        exclude = drop_covered(exclude);
104        let include: Vec<String> = drop_covered(
105            include
106                .into_iter()
107                .filter(|i| !exclude.iter().any(|e| prefix_covers(e, i)))
108                .collect(),
109        );
110        if include.is_empty() {
111            return Err(OakError::InvalidPath(
112                "a view must include at least one path".to_string(),
113            ));
114        }
115        exclude.retain(|e| include.iter().any(|i| prefix_covers(i, e)));
116
117        let mut spine: Vec<String> = Vec::new();
118        for name in spine_files {
119            let name = name.as_ref().trim();
120            validate_entry_name(name)?;
121            spine.push(name.to_string());
122        }
123        spine.sort();
124        spine.dedup();
125
126        Ok(ViewSpec {
127            include,
128            exclude,
129            spine_files: spine,
130        })
131    }
132
133    /// The whole repository, with no exclusions or spine files.
134    pub fn full() -> ViewSpec {
135        ViewSpec {
136            include: vec![String::new()],
137            exclude: Vec::new(),
138            spine_files: Vec::new(),
139        }
140    }
141
142    pub fn include(&self) -> &[String] {
143        &self.include
144    }
145
146    pub fn exclude(&self) -> &[String] {
147        &self.exclude
148    }
149
150    pub fn spine_files(&self) -> &[String] {
151        &self.spine_files
152    }
153
154    /// True when the view selects the whole repository.
155    pub fn is_full(&self) -> bool {
156        self.include == [""] && self.exclude.is_empty()
157    }
158
159    /// A new view with this one's includes and spine files plus `other`'s,
160    /// keeping an exclude only where both views excluded it or `other`
161    /// doesn't reach it — the union of what the two views select.
162    pub fn union(&self, other: &ViewSpec) -> Result<ViewSpec> {
163        let exclude = self
164            .exclude
165            .iter()
166            .filter(|e| !other.covers(e))
167            .chain(other.exclude.iter().filter(|e| !self.covers(e)));
168        ViewSpec::new(
169            self.include.iter().chain(&other.include),
170            exclude,
171            self.spine_files.iter().chain(&other.spine_files),
172        )
173    }
174
175    /// The canonical text form: one line per entry, `+prefix` for includes,
176    /// `-prefix` for excludes, `=name` for spine files, in that order. A bare
177    /// `+` includes the whole repo. Round-trips with [`ViewSpec::parse`] and
178    /// is what [`ViewSpec::id`] hashes, so it's also the wire form.
179    pub fn to_canonical(&self) -> String {
180        let mut lines = Vec::new();
181        lines.extend(self.include.iter().map(|p| format!("+{p}")));
182        lines.extend(self.exclude.iter().map(|p| format!("-{p}")));
183        lines.extend(self.spine_files.iter().map(|n| format!("={n}")));
184        lines.join("\n")
185    }
186
187    /// Parse [`ViewSpec::to_canonical`] output (or any hand-written text in
188    /// that shape; blank lines are ignored and the result is normalized).
189    pub fn parse(text: &str) -> Result<ViewSpec> {
190        let (mut include, mut exclude, mut spine) = (Vec::new(), Vec::new(), Vec::new());
191        for line in text.lines().map(str::trim).filter(|l| !l.is_empty()) {
192            let (sigil, rest) = line.split_at(1);
193            match sigil {
194                "+" => include.push(rest),
195                "-" => exclude.push(rest),
196                "=" => spine.push(rest),
197                _ => {
198                    return Err(OakError::InvalidPath(format!(
199                        "view line {line:?} must start with +, - or ="
200                    )))
201                }
202            }
203        }
204        ViewSpec::new(include, exclude, spine)
205    }
206
207    /// A stable identifier for this view: BLAKE3 over a version tag and the
208    /// canonical form.
209    pub fn id(&self) -> Hash {
210        hash_bytes(format!("oak-view-v1\n{}", self.to_canonical()).as_bytes())
211    }
212
213    fn is_excluded(&self, path: &str) -> bool {
214        self.exclude.iter().any(|e| prefix_covers(e, path))
215    }
216
217    /// Is `path` inside an included prefix and not excluded? Spine files are
218    /// not counted; see [`ViewSpec::includes_file`].
219    pub fn covers(&self, path: &str) -> bool {
220        let path = normalize_prefix(path);
221        self.include.iter().any(|i| prefix_covers(i, &path)) && !self.is_excluded(&path)
222    }
223
224    /// Does the view keep the file at `path`? True when the view
225    /// [covers](ViewSpec::covers) it, or when it is a spine file in a
226    /// directory the view passes through on the way to an included prefix.
227    pub fn includes_file(&self, path: &str) -> bool {
228        let path = normalize_prefix(path);
229        if self.covers(&path) {
230            return true;
231        }
232        let (dir, name) = path.rsplit_once('/').unwrap_or(("", path.as_str()));
233        self.spine_files.iter().any(|s| s == name)
234            && !self.is_excluded(&path)
235            && self.dir_state(dir) != DirState::Outside
236    }
237
238    fn dir_state(&self, dir: &str) -> DirState {
239        if self.is_excluded(dir) {
240            return DirState::Outside;
241        }
242        if self.include.iter().any(|i| prefix_covers(i, dir)) {
243            if self.exclude.iter().any(|e| prefix_covers(dir, e)) {
244                DirState::Partial
245            } else {
246                DirState::Full
247            }
248        } else if self.include.iter().any(|i| prefix_covers(dir, i)) {
249            DirState::Partial
250        } else {
251            DirState::Outside
252        }
253    }
254}
255
256fn normalize_all<I>(raw: I) -> Result<Vec<String>>
257where
258    I: IntoIterator,
259    I::Item: AsRef<str>,
260{
261    let mut out = Vec::new();
262    for p in raw {
263        let p = normalize_prefix(p.as_ref());
264        if !p.is_empty() {
265            validate_tree_path(&p)?;
266        }
267        out.push(p);
268    }
269    Ok(out)
270}
271
272/// Sort, dedup, and drop every prefix covered by another one.
273fn drop_covered(mut prefixes: Vec<String>) -> Vec<String> {
274    prefixes.sort();
275    prefixes.dedup();
276    let all = prefixes.clone();
277    prefixes.retain(|p| !all.iter().any(|q| q != p && prefix_covers(q, p)));
278    prefixes
279}
280
281/// Prune the tree at `root` to `view`. Directories wholly in view keep their
282/// hashes; `trees` holds only the spine directories pruning rebuilt (each
283/// once). An empty result is [`Tree::empty_hash`].
284pub fn prune_tree<F>(root: &Hash, view: &ViewSpec, fetch: &mut F) -> Result<BuiltTree>
285where
286    F: FnMut(&Hash) -> Result<Tree>,
287{
288    let mut trees = Vec::new();
289    let mut seen = HashSet::new();
290    let root_hash = match dir_hash(root) {
291        Some(root) => prune_dir(root, "", view, fetch, &mut trees, &mut seen)?,
292        None => None,
293    };
294    Ok(BuiltTree {
295        root_hash: root_hash.unwrap_or_else(Tree::empty_hash),
296        trees,
297    })
298}
299
300fn prune_dir<F>(
301    dir: &Hash,
302    path: &str,
303    view: &ViewSpec,
304    fetch: &mut F,
305    trees: &mut Vec<Tree>,
306    seen: &mut HashSet<Hash>,
307) -> Result<Option<Hash>>
308where
309    F: FnMut(&Hash) -> Result<Tree>,
310{
311    match view.dir_state(path) {
312        DirState::Outside => return Ok(None),
313        DirState::Full => return Ok(Some(dir.clone())),
314        DirState::Partial => {}
315    }
316    let tree = load_tree(dir, fetch)?;
317    let mut kept = Vec::with_capacity(tree.entries.len());
318    for entry in &tree.entries {
319        let child = child_path(path, &entry.name);
320        match entry.kind {
321            TreeEntryKind::Blob => {
322                if view.includes_file(&child) {
323                    kept.push(entry.clone());
324                }
325            }
326            TreeEntryKind::Tree => {
327                if let Some(hash) = prune_dir(&entry.hash, &child, view, fetch, trees, seen)? {
328                    kept.push(TreeEntry {
329                        hash,
330                        ..entry.clone()
331                    });
332                }
333            }
334        }
335    }
336    finish_dir(Some(&tree), kept, trees, seen)
337}
338
339/// The hash for a rebuilt directory: `None` when empty, the original hash
340/// when nothing changed, otherwise a new tree recorded once in `trees`.
341fn finish_dir(
342    original: Option<&Tree>,
343    entries: Vec<TreeEntry>,
344    trees: &mut Vec<Tree>,
345    seen: &mut HashSet<Hash>,
346) -> Result<Option<Hash>> {
347    if entries.is_empty() {
348        return Ok(None);
349    }
350    if let Some(original) = original {
351        let unchanged = original.entries.len() == entries.len()
352            && original.entries.iter().zip(&entries).all(|(a, b)| {
353                a.name == b.name && a.hash == b.hash && a.kind == b.kind && a.mode == b.mode
354            });
355        if unchanged {
356            return Ok(Some(original.hash.clone()));
357        }
358    }
359    let tree = Tree::new(entries)?;
360    let hash = tree.hash.clone();
361    if seen.insert(hash.clone()) {
362        trees.push(tree);
363    }
364    Ok(Some(hash))
365}
366
367/// Splice the view tree `view_root` back into the full tree `full_root`:
368/// everything the view selects is taken from `view_root` (so a file missing
369/// there is a deletion), everything else from `full_root`. `fetch` must
370/// resolve trees of both sides.
371///
372/// Refuses, with [`OakError::InvalidPath`] naming the path, any entry in
373/// `view_root` the view doesn't select, and a file and a directory meeting
374/// at one path (an in-view file replacing an out-of-view directory, or the
375/// reverse). `trees` holds only the directories the graft rebuilt.
376///
377/// For a `view_root` produced by [`prune_tree`] over `full_root` this is the
378/// identity, and `prune_tree(graft_tree(f, v)) == v` for any valid `v`.
379pub fn graft_tree<F>(
380    full_root: &Hash,
381    view_root: &Hash,
382    view: &ViewSpec,
383    fetch: &mut F,
384) -> Result<BuiltTree>
385where
386    F: FnMut(&Hash) -> Result<Tree>,
387{
388    let mut trees = Vec::new();
389    let mut seen = HashSet::new();
390    let root_hash = graft_dir(
391        dir_hash(full_root),
392        dir_hash(view_root),
393        "",
394        view,
395        fetch,
396        &mut trees,
397        &mut seen,
398    )?;
399    Ok(BuiltTree {
400        root_hash: root_hash.unwrap_or_else(Tree::empty_hash),
401        trees,
402    })
403}
404
405fn outside_view(path: &str) -> OakError {
406    let shown = if path.is_empty() { "/" } else { path };
407    OakError::InvalidPath(format!("{shown} is outside this view"))
408}
409
410#[allow(clippy::too_many_arguments)]
411fn graft_dir<F>(
412    full: Option<&Hash>,
413    viewed: Option<&Hash>,
414    path: &str,
415    view: &ViewSpec,
416    fetch: &mut F,
417    trees: &mut Vec<Tree>,
418    seen: &mut HashSet<Hash>,
419) -> Result<Option<Hash>>
420where
421    F: FnMut(&Hash) -> Result<Tree>,
422{
423    match view.dir_state(path) {
424        DirState::Outside => {
425            return match viewed {
426                Some(_) => Err(outside_view(path)),
427                None => Ok(full.cloned()),
428            }
429        }
430        DirState::Full => return Ok(viewed.cloned()),
431        DirState::Partial => {}
432    }
433    let full_tree = full.map(|h| load_tree(h, fetch)).transpose()?;
434    let view_tree = viewed.map(|h| load_tree(h, fetch)).transpose()?;
435
436    // name -> (full entry, view entry)
437    let mut names: BTreeMap<&str, (Option<&TreeEntry>, Option<&TreeEntry>)> = BTreeMap::new();
438    for e in full_tree.iter().flat_map(|t| &t.entries) {
439        names.entry(&e.name).or_default().0 = Some(e);
440    }
441    for e in view_tree.iter().flat_map(|t| &t.entries) {
442        names.entry(&e.name).or_default().1 = Some(e);
443    }
444
445    let mut entries = Vec::with_capacity(names.len());
446    for (name, (full_entry, view_entry)) in names {
447        let child = child_path(path, name);
448        let tree_of = |e: Option<&TreeEntry>| {
449            e.filter(|e| e.kind == TreeEntryKind::Tree)
450                .map(|e| e.hash.clone())
451        };
452        let blob_of = |e: Option<&TreeEntry>| e.filter(|e| e.kind == TreeEntryKind::Blob).cloned();
453
454        let sub = graft_dir(
455            tree_of(full_entry).as_ref(),
456            tree_of(view_entry).as_ref(),
457            &child,
458            view,
459            fetch,
460            trees,
461            seen,
462        )?;
463        let file = if view.includes_file(&child) {
464            blob_of(view_entry)
465        } else {
466            if blob_of(view_entry).is_some() {
467                return Err(outside_view(&child));
468            }
469            blob_of(full_entry)
470        };
471        match (sub, file) {
472            (Some(_), Some(_)) => {
473                return Err(OakError::InvalidPath(format!(
474                    "{child} would be both a file and a directory \
475                     (one of them is outside this view)"
476                )))
477            }
478            (Some(hash), None) => entries.push(TreeEntry {
479                name: name.to_string(),
480                kind: TreeEntryKind::Tree,
481                hash,
482                mode: crate::FileMode::Regular,
483            }),
484            (None, Some(blob)) => entries.push(blob),
485            (None, None) => {}
486        }
487    }
488    finish_dir(full_tree.as_ref(), entries, trees, seen)
489}
490
491/// What a source commit becomes in a view.
492#[derive(Debug, Clone)]
493pub enum DerivedViewCommit {
494    /// The source commit changed nothing the view selects: it maps to this
495    /// existing view commit (the view parent's), so a view's history only
496    /// holds commits that touched it.
497    Reuse(Hash),
498    /// A new view commit.
499    New(Commit),
500}
501
502impl DerivedViewCommit {
503    /// The view commit hash the source commit maps to.
504    pub fn hash(&self) -> &Hash {
505        match self {
506            DerivedViewCommit::Reuse(hash) => hash,
507            DerivedViewCommit::New(commit) => &commit.hash,
508        }
509    }
510}
511
512/// Derive the view commit for `source`, given its pruned root and the view
513/// commits its parents map to.
514///
515/// The result is an ordinary [`Commit`] — same hash format, same
516/// verification — with `manifest_hash` set to the pruned root, parents set
517/// to the parents' view commits, branch, author and timestamp copied, and
518/// `files` filtered to the paths the view keeps. When `redact_message` is
519/// set (the source also changed paths the viewer can't read) the message is
520/// replaced with [`REDACTED_VIEW_MESSAGE`].
521///
522/// A source that leaves the view unchanged — same pruned root as its first
523/// parent's view commit, and no merge parent bringing in a different view
524/// commit — is [`DerivedViewCommit::Reuse`] of that parent.
525pub fn derive_view_commit(
526    source: &Commit,
527    view: &ViewSpec,
528    view_root: Hash,
529    view_parent: Option<&Commit>,
530    view_merge_parent: Option<Hash>,
531    redact_message: bool,
532) -> Result<DerivedViewCommit> {
533    if let Some(parent) = view_parent {
534        let merge_is_noop = view_merge_parent
535            .as_ref()
536            .is_none_or(|mp| mp == &parent.hash);
537        if parent.manifest_hash == view_root && merge_is_noop {
538            return Ok(DerivedViewCommit::Reuse(parent.hash.clone()));
539        }
540    }
541    let files: Vec<FileChange> = source
542        .files
543        .iter()
544        .filter(|f| {
545            view.includes_file(&f.path)
546                || f.old_path.as_deref().is_some_and(|p| view.includes_file(p))
547        })
548        .cloned()
549        .collect();
550    let message = match &source.message {
551        Some(_) if redact_message => Some(REDACTED_VIEW_MESSAGE.to_string()),
552        other => other.clone(),
553    };
554    let merge_parent = view_merge_parent.filter(|mp| view_parent.is_none_or(|p| &p.hash != mp));
555    Commit::with_timestamp(
556        source.branch_name.clone(),
557        view_parent.map(|p| p.hash.clone()),
558        merge_parent,
559        view_root,
560        source.author.clone(),
561        message,
562        files,
563        source.timestamp,
564    )
565    .map(DerivedViewCommit::New)
566}
567
568#[cfg(test)]
569mod tests {
570    use super::*;
571    use crate::tree::test_support::{mutate, random_entries, Rng, Store};
572    use crate::tree::{build_tree, flatten_tree};
573    use crate::{hash_string, FileMode, ManifestEntry};
574
575    fn entry(path: &str, content: &str) -> ManifestEntry {
576        ManifestEntry {
577            path: path.to_string(),
578            blob_hash: hash_string(content),
579            mode: FileMode::Regular,
580        }
581    }
582
583    fn view(include: &[&str], exclude: &[&str], spine: &[&str]) -> ViewSpec {
584        ViewSpec::new(include, exclude, spine).unwrap()
585    }
586
587    fn flat(store: &Store, root: &Hash) -> Vec<ManifestEntry> {
588        let mut out = flatten_tree(root, &mut |h: &Hash| store.fetch(h)).unwrap();
589        out.sort_by(|a, b| a.path.cmp(&b.path));
590        out
591    }
592
593    fn sorted(mut entries: Vec<ManifestEntry>) -> Vec<ManifestEntry> {
594        entries.sort_by(|a, b| a.path.cmp(&b.path));
595        entries
596    }
597
598    fn paths(entries: &[ManifestEntry]) -> Vec<(String, Hash, FileMode)> {
599        entries
600            .iter()
601            .map(|e| (e.path.clone(), e.blob_hash.clone(), e.mode))
602            .collect()
603    }
604
605    fn company() -> Vec<ManifestEntry> {
606        vec![
607            entry("AGENTS.md", "root agents"),
608            entry("README.md", "readme"),
609            entry("apps/AGENTS.md", "apps agents"),
610            entry("apps/web/src/main.ts", "web"),
611            entry("apps/web/config/prod/secret.env", "secret"),
612            entry("apps/billing/src/lib.rs", "billing"),
613            entry("libs/ui/button.tsx", "button"),
614            entry("libs/auth/login.rs", "login"),
615        ]
616    }
617
618    #[test]
619    fn normalizes_redundant_entries() {
620        let v = view(
621            &["/apps/web/", "apps/web/src", "libs/ui", "vendor/x"],
622            &[
623                "apps/web/config",
624                "apps/web/config/prod",
625                "elsewhere",
626                "vendor",
627            ],
628            &["CLAUDE.md", "AGENTS.md", "AGENTS.md"],
629        );
630        assert_eq!(v.include(), &["apps/web", "libs/ui"]);
631        assert_eq!(v.exclude(), &["apps/web/config"]);
632        assert_eq!(v.spine_files(), &["AGENTS.md", "CLAUDE.md"]);
633    }
634
635    #[test]
636    fn rejects_empty_and_whole_repo_exclude() {
637        assert!(ViewSpec::new(["a"], ["a"], [] as [&str; 0]).is_err());
638        assert!(ViewSpec::new([] as [&str; 0], [] as [&str; 0], [] as [&str; 0]).is_err());
639        assert!(ViewSpec::new([""], ["/"], [] as [&str; 0]).is_err());
640        assert!(ViewSpec::new(["a"], [] as [&str; 0], ["a/b"]).is_err());
641        assert!(ViewSpec::new(["a/../b"], [] as [&str; 0], [] as [&str; 0]).is_err());
642    }
643
644    #[test]
645    fn canonical_form_round_trips_and_ids_are_stable() {
646        let v = view(
647            &["libs/ui", "apps/web"],
648            &["apps/web/config"],
649            &["AGENTS.md"],
650        );
651        assert_eq!(
652            v.to_canonical(),
653            "+apps/web\n+libs/ui\n-apps/web/config\n=AGENTS.md"
654        );
655        let parsed = ViewSpec::parse(&v.to_canonical()).unwrap();
656        assert_eq!(parsed, v);
657        assert_eq!(parsed.id(), v.id());
658        let reordered = view(
659            &["apps/web/", "libs/ui"],
660            &["/apps/web/config"],
661            &["AGENTS.md"],
662        );
663        assert_eq!(reordered.id(), v.id());
664        assert_ne!(view(&["apps/web"], &[], &[]).id(), v.id());
665        assert_eq!(ViewSpec::parse("+").unwrap(), ViewSpec::full());
666        assert!(ViewSpec::parse("apps").is_err());
667    }
668
669    #[test]
670    fn union_keeps_only_shared_exclusions() {
671        let a = view(&["apps"], &["apps/web/config"], &[]);
672        let b = view(&["apps/web", "libs/ui"], &[], &["AGENTS.md"]);
673        let u = a.union(&b).unwrap();
674        assert_eq!(u.include(), &["apps", "libs/ui"]);
675        assert!(u.exclude().is_empty());
676        assert_eq!(u.spine_files(), &["AGENTS.md"]);
677        let c = view(&["libs"], &[], &[]);
678        assert_eq!(a.union(&c).unwrap().exclude(), &["apps/web/config"]);
679    }
680
681    #[test]
682    fn prune_drops_sibling_names_and_keeps_spine_files() {
683        let mut store = Store::default();
684        let root = store.add_entries(&company());
685        let v = view(
686            &["apps/web", "libs/ui"],
687            &["apps/web/config/prod"],
688            &DEFAULT_SPINE_FILES,
689        );
690        let pruned = prune_tree(&root, &v, &mut |h: &Hash| store.fetch(h)).unwrap();
691        store.add_trees(pruned.trees);
692        let got: Vec<String> = flat(&store, &pruned.root_hash)
693            .into_iter()
694            .map(|e| e.path)
695            .collect();
696        assert_eq!(
697            got,
698            [
699                "AGENTS.md",
700                "apps/AGENTS.md",
701                "apps/web/src/main.ts",
702                "libs/ui/button.tsx"
703            ]
704        );
705    }
706
707    #[test]
708    fn prune_reuses_in_view_subtree_hashes() {
709        let mut store = Store::default();
710        let root = store.add_entries(&company());
711        let fetch = |h: &Hash| store.fetch(h);
712        let ui_before = crate::subtree_at_path(&root, "libs/ui", &mut { fetch }).unwrap();
713        let v = view(&["libs/ui", "apps/web"], &[], &[]);
714        let pruned = prune_tree(&root, &v, &mut |h: &Hash| store.fetch(h)).unwrap();
715        // Rebuilt: root, libs, apps. Not libs/ui or apps/web (reused by hash).
716        assert_eq!(pruned.trees.len(), 3);
717        store.add_trees(pruned.trees.clone());
718        let ui_after =
719            crate::subtree_at_path(&pruned.root_hash, "libs/ui", &mut |h: &Hash| store.fetch(h))
720                .unwrap();
721        assert_eq!(ui_before, ui_after);
722    }
723
724    #[test]
725    fn full_view_is_identity() {
726        let mut store = Store::default();
727        let root = store.add_entries(&company());
728        let pruned = prune_tree(&root, &ViewSpec::full(), &mut |h: &Hash| store.fetch(h)).unwrap();
729        assert_eq!(pruned.root_hash, root);
730        assert!(pruned.trees.is_empty());
731    }
732
733    #[test]
734    fn graft_refuses_writes_outside_the_view() {
735        let mut store = Store::default();
736        let full = company();
737        let root = store.add_entries(&full);
738        let v = view(&["apps/web"], &[], &DEFAULT_SPINE_FILES);
739
740        let mut outside = full
741            .iter()
742            .filter(|e| v.includes_file(&e.path))
743            .cloned()
744            .collect::<Vec<_>>();
745        outside.push(entry("apps/new.txt", "sneaky"));
746        let view_root = store.add_entries(&outside);
747        let err = graft_tree(&root, &view_root, &v, &mut |h: &Hash| store.fetch(h)).unwrap_err();
748        assert!(
749            err.to_string()
750                .contains("apps/new.txt is outside this view"),
751            "{err}"
752        );
753
754        let mut outside_dir = full
755            .iter()
756            .filter(|e| v.includes_file(&e.path))
757            .cloned()
758            .collect::<Vec<_>>();
759        outside_dir.push(entry("libs/auth/evil.rs", "x"));
760        let view_root = store.add_entries(&outside_dir);
761        let err = graft_tree(&root, &view_root, &v, &mut |h: &Hash| store.fetch(h)).unwrap_err();
762        assert!(
763            err.to_string().contains("libs is outside this view"),
764            "{err}"
765        );
766    }
767
768    #[test]
769    fn graft_applies_in_view_edits_and_spine_edits() {
770        let mut store = Store::default();
771        let full = company();
772        let root = store.add_entries(&full);
773        let v = view(&["apps/web"], &[], &DEFAULT_SPINE_FILES);
774        let mut edited: Vec<ManifestEntry> = full
775            .iter()
776            .filter(|e| v.includes_file(&e.path) && e.path != "apps/web/src/main.ts")
777            .cloned()
778            .collect();
779        edited.push(entry("apps/web/src/app.ts", "new"));
780        edited.retain(|e| e.path != "AGENTS.md");
781        edited.push(entry("AGENTS.md", "edited root agents"));
782        let view_root = store.add_entries(&edited);
783        let grafted = graft_tree(&root, &view_root, &v, &mut |h: &Hash| store.fetch(h)).unwrap();
784        store.add_trees(grafted.trees);
785
786        let mut expected: Vec<ManifestEntry> = full
787            .iter()
788            .filter(|e| !v.includes_file(&e.path))
789            .cloned()
790            .collect();
791        expected.extend(edited);
792        assert_eq!(
793            paths(&flat(&store, &grafted.root_hash)),
794            paths(&sorted(expected))
795        );
796    }
797
798    fn random_view(rng: &mut Rng) -> ViewSpec {
799        const PREFIXES: [&str; 9] = ["", "a", "b", "c", "a/b", "a/c", "b/a", "c/d", "a/b/c"];
800        loop {
801            let pick = |rng: &mut Rng| PREFIXES[rng.below(PREFIXES.len() as u64) as usize];
802            let include: Vec<&str> = (0..1 + rng.below(3)).map(|_| pick(rng)).collect();
803            let exclude: Vec<&str> = (0..rng.below(3))
804                .map(|_| pick(rng))
805                .filter(|p| !p.is_empty())
806                .collect();
807            let spine: Vec<&str> = if rng.below(2) == 0 { vec!["d"] } else { vec![] };
808            if let Ok(v) = ViewSpec::new(include, exclude, spine) {
809                return v;
810            }
811        }
812    }
813
814    #[test]
815    fn prune_matches_flat_filter_on_random_trees() {
816        let mut rng = Rng(0x5eed_0001);
817        for _ in 0..500 {
818            let mut store = Store::default();
819            let full = random_entries(&mut rng, 12);
820            let root = store.add_entries(&full);
821            let v = random_view(&mut rng);
822            let pruned = prune_tree(&root, &v, &mut |h: &Hash| store.fetch(h)).unwrap();
823            store.add_trees(pruned.trees);
824            let expected: Vec<ManifestEntry> = full
825                .iter()
826                .filter(|e| v.includes_file(&e.path))
827                .cloned()
828                .collect();
829            assert_eq!(
830                paths(&flat(&store, &pruned.root_hash)),
831                paths(&sorted(expected)),
832                "view {}",
833                v.to_canonical()
834            );
835            // Pruning a full tree then grafting it back changes nothing.
836            let back =
837                graft_tree(&root, &pruned.root_hash, &v, &mut |h: &Hash| store.fetch(h)).unwrap();
838            assert_eq!(back.root_hash, root, "view {}", v.to_canonical());
839        }
840    }
841
842    #[test]
843    fn graft_matches_flat_splice_on_random_edits() {
844        let mut rng = Rng(0x5eed_0002);
845        let mut checked = 0;
846        for _ in 0..800 {
847            let mut store = Store::default();
848            let full = random_entries(&mut rng, 12);
849            let root = store.add_entries(&full);
850            let v = random_view(&mut rng);
851            let in_view: Vec<ManifestEntry> = full
852                .iter()
853                .filter(|e| v.includes_file(&e.path))
854                .cloned()
855                .collect();
856            let edited: Vec<ManifestEntry> = mutate(&mut rng, &in_view, 4)
857                .into_iter()
858                .filter(|e| v.includes_file(&e.path))
859                .collect();
860            let view_root = store.add_entries(&edited);
861
862            let mut expected: Vec<ManifestEntry> = full
863                .iter()
864                .filter(|e| !v.includes_file(&e.path))
865                .cloned()
866                .collect();
867            expected.extend(edited.iter().cloned());
868            let grafted = graft_tree(&root, &view_root, &v, &mut |h: &Hash| store.fetch(h));
869            match build_tree(&expected) {
870                Ok(built) => {
871                    let grafted = grafted.unwrap_or_else(|e| {
872                        panic!("view {}: unexpected graft error {e}", v.to_canonical())
873                    });
874                    assert_eq!(
875                        grafted.root_hash,
876                        built.root_hash,
877                        "view {}",
878                        v.to_canonical()
879                    );
880                    store.add_trees(grafted.trees);
881                    // And the graft prunes back to exactly the view tree.
882                    let again =
883                        prune_tree(&grafted.root_hash, &v, &mut |h: &Hash| store.fetch(h)).unwrap();
884                    assert_eq!(again.root_hash, view_root, "view {}", v.to_canonical());
885                    checked += 1;
886                }
887                // A file/directory clash across the view boundary.
888                Err(_) => assert!(grafted.is_err(), "view {}", v.to_canonical()),
889            }
890        }
891        assert!(checked > 400, "too few clash-free cases: {checked}");
892    }
893
894    fn commit(manifest: &Hash, parent: Option<&Commit>, message: Option<&str>) -> Commit {
895        Commit::with_timestamp(
896            "main".to_string(),
897            parent.map(|p| p.hash.clone()),
898            None,
899            manifest.clone(),
900            "alice".to_string(),
901            message.map(str::to_string),
902            Vec::new(),
903            chrono::DateTime::from_timestamp(1_700_000_000, 0).unwrap(),
904        )
905        .unwrap()
906    }
907
908    #[test]
909    fn view_commits_reuse_unchanged_parents_and_redact_messages() {
910        let v = view(&["apps/web"], &[], &[]);
911        let root_a = hash_string("pruned-a");
912        let root_b = hash_string("pruned-b");
913        let source = commit(&hash_string("full-1"), None, Some("touch web and billing"));
914
915        let first =
916            match derive_view_commit(&source, &v, root_a.clone(), None, None, false).unwrap() {
917                DerivedViewCommit::New(c) => c,
918                other => panic!("expected new, got {other:?}"),
919            };
920        assert_eq!(first.manifest_hash, root_a);
921        assert_eq!(first.message.as_deref(), Some("touch web and billing"));
922        assert_ne!(first.hash, source.hash);
923        first.verify_fields().unwrap();
924
925        // Same pruned root: maps onto the parent view commit.
926        let next = commit(&hash_string("full-2"), Some(&source), Some("billing only"));
927        let reused =
928            derive_view_commit(&next, &v, root_a.clone(), Some(&first), None, false).unwrap();
929        assert!(matches!(&reused, DerivedViewCommit::Reuse(h) if h == &first.hash));
930
931        // Changed pruned root and touched restricted paths: new, redacted.
932        let redacted = derive_view_commit(&next, &v, root_b, Some(&first), None, true).unwrap();
933        let DerivedViewCommit::New(redacted) = redacted else {
934            panic!("expected new");
935        };
936        assert_eq!(redacted.parent_hash.as_ref(), Some(&first.hash));
937        assert_eq!(redacted.message.as_deref(), Some(REDACTED_VIEW_MESSAGE));
938        redacted.verify_fields().unwrap();
939    }
940
941    #[test]
942    fn view_commit_files_are_filtered_to_the_view() {
943        use crate::{ChangeType, FileChange};
944        let v = view(&["apps/web"], &[], &[]);
945        let change = |path: &str| FileChange {
946            path: path.to_string(),
947            change_type: ChangeType::Modified,
948            old_blob_hash: None,
949            new_blob_hash: None,
950            old_path: None,
951            old_mode: None,
952            new_mode: None,
953        };
954        let mut source = commit(&hash_string("full"), None, None);
955        source.files = vec![change("apps/web/a.ts"), change("apps/billing/b.rs")];
956        let DerivedViewCommit::New(c) =
957            derive_view_commit(&source, &v, hash_string("p"), None, None, false).unwrap()
958        else {
959            panic!("expected new");
960        };
961        let files: Vec<&str> = c.files.iter().map(|f| f.path.as_str()).collect();
962        assert_eq!(files, ["apps/web/a.ts"]);
963    }
964}