Skip to main content

grex_core/tree/
graph.rs

1//! Read-only pack graph produced by the [`crate::tree::Walker`].
2//!
3//! The graph is a value type: once the walker returns a [`PackGraph`] the
4//! structure is immutable. Callers (validators, schedulers, renderers) only
5//! ever see the already-assembled graph — they never participate in its
6//! construction. This decoupling lets us swap the walker for, say, an IPC
7//! driver or a snapshot-replay harness without touching any downstream
8//! consumer.
9//!
10//! # Ownership model
11//!
12//! * Nodes live in a `Vec`; node id == vector index.
13//! * Edges are a flat vector for cheap iteration; the few lookups we perform
14//!   on a walked tree do not justify an adjacency-map yet.
15//! * The root is always at index `0` by construction.
16//!
17//! # Non-goals
18//!
19//! * No mutation API. The graph cannot grow or shrink after walker exit.
20//! * No topological sort here — that belongs to the scheduler slice.
21//! * No serialisation — persistence is a later slice.
22
23use std::path::PathBuf;
24
25use crate::pack::PackManifest;
26
27/// Node-edge relationship kind.
28///
29/// `Child` edges are *owned*: the walker cloned the target repo and recursed
30/// into it. `DependsOn` edges are *referential*: the walker recorded that the
31/// parent named this dep but did not hydrate it — resolution happens at
32/// validate time via `DependsOnValidator`.
33///
34/// Marked `#[non_exhaustive]` so new edge relations (e.g. `Provides`,
35/// `Conflicts`) can land without breaking external match sites.
36#[non_exhaustive]
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum EdgeKind {
39    /// Parent owns/walks this child (cloned + recursed).
40    Child,
41    /// Parent merely references this pack by name or url.
42    DependsOn,
43}
44
45/// A pack in the walked graph.
46///
47/// Every field is `pub` by design: the graph is a read-only value type, and
48/// exposing the full record here is simpler than hand-curating accessors for
49/// each field.
50///
51/// Marked `#[non_exhaustive]` so audit fields (resolved ref SHA, hydration
52/// timestamps) can land without breaking library consumers who destructure
53/// the struct.
54#[non_exhaustive]
55#[derive(Debug, Clone)]
56pub struct PackNode {
57    /// Stable index inside the graph (equal to the `Vec` position).
58    pub id: usize,
59    /// `name` copied from the pack manifest for O(1) lookup.
60    pub name: String,
61    /// On-disk location of the pack's working tree.
62    pub path: PathBuf,
63    /// Source URL the walker used to hydrate this node, or `None` for the
64    /// root / nodes that were loaded directly from an on-disk path.
65    pub source_url: Option<String>,
66    /// Full parsed manifest.
67    pub manifest: PackManifest,
68    /// Parent id; `None` for the root.
69    pub parent: Option<usize>,
70    /// Resolved commit SHA of the pack's working tree, when the walker
71    /// could obtain one. `None` for the root (local path, no clone step)
72    /// or when `head_sha` probing fails. Mixed into
73    /// [`crate::lockfile::compute_actions_hash`] so ref drift invalidates
74    /// the skip-on-hash short-circuit (M4-D spec §M4 req 4a).
75    pub commit_sha: Option<String>,
76    /// `true` when the walker synthesised the manifest in-memory because
77    /// the on-disk child had no `.grex/pack.yaml` but did carry a `.git/`
78    /// (v1.1.1 plain-git children, see
79    /// `openspec/changes/feat-v1.1.1-plain-git-children/`). Threaded
80    /// through to the lockfile (`LockEntry::synthetic`) and downstream
81    /// surfaces (doctor, ls). Default `false` for every declared pack.
82    pub synthetic: bool,
83}
84
85/// An edge in the walked graph.
86///
87/// Marked `#[non_exhaustive]` so future edge-level metadata (priority,
88/// guard expression) is non-breaking for library consumers.
89#[non_exhaustive]
90#[derive(Debug, Clone)]
91pub struct PackEdge {
92    /// Origin node id.
93    pub from: usize,
94    /// Target node id.
95    pub to: usize,
96    /// Relationship kind.
97    pub kind: EdgeKind,
98}
99
100/// Fully-walked pack graph. Immutable post-construction.
101///
102/// Nodes are owned; callers borrow via [`PackGraph::nodes`] or the dedicated
103/// lookup helpers.
104#[derive(Debug)]
105pub struct PackGraph {
106    nodes: Vec<PackNode>,
107    edges: Vec<PackEdge>,
108}
109
110impl PackGraph {
111    /// Construct a graph from raw node and edge vectors.
112    ///
113    /// Pub-crate visibility keeps mutation ownership with the walker while
114    /// allowing an empty graph or a manually-assembled fixture inside tests
115    /// (via `pub(crate)` helpers invoked from the integration test harness).
116    ///
117    /// # Panics
118    ///
119    /// Panics if `nodes` is empty — a walk always produces at least the
120    /// root. This is a programming-error guard rather than a user-facing
121    /// failure mode.
122    #[must_use]
123    pub(crate) fn new(nodes: Vec<PackNode>, edges: Vec<PackEdge>) -> Self {
124        assert!(!nodes.is_empty(), "PackGraph must contain at least the root node");
125        Self { nodes, edges }
126    }
127
128    /// The root node (id == 0).
129    #[must_use]
130    pub fn root(&self) -> &PackNode {
131        &self.nodes[0]
132    }
133
134    /// All nodes in insertion order.
135    #[must_use]
136    pub fn nodes(&self) -> &[PackNode] {
137        &self.nodes
138    }
139
140    /// All edges in insertion order.
141    #[must_use]
142    pub fn edges(&self) -> &[PackEdge] {
143        &self.edges
144    }
145
146    /// Iterate the `Child`-kind neighbours of `id` (in insertion order).
147    pub fn children_of(&self, id: usize) -> impl Iterator<Item = &PackNode> {
148        self.neighbours(id, EdgeKind::Child)
149    }
150
151    /// Iterate the `DependsOn`-kind neighbours of `id`.
152    pub fn depends_on_of(&self, id: usize) -> impl Iterator<Item = &PackNode> {
153        self.neighbours(id, EdgeKind::DependsOn)
154    }
155
156    /// Find a node by its manifest name. Returns the first match in
157    /// insertion order; names are not guaranteed unique across a graph,
158    /// though per-pack validators may reject duplicates in future slices.
159    #[must_use]
160    pub fn find_by_name(&self, name: &str) -> Option<&PackNode> {
161        self.nodes.iter().find(|n| n.name == name)
162    }
163
164    /// Borrow a node by id.
165    #[must_use]
166    pub fn node(&self, id: usize) -> Option<&PackNode> {
167        self.nodes.get(id)
168    }
169
170    fn neighbours(&self, id: usize, kind: EdgeKind) -> impl Iterator<Item = &PackNode> {
171        self.edges
172            .iter()
173            .filter(move |e| e.from == id && e.kind == kind)
174            .filter_map(|e| self.nodes.get(e.to))
175    }
176}