differential_engine/ports.rs
1//! Ports: the traits the engine's business logic owns and adapters implement.
2//!
3//! Dependency direction only (ADR 0020). These exist so `pipeline`,
4//! `invariants`, `tree`, `worktree` and `crates/stack` never name
5//! `gitio::Repo` — each function's bound list is a reviewable statement of
6//! exactly how much git it is allowed to touch, and `invariants` can no longer
7//! so much as *express* `git log`.
8//!
9//! **Consumed by static dispatch.** There is exactly one implementation of
10//! each git port, `gitio::Repo`, and ADR 0020 forbids a second one — a fake
11//! git for tests included. Invariants 1–4 compare the engine's reconstruction
12//! against git's own answer; against a fake they would compare the fake with
13//! the fake and pass while proving nothing (ADR 0002). Tests use hermetic
14//! temporary repositories and real `git`.
15//!
16//! The two runtime-open abstractions in this crate — `llm::LlmBackend` and
17//! `lang::Language` — are deliberately NOT here. They are `dyn` because config
18//! and a plugin registry pick them at run time; nothing in this module is
19//! chosen at run time.
20//!
21//! There is no `trait Git: ObjectReader + …` convenience supertrait, and there
22//! must not be: the whole value is that a consumer's bounds name what it
23//! actually needs.
24
25use std::collections::HashMap;
26use std::path::{Path, PathBuf};
27
28use crate::EngineError;
29use crate::review_state::{Finding, ReviewState};
30
31// ---------------------------------------------------------------- objects
32
33/// Reading objects out of the odb.
34pub trait ObjectReader {
35 /// Blob content at `rev:path`, with `path` kept as raw bytes.
36 ///
37 /// `Ok(None)` when the path does not exist at that revision. Any other
38 /// failure is a real error — an absent file and a broken repository must
39 /// never render identically.
40 fn blob(&self, rev: &str, path: &[u8]) -> Result<Option<Vec<u8>>, EngineError>;
41
42 /// The same, for several specs at once, answered in the order given.
43 ///
44 /// Reading a blob costs a process, and a process costs milliseconds — so a
45 /// caller that already knows every file it is about to draw should say so
46 /// rather than paying that per file. Measured on a 120-file range: 240
47 /// one-at-a-time reads took a second, against one call for the lot
48 /// (ADR 0021's "what is left is process spawns").
49 ///
50 /// Bulk is the SAME need as `blob`, not a different one, which is why it
51 /// sits on this port rather than earning its own.
52 fn blobs(&self, specs: &[(&str, &[u8])]) -> Result<Vec<Option<Vec<u8>>>, EngineError>;
53
54 /// Assert `oid` is present in the odb.
55 ///
56 /// Invariant 1 verifies binary files this way, since they carry no hunks
57 /// to reconstruct from. Deliberately not `-> Result<bool>`: a recorded oid
58 /// missing from the odb is a broken repository, not a failed invariant.
59 fn require_object(&self, oid: &str) -> Result<(), EngineError>;
60}
61
62/// Writing objects into the odb. Loose and unreferenced (so gc-able) by
63/// design — the engine creates a ref only where `RefWriter` says so.
64pub trait ObjectWriter {
65 /// Write `content` as a blob and return its oid.
66 fn write_blob(&self, content: &[u8]) -> Result<String, EngineError>;
67}
68
69// ------------------------------------------------------------- revisions
70
71/// Turning what the user typed into diff endpoints. Consumed only by
72/// `pipeline`: nothing downstream of resolution ever re-resolves.
73pub trait RangeResolver {
74 fn merge_base(&self, a: &str, b: &str) -> Result<String, EngineError>;
75
76 /// Resolve to a commit sha, or accept a raw tree oid.
77 ///
78 /// The endpoints of an uncommitted-state review are synthesized trees
79 /// (ADR 0017) and every later stage is tree-safe.
80 fn resolve_endpoint(&self, rev: &str) -> Result<String, EngineError>;
81}
82
83/// Peeling an endpoint to its tree oid — the one thing invariant 3 compares
84/// against.
85///
86/// Kept apart from `RangeResolver` because its consumers (`invariants`,
87/// `crates/stack`) must never resolve ranges.
88pub trait TreeResolver {
89 fn tree_of(&self, rev: &str) -> Result<String, EngineError>;
90}
91
92// ----------------------------------------------------------- enumeration
93
94/// Canonical enumeration (ADR 0005: total, no exclusions, ever).
95///
96/// **FROZEN ARGV.** The byte format each method returns is what `parse.rs`,
97/// `rename_view.rs` and ultimately the frozen normaliser were validated
98/// against; changing a flag changes shape hashes and breaks real-corpus
99/// parity. Add a method, never edit one.
100pub trait DiffSource {
101 /// `diff-tree -r -z --raw --full-index --no-renames`: authoritative modes,
102 /// full oids, dispositions.
103 fn raw_records(&self, base: &str, head: &str) -> Result<Vec<u8>, EngineError>;
104
105 /// `diff-tree -r -U0 --no-renames --no-color --no-ext-diff`: the canonical
106 /// patch. Every hunk in the system comes from here.
107 fn canonical_patch(&self, base: &str, head: &str) -> Result<Vec<u8>, EngineError>;
108
109 /// `diff-tree -r -M -z --name-status`: rename-detected **annotations**
110 /// only (ADR 0003). Never affects what exists.
111 fn rename_records(&self, base: &str, head: &str) -> Result<Vec<u8>, EngineError>;
112}
113
114/// Invariant 4's independent patch source, and nothing else.
115///
116/// A **separate trait** from `DiffSource` on purpose. Invariant 4 recounts
117/// `@@` headers over a patch of the tree the engine built, using a counter
118/// that is deliberately not the parser. Sharing an accessor with enumeration
119/// would mean one edit to one flag silently moving both sides of the
120/// comparison together.
121///
122/// An implementation MUST call git directly and MUST NOT delegate to
123/// `DiffSource::canonical_patch` — note the argv genuinely differs today, and
124/// that duplication is the point rather than an oversight.
125///
126/// The return type is `Vec<u8>` and must stay `Vec<u8>`: the moment this port
127/// hands invariant 4 anything structured, the counter stops being independent.
128pub trait RecountSource {
129 fn recount_patch(&self, from: &str, to: &str) -> Result<Vec<u8>, EngineError>;
130}
131
132/// One `check-attr` answer for one path.
133pub struct AttrValue {
134 pub path: Vec<u8>,
135 /// git's raw answer: a value, or `unspecified` / `unset` / `true` /
136 /// `false`. What those *mean* is domain policy
137 /// (`plan::attr_marks_generated`).
138 pub value: Vec<u8>,
139}
140
141/// gitattributes lookup, for the generated-file **hint** — never enumeration.
142///
143/// Takes an attribute name the caller chose; it does not take a `Config` and
144/// iterate one itself, because a port that reads config is a port that could
145/// filter (ADR 0012).
146pub trait AttributeSource {
147 /// Note, unchanged from before this trait existed: `check-attr` consults
148 /// the worktree/index `.gitattributes`, not the reviewed revisions —
149 /// acceptable for a hint that can never remove a file from enumeration.
150 fn check_attr(&self, attr: &str, paths: &[&[u8]]) -> Result<Vec<AttrValue>, EngineError>;
151}
152
153// -------------------------------------------------------- scratch index
154
155/// One record to feed a scratch index.
156///
157/// Owned rather than borrowed: a text file's oid is produced by
158/// `ObjectWriter::write_blob` inside the staging loop and would not outlive a
159/// borrow. One allocation per changed file is free next to the subprocess it
160/// is about to be piped into.
161pub enum IndexEntry {
162 Set {
163 mode: String,
164 oid: String,
165 path: Vec<u8>,
166 },
167 Remove {
168 path: Vec<u8>,
169 },
170}
171
172/// Opening a scratch index. Never the user's index, never a checkout
173/// (ADR 0011).
174pub trait TreeBuilder {
175 /// Not object-safe, by design: an associated type makes
176 /// `Box<dyn TreeBuilder>` impossible, so runtime dispatch cannot creep
177 /// back in behind this seam.
178 type Session: IndexSession;
179
180 /// A scratch index seeded from `tree_ish`.
181 fn begin_from_tree(&self, tree_ish: &str) -> Result<Self::Session, EngineError>;
182
183 /// A scratch index seeded from the repository's CURRENT index, for the
184 /// ADR-0017 uncommitted-state snapshots.
185 ///
186 /// Errors if the index has unmerged entries — a conflicted index has no
187 /// single tree.
188 fn begin_from_current_index(&self) -> Result<Self::Session, EngineError>;
189}
190
191/// A scratch index, alive as long as the value. Dropping it removes the
192/// temporary index file; blobs it wrote stay in the odb, unreferenced.
193pub trait IndexSession {
194 /// Stage a batch in one feed: quoting-proof, and one subprocess instead
195 /// of one per file.
196 fn stage(&mut self, entries: &[IndexEntry]) -> Result<(), EngineError>;
197
198 /// Hash each path's CURRENT WORKTREE content into the odb and stage it,
199 /// admitting new files and dropping ones deleted from the worktree.
200 ///
201 /// The worktree-snapshot primitive; nothing else may call it.
202 fn stage_from_worktree(&mut self, nul_paths: &[u8]) -> Result<(), EngineError>;
203
204 /// The tree oid of the currently staged state.
205 fn write_tree(&self) -> Result<String, EngineError>;
206}
207
208/// Reading the working copy. Only the ADR-0017 snapshots use this.
209pub trait WorkingCopy {
210 /// NUL-terminated tracked paths.
211 fn tracked_paths(&self) -> Result<Vec<u8>, EngineError>;
212 /// NUL-terminated untracked-but-not-ignored paths.
213 fn untracked_paths(&self) -> Result<Vec<u8>, EngineError>;
214
215 /// Whether any tracked file differs from `HEAD`, staged or unstaged.
216 ///
217 /// Untracked files are a separate question — `untracked_paths` answers
218 /// that — because a snapshot admits them via `--add`, and the two are
219 /// detected by different plumbing.
220 ///
221 /// May answer `true` for a merely stat-dirty index, where a content
222 /// comparison would say otherwise. That is the safe direction: a spurious
223 /// `true` costs a no-op checkbox, a spurious `false` would hide an option
224 /// the reviewer needs.
225 fn has_tracked_changes(&self) -> Result<bool, EngineError>;
226}
227
228// ------------------------------------------------------ writes that publish
229
230/// Author/committer identity for a synthetic commit. Domain data: a renderer
231/// decides who its commits belong to.
232pub struct CommitIdentity<'a> {
233 pub name: &'a str,
234 pub email: &'a str,
235}
236
237/// `commit-tree`. Separate from `IndexSession` because it does not touch an
238/// index — it takes a tree oid already written.
239pub trait CommitWriter {
240 fn commit_tree(
241 &self,
242 tree: &str,
243 parent: &str,
244 message: &[u8],
245 identity: CommitIdentity<'_>,
246 ) -> Result<String, EngineError>;
247}
248
249/// `update-ref`. The only port in the engine that mutates repository state a
250/// user can see, with exactly one consumer: the shadow-branch renderer.
251pub trait RefWriter {
252 fn update_ref(&self, name: &str, target: &str) -> Result<(), EngineError>;
253}
254
255// -------------------------------------------------------------- browsing
256
257pub struct CommitSummary {
258 pub sha: String,
259 pub short: String,
260 pub subject: String,
261 pub author: String,
262}
263
264/// History browsing for the review-source picker.
265pub trait CommitHistory {
266 /// False on an unborn HEAD — there is nothing to diff against.
267 fn has_commits(&self) -> bool;
268
269 /// The most recent `max` commits reachable from `from`, newest first.
270 fn recent_commits(&self, from: &str, max: usize) -> Result<Vec<CommitSummary>, EngineError>;
271
272 /// Branch/tag/remote names by the COMMIT sha they point at, annotated tags
273 /// peeled.
274 ///
275 /// Decoration only, so an unreadable ref list costs decoration and never
276 /// the picker: the adapter returns an empty map rather than an error.
277 fn refs_by_commit(&self) -> HashMap<String, Vec<String>>;
278}
279
280/// Where this repository's differential state lives. Path *policy* is domain
281/// (`plan::grouping_cache_dir`, `plan::review_dir`); this only says where the
282/// repository keeps its shared git directory.
283pub trait RepoLayout {
284 /// The shared git directory, absolutised (worktree-safe).
285 fn common_dir(&self) -> Result<PathBuf, EngineError>;
286 fn work_root(&self) -> &Path;
287}
288
289// ----------------------------------------------------------- persistence
290
291/// The grouping cache (ADR 0009).
292///
293/// The stored value is the RAW model response, so audit and assembly stay pure
294/// functions replayed on load and their fixes apply to cached runs too.
295///
296/// Keys are opaque hex from `grouping::cache_key`. An implementation MUST
297/// treat them as opaque and MUST NOT derive, namespace or truncate them: the
298/// key composition pins every existing cache entry in every checkout.
299pub trait GroupingCache {
300 fn get(&self, key: &str) -> Result<Option<String>, EngineError>;
301 fn put(&self, key: &str, response: &str) -> Result<(), EngineError>;
302}
303
304/// One review's sidecar (ADR 0013).
305///
306/// Every read is total: a store that has never been written yields defaults,
307/// never an error. `ReviewSession` is write-through — every mutator saves
308/// before returning — so an implementation must be cheap enough for that, and
309/// crash-safe in the sense that matters here: a torn write loses at most the
310/// last action.
311pub trait ReviewStore {
312 /// Persist a plan document under its content hash and point `current` at
313 /// it. Idempotent: re-saving the same hash must not rewrite the body.
314 ///
315 /// Takes serialised JSON and the hash rather than a `PlanDocument`,
316 /// which keeps `schema` out of this module entirely — the frozen contract
317 /// stays frozen (ADR 0008, 0018).
318 fn save_plan(&self, hash: &str, json: &str) -> Result<(), EngineError>;
319
320 fn load_state(&self) -> Result<ReviewState, EngineError>;
321 fn save_state(&self, state: &ReviewState) -> Result<(), EngineError>;
322
323 fn load_findings(&self) -> Result<Vec<Finding>, EngineError>;
324 /// Rewrites the whole set (status changes, deletions, re-anchor results).
325 /// The set is small; simplicity beats cleverness.
326 fn save_findings(&self, findings: &[Finding]) -> Result<(), EngineError>;
327}
328
329/// Where configuration comes from.
330///
331/// The engine decides WHICH files to look for, what precedence they have and
332/// what their absence means; this port only says where the user's config
333/// directory is and hands back file contents.
334pub trait ConfigSource {
335 /// The user config directory. `None` when no home directory can be
336 /// determined — then the user file simply does not exist.
337 fn user_config_dir(&self) -> Option<PathBuf>;
338
339 /// Contents, or `None` when the file does not exist. Any other failure
340 /// (permissions, non-UTF-8) is an error.
341 fn read(&self, path: &Path) -> Result<Option<String>, EngineError>;
342
343 /// Contents of a file the caller named explicitly, where absence is a hard
344 /// error rather than a default.
345 ///
346 /// A separate method rather than the domain synthesising the message from
347 /// `read`'s `None`, so the error text comes from the same `std::fs` call
348 /// it always did and cannot drift.
349 fn read_required(&self, path: &Path) -> Result<String, EngineError>;
350}