rto-graph 5.8.1

Provenance-tagged codebase knowledge graph store for Roteiro. Implementation detail of the roteiro CLI; no API stability guarantee.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
//! A thin `gix` wrapper exposing exactly the git facts the sync engine needs:
//! the HEAD tree id, the blobs in that tree, and blob contents. Kept small so
//! all `gix` coupling lives in one place.

use std::path::Path;

/// A blob in a tree: its repository-relative path and hex object id.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BlobRef {
    /// Repository-relative path (forward-slash separated).
    pub path: String,
    /// Hex-encoded git blob object id.
    pub oid: String,
}

/// Which tree the graph — derived layer *and* authored layer — is built from:
/// the committed `HEAD`, the working tree (uncommitted edits on disk), or the
/// git index (the staged tree a commit would record).
///
/// It selects the sync engine ([`crate::sync`] / [`crate::sync_worktree`] /
/// [`crate::sync_index`]) and the authored-layer source
/// ([`Repo::read_source`]) **together**, which is the point of it being one
/// type: the two layers disagreeing about which tree they describe is issue
/// #330, and it was a silent wrong answer rather than a loud one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GraphSource {
    /// The committed `HEAD` tree (the CI merge gate).
    Committed,
    /// The working tree: `HEAD` plus uncommitted edits to tracked files on disk.
    Worktree,
    /// The git index — exactly what a commit would record (the pre-commit gate).
    Index,
}

impl GraphSource {
    /// A short stable token for this source, for reports and tool documents.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Committed => "committed",
            Self::Worktree => "worktree",
            Self::Index => "index",
        }
    }
}

/// Errors raised while reading from a git repository.
#[derive(Debug, thiserror::Error)]
pub enum GitError {
    /// A `gix` operation failed (message preserved).
    #[error("git error: {0}")]
    Git(String),
    /// A tree entry path was not valid UTF-8.
    #[error("non-utf8 path in tree: {0:?}")]
    NonUtf8Path(Vec<u8>),
}

fn ge<E: std::fmt::Display>(e: E) -> GitError {
    GitError::Git(e.to_string())
}

/// Who last changed one path, and when — see [`Repo::last_authors`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PathAuthor {
    /// The commit author's name, exactly as git recorded it. The bare identity:
    /// any prefix a format requires (OKF's `human:`, §7) is the renderer's.
    pub name: String,
    /// That commit's commit time, in seconds since the Unix epoch, UTC.
    ///
    /// Carried alongside the name because the two are one claim. Stamping a
    /// person's confirmation with the *render's* clock would date a review to a
    /// moment the reviewer had nothing to do with, and would make the bundle
    /// differ on every render for a document nobody touched.
    pub at: i64,
}

/// The blob id at `path` within `tree`, memoised on `(tree, path)`.
///
/// `None` means the path does not exist in that tree — which is a state the
/// caller compares like any other, because a path appearing (or disappearing) is
/// as much a change as its content differing.
fn blob_at<'p>(
    repo: &gix::Repository,
    memo: &mut std::collections::HashMap<(gix::ObjectId, &'p str), Option<gix::ObjectId>>,
    tree: gix::ObjectId,
    path: &'p str,
) -> Result<Option<gix::ObjectId>, GitError> {
    if let Some(hit) = memo.get(&(tree, path)) {
        return Ok(*hit);
    }
    let found = repo
        .find_object(tree)
        .map_err(ge)?
        .try_into_tree()
        .map_err(ge)?
        .lookup_entry(path.split('/').map(str::as_bytes))
        .map_err(ge)?
        .map(|e| e.id().detach());
    memo.insert((tree, path), found);
    Ok(found)
}

/// A discovered git repository.
pub struct Repo {
    inner: gix::Repository,
}

impl Repo {
    /// Discover the repository containing `path` (walking upwards to the `.git`).
    ///
    /// # Errors
    /// Returns [`GitError::Git`] if no repository is found or it cannot be opened.
    pub fn discover(path: &Path) -> Result<Self, GitError> {
        Ok(Self {
            inner: gix::discover(path).map_err(ge)?,
        })
    }

    /// The repository's *common* git directory. The cache lives under here so it
    /// is shared across linked worktrees (which each have their own git dir).
    #[must_use]
    pub fn common_dir(&self) -> &Path {
        self.inner.common_dir()
    }

    /// This worktree's git directory (per-worktree; the graph DB lives here).
    #[must_use]
    pub fn git_dir(&self) -> &Path {
        self.inner.git_dir()
    }

    /// The directory git actually looks in for hooks. Honours `core.hooksPath`
    /// (absolute, or relative to the working-tree root — else the git dir); when
    /// unset it is `<common git dir>/hooks`, so managed hooks are shared across
    /// linked worktrees. `roteiro init` installs into this so its hooks run
    /// wherever git expects them.
    #[must_use]
    pub fn hooks_dir(&self) -> std::path::PathBuf {
        let configured = self.inner.config_snapshot().string("core.hooksPath");
        // An empty `core.hooksPath` (e.g. `git -c core.hooksPath=`) means "unset".
        let configured = configured.filter(|c| !AsRef::<[u8]>::as_ref(c).is_empty());
        if let Some(configured) = configured {
            let bytes: &[u8] = configured.as_ref();
            let path = std::path::PathBuf::from(String::from_utf8_lossy(bytes).into_owned());
            if path.is_absolute() {
                return path;
            }
            let base = self.inner.workdir().unwrap_or_else(|| self.inner.git_dir());
            return base.join(path);
        }
        self.common_dir().join("hooks")
    }

    /// The working directory, if this is not a bare repository. The dirty
    /// overlay reads uncommitted file contents from here.
    #[must_use]
    pub fn workdir(&self) -> Option<&Path> {
        self.inner.workdir()
    }

    /// The hex git blob object id that `bytes` would have, without writing
    /// anything. Used to detect whether a working-copy file differs from the
    /// committed blob (same content ⇒ same id).
    ///
    /// # Errors
    /// Returns [`GitError::Git`] if hashing fails.
    pub fn blob_oid(&self, bytes: &[u8]) -> Result<String, GitError> {
        let id = gix::objs::compute_hash(self.inner.object_hash(), gix::objs::Kind::Blob, bytes)
            .map_err(ge)?;
        Ok(id.to_hex().to_string())
    }

    /// Hex object id of the tree at `HEAD`.
    ///
    /// # Errors
    /// Returns [`GitError::Git`] if `HEAD` cannot be resolved to a tree.
    pub fn head_tree_id(&self) -> Result<String, GitError> {
        let tree = self.inner.head_tree().map_err(ge)?;
        Ok(tree.id().to_hex().to_string())
    }

    /// Hex object id of the commit at `HEAD` — a stable permalink ref for the tree
    /// the graph was built from (used to build source links).
    ///
    /// # Errors
    /// Returns [`GitError::Git`] if `HEAD` cannot be resolved to a commit.
    pub fn head_commit_id(&self) -> Result<String, GitError> {
        Ok(self
            .inner
            .head_id()
            .map_err(ge)?
            .detach()
            .to_hex()
            .to_string())
    }

    /// Seconds since the Unix epoch of the `HEAD` commit's commit time, in UTC.
    ///
    /// Added for analyzer-asset provisioning: an advisory database that is a git
    /// checkout has no publication date of its own, and `cargo audit` reports
    /// none at all when it is pointed at a database with `--db` rather than
    /// resolving one itself. The commit time is the publication date, and it is
    /// what lets a result be labelled *possibly stale* with a number attached
    /// (ADR-0012).
    ///
    /// # Errors
    /// Returns [`GitError::Git`] if `HEAD` cannot be resolved to a commit or the
    /// commit carries no readable time.
    pub fn head_commit_time(&self) -> Result<i64, GitError> {
        let commit = self.inner.head_commit().map_err(ge)?;
        Ok(commit.time().map_err(ge)?.seconds)
    }

    /// Who last changed each of `paths`, and when — the equivalent of
    /// `git log -1 --format='%an %ct' -- <path>` for a whole set at once.
    ///
    /// Used to attribute the **authored** layer to a person, which is what puts a
    /// concept in OKF's human-reviewed trust tier (§5.3) rather than the
    /// machine-confirmed one. The `human:` prefix is applied by the renderer, not
    /// here — this returns the bare identity.
    ///
    /// # Per path, because the claim is per document
    ///
    /// The obvious cheap answer is the `HEAD` commit's author, and it is wrong in
    /// a way the format cannot survive: `verified: [{ by: human:<id> }]` asserts
    /// that *that person* stands behind *that document*, so attributing the whole
    /// repository to whoever pushed last records a confirmation nobody made. A
    /// bot merge at `HEAD` would mark every ADR as human-reviewed by the bot.
    ///
    /// # What "last changed" means here
    ///
    /// Walking newest-first by commit time, a commit changed a path when the blob
    /// at that path differs from the blob in **every** parent — the same
    /// definition `git log -- <path>` uses, so a merge that only carried a change
    /// across is not credited with making it. A path present in a root commit was
    /// changed by that commit.
    ///
    /// A path absent from the result was never resolved: the history ran out
    /// first (a shallow clone), a commit's parents could not be read (a partial
    /// clone), or the walk failed. The caller must read that as *no
    /// confirmation*, never as the tool's — substituting a machine actor would
    /// move a concept down a trust tier silently, which is worse than claiming
    /// nothing.
    ///
    /// Every commit this cannot fully compare is skipped rather than guessed at,
    /// for the same reason: the only wrong answer that costs anything here is a
    /// confident one.
    ///
    /// # Errors
    /// Returns [`GitError::Git`] if `HEAD` cannot be resolved or the history
    /// cannot be walked.
    pub fn last_authors(
        &self,
        paths: &std::collections::BTreeSet<String>,
    ) -> Result<std::collections::BTreeMap<String, PathAuthor>, GitError> {
        use std::collections::{BTreeMap, BTreeSet, HashMap};

        let mut out: BTreeMap<String, PathAuthor> = BTreeMap::new();
        if paths.is_empty() {
            return Ok(out);
        }
        let head = self.inner.head_id().map_err(ge)?.detach();

        // A local handle carrying an object cache. The walk reads each commit's
        // tree and its parents' trees, and every parent is itself visited later
        // in the walk, so without a cache the same objects are decoded twice.
        let mut repo = self.inner.clone();
        repo.object_cache_size_if_unset(8 * 1024 * 1024);

        // The shallow boundary, where the history a comparison needs is absent.
        // In a `fetch-depth: 1` checkout the paths that would be misattributed
        // there are *every* path, credited to whoever made the one commit
        // present — precisely the false claim this method exists to stop — so a
        // boundary commit resolves nothing.
        //
        // Two mechanisms refuse it, and measured by injection **either alone is
        // enough**: deleting this check leaves
        // `a_shallow_clone_claims_no_human_verifier_rather_than_the_wrong_one`
        // green, and so does reverting the all-or-nothing parent read below.
        // Only removing both makes it fail. The reason is that gix does not
        // report a boundary commit as parentless: it lists the parent ids, and
        // the *objects* behind them are what is missing, so the read below
        // already declines. This check is kept as the one that does not depend
        // on an object lookup failing — it names the condition git itself
        // records, and it is the cheaper of the two.
        let boundary: BTreeSet<gix::ObjectId> = repo
            .shallow_commits()
            .map_err(ge)?
            .map(|c| c.iter().copied().collect())
            .unwrap_or_default();

        let mut pending: BTreeSet<&str> = paths.iter().map(String::as_str).collect();
        // (tree id, path) -> blob id there. Keyed on the *tree* rather than the
        // commit so a parent looked up as a parent and later walked as a commit
        // is one lookup, not two.
        let mut memo: HashMap<(gix::ObjectId, &str), Option<gix::ObjectId>> = HashMap::new();

        let walk = repo
            .rev_walk([head])
            .sorting(gix::revision::walk::Sorting::ByCommitTime(
                gix::traverse::commit::simple::CommitTimeOrder::NewestFirst,
            ))
            .all()
            .map_err(ge)?;

        for info in walk {
            if pending.is_empty() {
                break;
            }
            let info = info.map_err(ge)?;
            if boundary.contains(&info.id) {
                continue;
            }
            let commit = info.object().map_err(ge)?;
            let tree_id = commit.tree_id().map_err(ge)?.detach();
            // **Every** parent, or none of this commit's answers. A parent that
            // cannot be read is not a parent that is absent: dropping it silently
            // shrinks the set this commit is compared against, and dropping the
            // last one turns the commit into an apparent root that introduced
            // everything it contains. Both directions produce an attribution, and
            // an attribution derived from history we could not read is the false
            // claim this whole method exists to avoid. A partial clone reaches
            // here without a `shallow` file to warn us.
            let parent_trees: Option<Vec<gix::ObjectId>> = info
                .parent_ids
                .iter()
                .map(|id| {
                    repo.find_object(*id)
                        .ok()
                        .and_then(|o| o.try_into_commit().ok())
                        .and_then(|c| c.tree_id().ok())
                        .map(gix::Id::detach)
                })
                .collect();
            // `collect` into an `Option<Vec<_>>` is the all-or-nothing above: one
            // unreadable parent makes the whole set `None`.
            let Some(parent_trees) = parent_trees else {
                continue;
            };

            let mut resolved: Vec<&str> = Vec::new();
            for path in &pending {
                let here = blob_at(&repo, &mut memo, tree_id, path)?;
                // A root commit introduces whatever it contains; otherwise the
                // commit changed the path only if no parent already had this blob.
                let changed = if parent_trees.is_empty() {
                    here.is_some()
                } else {
                    let mut differs = true;
                    for parent in &parent_trees {
                        if blob_at(&repo, &mut memo, *parent, path)? == here {
                            differs = false;
                            break;
                        }
                    }
                    differs
                };
                if changed {
                    resolved.push(path);
                }
            }
            if resolved.is_empty() {
                continue;
            }
            // Read the author only once a path actually resolved: it decodes the
            // commit's header, and most commits in the walk touch none of `paths`.
            let author = commit
                .author()
                .ok()
                .map(|a| a.name.to_string())
                .filter(|n| !n.trim().is_empty());
            let at = commit.time().map_err(ge)?.seconds;
            for path in resolved {
                pending.remove(path);
                if let Some(name) = author.clone() {
                    out.insert(path.to_owned(), PathAuthor { name, at });
                }
            }
        }
        Ok(out)
    }

    /// The `origin` remote's fetch URL, if one is configured — e.g. to derive a
    /// web "blob" base for source links. `None` when there is no `origin` remote.
    #[must_use]
    pub fn origin_url(&self) -> Option<String> {
        let remote = self.inner.find_remote("origin").ok()?;
        let url = remote.url(gix::remote::Direction::Fetch)?;
        Some(url.to_bstring().to_string())
    }

    /// Every blob reachable from the `HEAD` tree, with full paths.
    ///
    /// # Errors
    /// Returns [`GitError`] if the tree cannot be traversed or a path is not
    /// valid UTF-8.
    pub fn walk_blobs(&self) -> Result<Vec<BlobRef>, GitError> {
        let tree = self.inner.head_tree().map_err(ge)?;
        walk_tree_blobs(&tree)
    }

    /// Every blob reachable from an arbitrary commit-or-tree `rev` (a hex oid),
    /// with full paths — like [`Repo::walk_blobs`] but for any point in history,
    /// not just `HEAD`. A commit oid is peeled to its tree, so a submodule pin (a
    /// commit sha) works directly. The primitive for extracting a repo's graph at
    /// the version a spoke pins (ADR-0009 step 8 — version-pin resolution).
    ///
    /// # Errors
    /// Returns [`GitError`] if `rev` cannot be resolved to a tree, the tree cannot
    /// be traversed, or a path is not valid UTF-8.
    pub fn blobs_at(&self, rev: &str) -> Result<Vec<BlobRef>, GitError> {
        let tree = self.tree_by_rev(rev)?;
        walk_tree_blobs(&tree)
    }

    /// The hex tree id an arbitrary revspec resolves to (a commit peels to its
    /// tree) — an **O(1)** resolution that does not walk the tree, so it doubles as
    /// a cheap "does this ref exist?" check (ADR-0009 step 8b/8c).
    ///
    /// # Errors
    /// Returns [`GitError`] if `rev` cannot be resolved to a tree.
    pub fn tree_id_at(&self, rev: &str) -> Result<String, GitError> {
        Ok(self.tree_by_rev(rev)?.id().to_hex().to_string())
    }

    /// Every git submodule pinned in the `HEAD` tree, sorted by path: a gitlink
    /// (commit) entry gives the path and the commit it points at, enriched with
    /// its `.gitmodules` URL when declared. The pinned commit is the **version a
    /// deployment repo ships** (ADR-0009 derived facts). Empty when there are none.
    ///
    /// # Errors
    /// Returns [`GitError`] if the tree cannot be traversed, `.gitmodules` cannot
    /// be read, or a path is not valid UTF-8.
    pub fn submodules(&self) -> Result<Vec<Submodule>, GitError> {
        let tree = self.inner.head_tree().map_err(ge)?;
        self.submodules_in_tree(&tree)
    }

    /// Every git submodule pinned at an arbitrary commit/tree `rev`, sorted by path
    /// — like [`Repo::submodules`] but for a historical point, so a hub graph
    /// extracted at a pinned version (ADR-0009 step 8) carries its own submodules
    /// as they were then.
    ///
    /// # Errors
    /// As [`Repo::submodules`], plus if `rev` cannot be resolved to a tree.
    pub fn submodules_at(&self, rev: &str) -> Result<Vec<Submodule>, GitError> {
        let tree = self.tree_by_rev(rev)?;
        self.submodules_in_tree(&tree)
    }

    /// Collect the submodule gitlinks (and `.gitmodules` URLs) in `tree`.
    fn submodules_in_tree(&self, tree: &gix::Tree<'_>) -> Result<Vec<Submodule>, GitError> {
        let mut recorder = gix::traverse::tree::Recorder::default();
        tree.traverse().breadthfirst(&mut recorder).map_err(ge)?;

        let mut links: Vec<(String, String)> = Vec::new();
        let mut gitmodules: Option<gix::ObjectId> = None;
        for entry in &recorder.records {
            if entry.mode.is_commit() {
                let path = String::from_utf8(entry.filepath.clone().into())
                    .map_err(|e| GitError::NonUtf8Path(e.into_bytes()))?;
                links.push((path, entry.oid.to_hex().to_string()));
            } else if entry.mode.is_blob() && entry.filepath.as_slice() == b".gitmodules" {
                gitmodules = Some(entry.oid);
            }
        }
        self.assemble_submodules(links, gitmodules)
    }

    /// Every git submodule pinned in the **staged index** (the tree a commit would
    /// record), sorted by path. Same shape as [`Repo::submodules`] but reads the
    /// gitlinks (and `.gitmodules`) from the index, so the index-aware sync — the
    /// pre-commit gate — reflects a *staged* submodule bump, not the `HEAD` pin.
    ///
    /// # Errors
    /// As [`Repo::submodules`], plus index-load failure.
    pub fn index_submodules(&self) -> Result<Vec<Submodule>, GitError> {
        use gix::index::entry::Mode;
        let index = self.inner.index_or_load_from_head().map_err(ge)?;
        let mut links: Vec<(String, String)> = Vec::new();
        let mut gitmodules: Option<gix::ObjectId> = None;
        for entry in index.entries() {
            if entry.stage_raw() != 0 {
                continue;
            }
            let path = String::from_utf8(entry.path(&index).to_vec())
                .map_err(|e| GitError::NonUtf8Path(e.into_bytes()))?;
            if entry.mode == Mode::COMMIT {
                links.push((path, entry.id.to_hex().to_string()));
            } else if path == ".gitmodules"
                && matches!(entry.mode, Mode::FILE | Mode::FILE_EXECUTABLE)
            {
                gitmodules = Some(entry.id);
            }
        }
        self.assemble_submodules(links, gitmodules)
    }

    /// Assemble `(path, sha)` gitlinks into sorted [`Submodule`]s, resolving each
    /// path's URL from the `.gitmodules` blob at `gitmodules` (when present). Shared
    /// by the `HEAD`-tree and index submodule readers.
    fn assemble_submodules(
        &self,
        links: Vec<(String, String)>,
        gitmodules: Option<gix::ObjectId>,
    ) -> Result<Vec<Submodule>, GitError> {
        if links.is_empty() {
            return Ok(Vec::new());
        }
        let urls = match gitmodules {
            Some(oid) => {
                let bytes = self.read_blob(&oid.to_hex().to_string())?;
                parse_gitmodules(&String::from_utf8_lossy(&bytes))
            }
            None => std::collections::HashMap::new(),
        };
        let mut out: Vec<Submodule> = links
            .into_iter()
            .map(|(path, sha)| {
                let url = urls.get(&path).cloned();
                Submodule { path, sha, url }
            })
            .collect();
        out.sort_by(|a, b| a.path.cmp(&b.path));
        Ok(out)
    }

    /// **What a `--base <spec>` actually bound to** — the ref, the commit, and how
    /// that commit stands against its upstream (issue #649).
    ///
    /// # The defect this exists to make visible
    ///
    /// [`Repo::changed_between`] resolves its base with `rev_parse_single`, so the
    /// bare name `main` binds to the **local branch**, never to
    /// `refs/remotes/origin/main`. That is correct for `rev_parse_single` and it is
    /// what git itself does; the problem was that nothing surfaced the consequence.
    /// A local `main` seventeen commits behind its upstream answers a *different
    /// question* from the one that was asked, and answers it in output textually
    /// identical to a correct run: `review --base main` reported 33 changed files
    /// where the real footprint was 2, with `drift: []` and exit 0.
    ///
    /// Rebasing does not save you, which is what made it durable — rebasing the
    /// branch does not move the local `main` ref.
    ///
    /// # Why a superset is the *silent* case and divergence is the dangerous one
    ///
    /// When the base is an **ancestor** of its upstream ([`Upstream::ahead`] is 0),
    /// the diff is a strict superset of the true one: more files, all of yours
    /// included. Every drift item that would have been found is still found, so the
    /// gate still holds and the run looks *more* thorough rather than less. Nothing
    /// fails, which is why it went unnoticed for a whole session.
    ///
    /// When the two have **diverged** ([`Upstream::ahead`] and [`Upstream::behind`]
    /// are both non-zero), the diff can *omit* changes that exist on both sides of
    /// the fork, and then a clean verdict is worthless rather than merely wide.
    /// [`Upstream::diverged`] separates the two so a caller can say different
    /// things about them.
    ///
    /// # Errors
    /// Returns [`GitError::Git`] if `spec` cannot be resolved to a single commit,
    /// or if a reachability walk against the upstream fails.
    pub fn resolve_base(&self, spec: &str) -> Result<BaseResolution, GitError> {
        // Two reads of one spec, deliberately. `rev_parse` is the only one that
        // reports *which ref* the name bound to — the whole point here, since
        // `main` and `origin/main` are the two answers a reader has to be able to
        // tell apart — while `single()` yields the same commit `changed_between`
        // resolves. A spec that names no ref at all (a raw sha, `HEAD~3`) leaves
        // `reference` as `None`, which is honest: there is no upstream question to
        // ask about a commit nobody named.
        let parsed = self.inner.rev_parse(spec).map_err(ge)?;
        let reference = parsed
            .first_reference()
            .map(|r| r.name.as_bstr().to_string());
        let oid = parsed
            .single()
            .ok_or_else(|| GitError::Git(format!("`{spec}` names a range, not a single commit")))?
            .detach();

        let upstream = match reference.as_deref() {
            Some(name) => self.upstream_of(name, oid)?,
            None => None,
        };
        Ok(BaseResolution {
            spec: spec.to_owned(),
            reference,
            commit: oid.to_hex().to_string(),
            upstream,
        })
    }

    /// The remote-tracking ref configured for the local branch `reference`, with
    /// the two reachability counts, or `None` when there is no upstream to compare
    /// against.
    ///
    /// `None` is the ordinary answer for most inputs and is never an error: a
    /// remote-tracking ref (`origin/main`) has no upstream of its own, a tag has
    /// none, and a local branch that was never pushed has none. A caller that
    /// cannot find out whether a base is stale must proceed exactly as it did
    /// before rather than refuse, so every failure to answer here resolves to
    /// `None` — the base is still resolved and still reported, and only the
    /// staleness check is missing.
    fn upstream_of(
        &self,
        reference: &str,
        base: gix::ObjectId,
    ) -> Result<Option<Upstream>, GitError> {
        let Ok(full) = gix::refs::FullName::try_from(reference) else {
            return Ok(None);
        };
        // `Fetch`, not `Push`: the question is "has the world moved on since this
        // ref last caught up", which is what a fetch would bring in. A `pushRemote`
        // pointing elsewhere does not make the base any less stale.
        // A misconfigured tracking setting — a `branch.<name>.merge` that no fetch
        // refspec maps — lands here as `Some(Err(_))` and is treated as "no
        // upstream", not as a failed review.
        let Some(Ok(tracking)) = self
            .inner
            .branch_remote_tracking_ref_name(full.as_ref(), gix::remote::Direction::Fetch)
        else {
            return Ok(None);
        };
        let Ok(mut tracking_ref) = self.inner.find_reference(tracking.as_ref()) else {
            // Configured but not present: a branch whose upstream has never been
            // fetched into this clone. Nothing to compare against.
            return Ok(None);
        };
        let Ok(upstream_id) = tracking_ref.peel_to_id() else {
            return Ok(None);
        };
        let upstream = upstream_id.detach();

        // The overwhelmingly common case, and it costs nothing: an up-to-date base
        // needs no traversal at all. Short-circuited rather than left to the walk
        // because `with_hidden` is documented to be able to visit every commit when
        // the two sides are disjoint, and paying that on every `--base main` of a
        // healthy branch would be a real cost for a guaranteed pair of zeroes.
        let (behind, ahead) = if upstream == base {
            (0, 0)
        } else {
            (
                self.count_reachable(upstream, base)?,
                self.count_reachable(base, upstream)?,
            )
        };
        Ok(Some(Upstream {
            reference: tracking.as_bstr().to_string(),
            commit: upstream.to_hex().to_string(),
            behind,
            ahead,
        }))
    }

    /// Commits reachable from `tip` but not from `hidden` — `git rev-list --count
    /// hidden..tip`.
    fn count_reachable(
        &self,
        tip: gix::ObjectId,
        hidden: gix::ObjectId,
    ) -> Result<usize, GitError> {
        let walk = self
            .inner
            .rev_walk([tip])
            .with_hidden([hidden])
            .all()
            .map_err(ge)?;
        let mut n = 0usize;
        for info in walk {
            info.map_err(ge)?;
            n += 1;
        }
        Ok(n)
    }

    /// The tracked files that differ between `base` (any revspec — a branch,
    /// `HEAD~3`, a sha) and the current `HEAD`, sorted by path. Used for
    /// change-scoped tooling over a commit range (e.g. `roteiro review --base
    /// main`), distinct from [`Repo::changed_files`], which compares the working
    /// tree to `HEAD`. A path only in `HEAD` is added, only in `base` is deleted.
    ///
    /// Callers that report *what they compared against* should resolve the spec
    /// once with [`Repo::resolve_base`] and pass [`BaseResolution::commit`] here,
    /// so the commit named in the report and the commit actually diffed cannot be
    /// two different answers to one question.
    ///
    /// # Errors
    /// Returns [`GitError`] if `base` cannot be resolved to a tree, a tree cannot
    /// be traversed, or a path is not valid UTF-8.
    pub fn changed_between(&self, base: &str) -> Result<Vec<ChangedFile>, GitError> {
        let base_tree = self
            .inner
            .rev_parse_single(base)
            .map_err(ge)?
            .object()
            .map_err(ge)?
            .peel_to_tree()
            .map_err(ge)?;
        let base_oid = base_tree.id().to_hex().to_string();
        let head_oid = self.head_tree_id()?;

        // Reuse the subtree-pruning tree diff, then flatten to the `ChangedFile`
        // (path, status) shape this API exposes. `diff_trees` already sorts and
        // prunes unchanged subtrees, so this is O(change), not a full walk.
        let diff = self.diff_trees(&base_oid, &head_oid)?;
        // A tree diff's `changed` set conflates genuinely-new files with edits to
        // existing ones, so range review labels them `Modified` rather than
        // distinguishing `Added` (which would need the base file set).
        let mut out: Vec<ChangedFile> = diff
            .changed
            .into_iter()
            .map(|b| ChangedFile {
                path: b.path,
                status: ChangeStatus::Modified,
            })
            .chain(diff.deleted.into_iter().map(|path| ChangedFile {
                path,
                status: ChangeStatus::Deleted,
            }))
            .collect();
        out.sort_by(|a, b| a.path.cmp(&b.path));
        Ok(out)
    }

    /// Read the bytes of the blob with hex object id `oid`.
    ///
    /// # Errors
    /// Returns [`GitError::Git`] if the id is malformed or the object is absent.
    pub fn read_blob(&self, oid: &str) -> Result<Vec<u8>, GitError> {
        let id = gix::ObjectId::from_hex(oid.as_bytes()).map_err(ge)?;
        // `detach()` moves the owned data out without cloning; `Object` itself
        // implements `Drop`, so the bare field cannot be moved out directly.
        Ok(self.inner.find_object(id).map_err(ge)?.detach().data)
    }

    /// The bytes of a tracked file's **authored source**, from the tree named by
    /// `source`: the committed `HEAD` blob, the staged blob, or the file as it
    /// stands on disk (unstaged edits included, and *not* the git index).
    ///
    /// The `Worktree` reading matches [`crate::sync_worktree`], which the derived
    /// graph is built from, so the authored and derived layers stay consistent —
    /// see [`GraphSource`] for why that pairing is one type rather than two
    /// independent choices.
    ///
    /// Returns `Ok(None)` when a worktree file has been deleted, so the caller
    /// drops it.
    ///
    /// # Errors
    /// Returns [`GitError::Git`] if the blob cannot be read, or if reading the
    /// working-tree copy fails for any reason other than the file being absent.
    pub fn read_source(
        &self,
        blob: &BlobRef,
        source: GraphSource,
    ) -> Result<Option<Vec<u8>>, GitError> {
        match source {
            // Worktree: the file as it stands on disk (unstaged edits included),
            // or `None` if it was deleted there.
            GraphSource::Worktree => match self.workdir() {
                Some(workdir) => match std::fs::read(workdir.join(&blob.path)) {
                    Ok(bytes) => Ok(Some(bytes)),
                    Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
                    // Folded into `GitError::Git` with the path rather than
                    // carried as its own variant: `GitError` is not
                    // `#[non_exhaustive]`, so a new variant would break every
                    // downstream exhaustive match for a message this already
                    // preserves.
                    Err(e) => Err(GitError::Git(format!("reading {}: {e}", blob.path))),
                },
                None => Ok(Some(self.read_blob(&blob.oid)?)),
            },
            // Committed reads the `HEAD` blob; Index reads the staged blob — for
            // both, `blob.oid` is already the right object (the blob list came
            // from that tree), so read it directly.
            GraphSource::Committed | GraphSource::Index => Ok(Some(self.read_blob(&blob.oid)?)),
        }
    }

    /// Tracked files whose working-tree content differs from `HEAD` — the change
    /// about to be committed. A file is *changed* when its working-copy bytes hash
    /// to a different blob id than the committed one (content, not mtime), and
    /// *deleted* when it is absent from the working tree. Untracked new files are
    /// not reported (they are not in the `HEAD` tree). Same detection as
    /// [`crate::sync_worktree`], surfaced for change-scoped tooling.
    ///
    /// # Errors
    /// Returns [`GitError`] on a git failure. In a bare repo (no working tree)
    /// the change set is empty.
    pub fn changed_files(&self) -> Result<Vec<ChangedFile>, GitError> {
        let mut out = Vec::new();
        let Some(workdir) = self.workdir() else {
            return Ok(out);
        };
        for blob in self.walk_blobs()? {
            match std::fs::read(workdir.join(&blob.path)) {
                Ok(bytes) => {
                    if self.blob_oid(&bytes)? != blob.oid {
                        out.push(ChangedFile {
                            path: blob.path,
                            status: ChangeStatus::Modified,
                        });
                    }
                }
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => out.push(ChangedFile {
                    path: blob.path,
                    status: ChangeStatus::Deleted,
                }),
                Err(e) => return Err(GitError::Git(e.to_string())),
            }
        }
        // `walk_blobs` order is an implementation detail; sort so `roteiro review`
        // output is deterministic across platforms and gix versions.
        out.sort_by(|a, b| a.path.cmp(&b.path));
        Ok(out)
    }

    /// The **staged** files: each regular blob in the git index with its staged
    /// object id, sorted by path. This is the tree that a commit would record —
    /// unlike [`Repo::changed_files`] (the working tree) — so it lets tooling gate
    /// exactly what is about to be committed (the pre-commit index-aware `check`).
    /// Conflict (unmerged) entries, directories, submodules and symlinks are
    /// skipped.
    ///
    /// # Errors
    /// Returns [`GitError`] if the index cannot be loaded or a path is not valid
    /// UTF-8.
    pub fn index_files(&self) -> Result<Vec<BlobRef>, GitError> {
        use gix::index::entry::Mode;
        let index = self.inner.index_or_load_from_head().map_err(ge)?;
        let mut out = Vec::new();
        for entry in index.entries() {
            if entry.stage_raw() != 0 || !matches!(entry.mode, Mode::FILE | Mode::FILE_EXECUTABLE) {
                continue;
            }
            let path = String::from_utf8(entry.path(&index).to_vec())
                .map_err(|e| GitError::NonUtf8Path(e.into_bytes()))?;
            out.push(BlobRef {
                path,
                oid: entry.id.to_hex().to_string(),
            });
        }
        out.sort_by(|a, b| a.path.cmp(&b.path));
        Ok(out)
    }

    /// Every path the working tree has that `head_paths` does not — the files
    /// a commit would **add**, whether or not they have been staged yet.
    ///
    /// # Why this exists rather than `untracked_files` alone
    ///
    /// The obvious spelling of "new files in the working tree" is
    /// [`Repo::untracked_files`], and it is wrong in a way that reads as
    /// correct. The two sets classify against **different trees**:
    /// `untracked_files` is defined against the **index**, and a caller's
    /// `head_paths` comes from **HEAD**. So `git add` on a new file removes it
    /// from the untracked set without adding it to HEAD, and the union of the
    /// two has a hole exactly the size of "staged, not yet committed".
    ///
    /// That hole has been found three times, in three surfaces, each time as a
    /// silent wrong answer rather than a failure:
    ///
    /// - issue #636 — `sync` deleted a node from the graph on `git add`;
    /// - issue #649 — `review` said "no working-tree changes to review" on a
    ///   tree with a staged addition in it;
    /// - issue #657 — `check` reported **0 violations** on drift it had caught
    ///   one `git add` earlier, silencing the gate at the moment it matters most.
    ///
    /// Each was fixed where it was found, which left three copies of one rule.
    /// This is the rule, once, so the fourth surface inherits it instead of
    /// re-deriving it.
    ///
    /// `head_paths` is a parameter rather than something walked here because
    /// every caller already holds HEAD's paths for its own reasons; walking the
    /// tree again to re-derive them would make the shared version cost more than
    /// the copies it replaces.
    ///
    /// `.gitignore` is honoured, and the union states *how*: an ignored file is
    /// absent from the dirwalk, so it enters only by being in the index — which
    /// takes a deliberate `git add -f`. That is the right outcome rather than a
    /// leak, because force-adding overrides the ignore and the file will be
    /// committed regardless.
    ///
    /// # Errors
    /// Returns [`GitError`] if the dirwalk or the index cannot be read.
    pub fn added_since_head(
        &self,
        head_paths: &std::collections::BTreeSet<&str>,
    ) -> Result<std::collections::BTreeSet<String>, GitError> {
        // **Both** sources are filtered against HEAD, not only the index one.
        // `untracked_files` classifies against the index, so a path can be in
        // HEAD *and* reported untracked simultaneously: `git rm --cached f`
        // drops `f` from the index and leaves it on disk, and git then calls it
        // untracked while HEAD still carries it. Taking that set wholesale
        // labels a tracked file an addition. Found by Copilot on #656 and fixed
        // there inline; collapsing the call sites onto this helper would have
        // undone it, which is what the rebase conflict was really about.
        let mut out: std::collections::BTreeSet<String> = self
            .untracked_files()?
            .into_iter()
            .filter(|p| !head_paths.contains(p.as_str()))
            .collect();
        for entry in self.index_files()? {
            if !head_paths.contains(entry.path.as_str()) {
                out.insert(entry.path);
            }
        }
        Ok(out)
    }

    /// Untracked, non-ignored regular files in the working tree: everything the
    /// dirwalk finds that the **index** does not carry.
    ///
    /// Not "files in neither `HEAD` nor the index", which this said until #662
    /// pointed at the contradiction with [`Repo::added_since_head`] directly
    /// above. The set is defined against the index *alone*, so a path can be in
    /// `HEAD` and in here at once: `git rm --cached f` drops `f` from the index
    /// and leaves it on disk, and git then reports it untracked while `HEAD`
    /// still carries it.
    ///
    /// **This is not "the new files in the working tree".** It is defined against
    /// the **index**, so `git add` removes a file from it. A caller that unions
    /// this with a HEAD-derived set has a hole exactly the size of "staged, not
    /// yet committed" — which is issues #636, #649 and #657, three surfaces that
    /// each made that union by hand and each gave a silently wrong answer. Use
    /// [`Repo::added_since_head`] instead; it is that union, correct, in one place.
    ///
    /// Respects `.gitignore` / `.git/info/exclude` / global excludes, skips nested
    /// repositories and non-regular files (symlinks, dirs, submodules), and returns
    /// repository-relative, unix-separated paths, sorted. Empty in a bare repo.
    ///
    /// # Errors
    /// Returns [`GitError`] on a git failure or a non-UTF-8 path.
    pub fn untracked_files(&self) -> Result<Vec<String>, GitError> {
        use gix::dir::entry::{Kind, Status};
        use gix::dir::walk::EmissionMode;

        if self.inner.workdir().is_none() {
            return Ok(Vec::new());
        }
        // Classify the working tree against the index; emit each untracked file
        // (not whole collapsed dirs), leaving ignored files unemitted (the default)
        // so `.gitignore` is honoured.
        let index = self.inner.index_or_empty().map_err(ge)?;
        let options = self
            .inner
            .dirwalk_options()
            .map_err(ge)?
            .emit_untracked(EmissionMode::Matching);
        // A never-set interrupt flag: the walk is a bounded, synchronous pass, so
        // there is nothing to cancel it from. (`gix` wants an owned/static flag;
        // its private wrapper type isn't nameable, so build one via `Arc`.)
        let never = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let iter = self
            .inner
            .dirwalk_iter(index, std::iter::empty::<&str>(), never.into(), options)
            .map_err(ge)?;

        let mut out = Vec::new();
        for item in iter {
            let entry = item.map_err(ge)?.entry;
            // Only brand-new regular files; symlinks/dirs/submodules are excluded
            // by the `File` disk kind, ignored files by the emission mode above.
            if entry.status == Status::Untracked && entry.disk_kind == Some(Kind::File) {
                let path = String::from_utf8(entry.rela_path.into())
                    .map_err(|e| GitError::NonUtf8Path(e.into_bytes()))?;
                out.push(path);
            }
        }
        out.sort();
        Ok(out)
    }
}

/// Collect every blob reachable from `tree`, with full repository-relative paths.
fn walk_tree_blobs(tree: &gix::Tree<'_>) -> Result<Vec<BlobRef>, GitError> {
    let mut recorder = gix::traverse::tree::Recorder::default();
    tree.traverse().breadthfirst(&mut recorder).map_err(ge)?;
    let mut out = Vec::new();
    for entry in recorder.records {
        if !entry.mode.is_blob() {
            continue;
        }
        let path = String::from_utf8(entry.filepath.into())
            .map_err(|e| GitError::NonUtf8Path(e.into_bytes()))?;
        out.push(BlobRef {
            path,
            oid: entry.oid.to_hex().to_string(),
        });
    }
    Ok(out)
}

/// A git submodule pinned in a tree: its repo-relative path, the commit it points
/// at (the gitlink oid — the **version pin** a deployment ships), and its
/// configured URL from `.gitmodules` when registered there.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Submodule {
    /// Repo-relative path the submodule is mounted at.
    pub path: String,
    /// Hex commit id the gitlink points at (the pinned version).
    pub sha: String,
    /// The submodule's URL from `.gitmodules`, if declared there.
    pub url: Option<String>,
}

/// Parse a `.gitmodules` file into a `path → url` map. INI-like: each
/// `[submodule "<name>"]` section carries a `path` and a `url`.
fn parse_gitmodules(text: &str) -> std::collections::HashMap<String, String> {
    let mut map = std::collections::HashMap::new();
    let (mut path, mut url) = (None, None);
    let mut in_submodule = false;
    let mut flush = |path: &mut Option<String>, url: &mut Option<String>| {
        if let (Some(p), Some(u)) = (path.take(), url.take()) {
            map.insert(p, u);
        }
    };
    for line in text.lines() {
        let line = line.trim();
        if line.starts_with('[') {
            flush(&mut path, &mut url);
            in_submodule = line.starts_with("[submodule");
        } else if in_submodule {
            if let Some(v) = line
                .strip_prefix("path")
                .and_then(|r| r.trim_start().strip_prefix('='))
            {
                path = Some(v.trim().to_owned());
            } else if let Some(v) = line
                .strip_prefix("url")
                .and_then(|r| r.trim_start().strip_prefix('='))
            {
                url = Some(v.trim().to_owned());
            }
        }
    }
    flush(&mut path, &mut url);
    map
}

/// How a file changed relative to the comparison baseline — for review labelling.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChangeStatus {
    /// A new file, absent from the baseline (e.g. a brand-new untracked file).
    Added,
    /// Present on both sides, with different content.
    Modified,
    /// Removed from the working tree (or the `HEAD` side of a range).
    Deleted,
}

impl ChangeStatus {
    /// Stable lowercase label (`added` | `modified` | `deleted`).
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Added => "added",
            Self::Modified => "modified",
            Self::Deleted => "deleted",
        }
    }
}

/// What a review's `--base <spec>` resolved to — see [`Repo::resolve_base`].
///
/// Serialisable because a report that does not say what it compared against
/// cannot be checked against the question it was asked. Issue #649's whole
/// complaint about `review` was that its output under-describes its own basis:
/// the diff was missing, and so was this.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct BaseResolution {
    /// The revspec exactly as it was given on the command line.
    ///
    /// Kept beside [`BaseResolution::reference`] rather than replaced by it,
    /// because the gap between the two *is* the defect: `main` and
    /// `refs/heads/main` printed together are what let a reader see that they did
    /// not ask for `refs/remotes/origin/main`.
    pub spec: String,
    /// The full name of the ref the spec bound to (`refs/heads/main`), or `None`
    /// when the spec named no ref — a raw sha, `HEAD~3`.
    #[serde(rename = "ref", skip_serializing_if = "Option::is_none")]
    pub reference: Option<String>,
    /// The commit it resolved to, in full hex.
    pub commit: String,
    /// How that commit stands against its upstream, when it has one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub upstream: Option<Upstream>,
}

impl BaseResolution {
    /// The first twelve hex digits of [`BaseResolution::commit`], for a summary
    /// line.
    ///
    /// Twelve rather than git's default seven: seven is chosen for typing, and
    /// this is chosen for *comparing* — the reader's next move is
    /// `git rev-parse --short main origin/main`, whose seven-digit answer is a
    /// prefix of this one, so the comparison still works in the direction it is
    /// actually made.
    #[must_use]
    pub fn short_commit(&self) -> &str {
        let n = self.commit.len().min(12);
        &self.commit[..n]
    }
}

/// The remote-tracking ref a resolved base is measured against, and the two
/// reachability counts that say how far apart they are.
///
/// Both counts, never one. "Behind by 17" and "behind by 17, ahead by 3" are
/// different situations with different consequences — the first over-reports a
/// change, the second can *omit* it — and a single number could not tell them
/// apart. See [`Repo::resolve_base`].
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct Upstream {
    /// Full name of the tracking ref (`refs/remotes/origin/main`).
    #[serde(rename = "ref")]
    pub reference: String,
    /// The commit it points at, in full hex.
    pub commit: String,
    /// Commits the upstream has that the base does not — `base..upstream`.
    pub behind: usize,
    /// Commits the base has that the upstream does not — `upstream..base`.
    pub ahead: usize,
}

impl Upstream {
    /// The first twelve hex digits of [`Upstream::commit`]; see
    /// [`BaseResolution::short_commit`].
    #[must_use]
    pub fn short_commit(&self) -> &str {
        let n = self.commit.len().min(12);
        &self.commit[..n]
    }

    /// Whether the base is missing commits its upstream has — the diff is then a
    /// superset of the true one, which is the *silent* failure: more files, all of
    /// yours included, so nothing fails and the run reads as more thorough.
    #[must_use]
    pub fn is_behind(&self) -> bool {
        self.behind > 0
    }

    /// Whether the two have genuinely forked. This is the case a clean verdict
    /// actively misleads about, because the diff can omit changes present on both
    /// sides of the fork.
    #[must_use]
    pub fn diverged(&self) -> bool {
        self.behind > 0 && self.ahead > 0
    }
}

/// A file that differs between the working tree (or a base revision) and `HEAD`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChangedFile {
    /// Repository-relative path.
    pub path: String,
    /// How the file changed.
    pub status: ChangeStatus,
}

/// The blob-level difference between two trees: paths added or modified (with
/// their new blob oid) and paths deleted. See [`Repo::diff_trees`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TreeDiff {
    /// Blobs whose *tree entry* differs from the old tree — a changed blob oid,
    /// or a mode change (e.g. the executable bit) on otherwise-identical content —
    /// as `(path, new blob oid)`. These are the paths to re-extract; a mode-only
    /// change re-extracts to identical facts (extraction is content-addressed), a
    /// harmless cache hit.
    pub changed: Vec<BlobRef>,
    /// Blobs present in the old tree but absent from the new — paths whose facts
    /// must be dropped.
    pub deleted: Vec<String>,
}

impl Repo {
    /// The blob-level diff between two tree object ids (`old` → `new`), pruning
    /// unchanged subtrees: gix descends only into subtrees whose oid differs, so
    /// the cost is proportional to the *change*, not the tree size. Renames are
    /// reported as a delete plus an add (rewrite tracking is off), which is what
    /// the path-scoped extractor wants. Results are sorted by path for determinism.
    ///
    /// This is the incremental-sync counterpart to [`Repo::walk_blobs`]: given the
    /// last-synced tree and `HEAD`, it yields exactly the paths that changed.
    ///
    /// # Errors
    /// Returns [`GitError`] if either id is not a tree, the diff fails, or a path
    /// is not valid UTF-8.
    pub fn diff_trees(&self, old: &str, new: &str) -> Result<TreeDiff, GitError> {
        let old_tree = self.tree_by_hex(old)?;
        let new_tree = self.tree_by_hex(new)?;

        let mut changed = Vec::new();
        let mut deleted = Vec::new();
        let mut err: Option<GitError> = None;

        let mut platform = old_tree.changes().map_err(ge)?;
        platform.options(|o| {
            o.track_rewrites(None);
        });
        platform
            .for_each_to_obtain_tree(&new_tree, |change| {
                use gix::object::tree::diff::Change;
                let record = |path: &gix::bstr::BStr| -> Result<String, GitError> {
                    String::from_utf8(path.to_vec())
                        .map_err(|e| GitError::NonUtf8Path(e.into_bytes()))
                };
                match change {
                    Change::Addition {
                        location,
                        entry_mode,
                        id,
                        ..
                    }
                    | Change::Modification {
                        location,
                        entry_mode,
                        id,
                        ..
                    } => {
                        if entry_mode.is_blob() {
                            match record(location) {
                                Ok(path) => changed.push(BlobRef {
                                    path,
                                    oid: id.to_hex().to_string(),
                                }),
                                Err(e) => err = Some(e),
                            }
                        }
                    }
                    Change::Deletion {
                        location,
                        entry_mode,
                        ..
                    } => {
                        if entry_mode.is_blob() {
                            match record(location) {
                                Ok(path) => deleted.push(path),
                                Err(e) => err = Some(e),
                            }
                        }
                    }
                    // Rewrite tracking is disabled, so renames arrive as
                    // Deletion + Addition; this arm is unreachable in practice.
                    Change::Rewrite { .. } => {}
                }
                Ok::<_, std::convert::Infallible>(gix::object::tree::diff::Action::Continue(()))
            })
            .map_err(ge)?;

        if let Some(e) = err {
            return Err(e);
        }
        changed.sort_by(|a, b| a.path.cmp(&b.path));
        deleted.sort();
        Ok(TreeDiff { changed, deleted })
    }

    /// Resolve a hex object id to a [`gix::Tree`].
    fn tree_by_hex(&self, hex: &str) -> Result<gix::Tree<'_>, GitError> {
        let id = gix::ObjectId::from_hex(hex.as_bytes()).map_err(ge)?;
        self.inner
            .find_object(id)
            .map_err(ge)?
            .peel_to_tree()
            .map_err(ge)
    }

    /// Resolve **any git revspec** — a sha, a tag, a branch, `HEAD~1` — to its
    /// tree. Unlike [`Repo::tree_by_hex`] (raw oids only), this accepts the tag /
    /// branch names the pinned-version resolution (`--hub-rev`, an image tag) can
    /// carry. Mirrors the resolution in [`Repo::changed_between`].
    fn tree_by_rev(&self, rev: &str) -> Result<gix::Tree<'_>, GitError> {
        self.inner
            .rev_parse_single(rev)
            .map_err(ge)?
            .object()
            .map_err(ge)?
            .peel_to_tree()
            .map_err(ge)
    }
}

#[cfg(test)]
mod tests {
    use super::parse_gitmodules;

    #[test]
    fn parse_gitmodules_maps_path_to_url_in_either_field_order() {
        let text = "\
[submodule \"vendor/app\"]\n\
\tpath = vendor/app\n\
\turl = https://github.com/acme/app.git\n\
[submodule \"libs/util\"]\n\
\turl = git@github.com:acme/util.git\n\
\tpath = libs/util\n";
        let map = parse_gitmodules(text);
        assert_eq!(
            map.get("vendor/app").map(String::as_str),
            Some("https://github.com/acme/app.git")
        );
        // URL declared before path in its section still maps.
        assert_eq!(
            map.get("libs/util").map(String::as_str),
            Some("git@github.com:acme/util.git")
        );
        assert_eq!(map.len(), 2);
    }

    #[test]
    fn parse_gitmodules_ignores_non_submodule_sections() {
        let map = parse_gitmodules("[core]\n\tbare = false\n[submodule \"a\"]\npath=a\nurl=u\n");
        assert_eq!(map.len(), 1);
        assert_eq!(map.get("a").map(String::as_str), Some("u"));
    }
}