githttp-fs 1.0.7

A git-backed content management database served over HTTP
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
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
// githttp-fs
//
// Git-based Content Management System
// Copyright: 2026, Valerian Saliou <valerian@valeriansaliou.name>
// License: Mozilla Public License v2.0 (MPL v2.0)

use chrono::{DateTime, Utc};
use git2::build::TreeUpdateBuilder;
use git2::{
    Delta, DiffFindOptions, DiffFormat, DiffOptions, FileMode, Oid, Repository, Signature, Sort,
};
use serde::Serialize;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use crate::error::AppError;

/// A node in the repository file tree returned by the list endpoint.
/// Serialises with a `"type"` discriminant field so clients can distinguish
/// files from directories without inspecting the presence of `children`.
#[derive(Debug, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum TreeNode {
    File {
        name: String,
    },
    Directory {
        name: String,
        children: Vec<TreeNode>,
    },
}

#[derive(Debug, Serialize)]
pub struct CommitAuthor {
    pub name: String,
    pub email: String,
}

#[derive(Debug, Serialize)]
pub struct CommitSummary {
    pub sha: String,
    pub message: String,
    pub author: CommitAuthor,
    pub committed_at: DateTime<Utc>,
}

#[derive(Debug, Serialize)]
pub struct CommitDetail {
    pub sha: String,
    pub message: String,
    pub author: CommitAuthor,
    pub committed_at: DateTime<Utc>,
    pub files: Vec<CommitFileDetail>,
}

#[derive(Debug, Serialize)]
pub struct CommitFileDetail {
    pub path: String,
    /// "created" | "updated" | "deleted" | "moved"
    pub change: String,
    /// Only present for moved files — the previous path.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from_path: Option<String>,
    /// Full file content at this commit. Empty string for deleted files.
    pub content: String,
    /// Unified diff for this file.
    pub diff: String,
}

/// Describes a single file change that occurred in a commit.
/// Used internally to drive hook delivery.
#[derive(Debug, Clone)]
pub enum FileChange {
    Created {
        path: String,
        content: String,
    },
    Updated {
        path: String,
        content: String,
    },
    Deleted {
        path: String,
    },
    Moved {
        from_path: String,
        to_path: String,
        content: String,
    },
}

/// Internal record used while building per-file commit details.
struct DeltaRecord {
    status: Delta,
    old_oid: Oid,
    new_oid: Oid,
    old_path: Option<PathBuf>,
    new_path: Option<PathBuf>,
}

// ---------------------------------------------------------------------------
// GitUtils — private low-level helpers shared across all operation groups
// ---------------------------------------------------------------------------

struct GitUtils;

impl GitUtils {
    fn git_signature<'a>(
        author_name: &'a str,
        author_email: &'a str,
    ) -> Result<Signature<'a>, AppError> {
        if author_name.trim().is_empty() {
            return Err(AppError::InvalidOperation {
                reason: "author.name must not be empty".to_string(),
            });
        }
        if author_email.trim().is_empty() {
            return Err(AppError::InvalidOperation {
                reason: "author.email must not be empty".to_string(),
            });
        }

        tracing::trace!(author_name = %author_name, author_email = %author_email, "creating git signature");

        Signature::now(author_name, author_email).map_err(AppError::Git)
    }

    fn timestamp_from_git_time(git_time: git2::Time) -> DateTime<Utc> {
        DateTime::from_timestamp(git_time.seconds(), 0).unwrap_or(DateTime::UNIX_EPOCH)
    }

    /// Opens an existing tenant repository, mapping a missing directory to a
    /// 404-friendly `TenantNotFound` error rather than a generic git failure.
    fn open_tenant_repo(repo_path: &Path, tenant_id: &str) -> Result<Repository, AppError> {
        if !repo_path.exists() {
            tracing::debug!(tenant_id = %tenant_id, "tenant repository not found");

            return Err(AppError::TenantNotFound {
                tenant_id: tenant_id.to_string(),
            });
        }

        tracing::trace!(tenant_id = %tenant_id, path = %repo_path.display(), "opening tenant repository");

        Repository::open(repo_path).map_err(AppError::Git)
    }

    /// Opens an existing repo or initialises a new one with an empty root commit
    /// so that HEAD is always valid for subsequent operations.
    fn open_or_init_repo(
        repo_path: &Path,
        author_name: &str,
        author_email: &str,
    ) -> Result<Repository, AppError> {
        if repo_path.join(".git").exists() {
            tracing::trace!(path = %repo_path.display(), "opening existing repository");

            return Repository::open(repo_path).map_err(AppError::Git);
        }

        tracing::info!(path = %repo_path.display(), "initialising new tenant repository");

        std::fs::create_dir_all(repo_path)?;

        let repo = Repository::init(repo_path)?;
        let signature = Self::git_signature(author_name, author_email)?;

        // An empty tree is required for the root commit so that HEAD is valid.
        tracing::trace!(path = %repo_path.display(), "writing empty tree for root commit");

        let empty_tree_id = repo.treebuilder(None)?.write()?;
        let empty_tree = repo.find_tree(empty_tree_id)?;

        let root_oid = repo.commit(
            Some("HEAD"),
            &signature,
            &signature,
            "chore: initialize",
            &empty_tree,
            &[],
        )?;

        tracing::debug!(path = %repo_path.display(), sha = %root_oid, "root commit created");

        drop(empty_tree);

        Ok(repo)
    }

    /// Reads a blob's content from `tree` at `file_path` and decodes it as UTF-8.
    fn blob_content_from_tree(
        repo: &Repository,
        tree: &git2::Tree<'_>,
        file_path: &str,
    ) -> Result<String, AppError> {
        tracing::trace!(path = %file_path, "reading blob from tree");

        let tree_entry =
            tree.get_path(Path::new(file_path))
                .map_err(|_err| AppError::FileNotFound {
                    path: file_path.to_string(),
                })?;

        let blob = repo.find_blob(tree_entry.id())?;

        tracing::trace!(path = %file_path, blob_id = %tree_entry.id(), size = blob.size(), "blob found");

        std::str::from_utf8(blob.content())
            .map(|text| text.to_string())
            .map_err(|_err| AppError::InvalidUtf8 {
                path: file_path.to_string(),
            })
    }

    fn path_string(path: Option<&Path>) -> String {
        path.map(|p| p.to_string_lossy().into_owned())
            .unwrap_or_default()
    }

    /// Builds a recursive `TreeNode` tree from a flat list of file paths plus
    /// an explicit list of directory stub paths (directories whose contents
    /// were not walked due to a depth limit). Directories are sorted before files
    /// at each level; entries within each group are sorted alphabetically.
    fn build_tree(
        flat: Vec<String>,
        stubs: Vec<String>,
        max_depth: Option<usize>,
    ) -> Vec<TreeNode> {
        enum NodeBuilder {
            File,
            Dir(BTreeMap<String, NodeBuilder>),
        }

        fn insert(
            dir: &mut BTreeMap<String, NodeBuilder>,
            components: &[&str],
            max_depth: Option<usize>,
            current_depth: usize,
        ) {
            match components {
                [] => {}
                [name] => {
                    dir.insert(name.to_string(), NodeBuilder::File);
                }
                [name, rest @ ..] => {
                    if let Some(max) = max_depth {
                        if current_depth >= max {
                            dir.entry(name.to_string())
                                .or_insert_with(|| NodeBuilder::Dir(BTreeMap::new()));
                            return;
                        }
                    }
                    let child = dir
                        .entry(name.to_string())
                        .or_insert_with(|| NodeBuilder::Dir(BTreeMap::new()));

                    if let NodeBuilder::Dir(children) = child {
                        insert(children, rest, max_depth, current_depth + 1);
                    }
                }
            }
        }

        fn insert_stub(dir: &mut BTreeMap<String, NodeBuilder>, components: &[&str]) {
            match components {
                [] => {}
                [name] => {
                    dir.entry(name.to_string())
                        .or_insert_with(|| NodeBuilder::Dir(BTreeMap::new()));
                }
                [name, rest @ ..] => {
                    let child = dir
                        .entry(name.to_string())
                        .or_insert_with(|| NodeBuilder::Dir(BTreeMap::new()));
                    if let NodeBuilder::Dir(children) = child {
                        insert_stub(children, rest);
                    }
                }
            }
        }

        fn convert(name: String, node: NodeBuilder) -> TreeNode {
            match node {
                NodeBuilder::File => TreeNode::File { name },
                NodeBuilder::Dir(children) => {
                    let mut dirs: Vec<TreeNode> = Vec::new();
                    let mut files: Vec<TreeNode> = Vec::new();

                    for (child_name, child_node) in children {
                        match child_node {
                            NodeBuilder::Dir(_) => dirs.push(convert(child_name, child_node)),
                            NodeBuilder::File => files.push(convert(child_name, child_node)),
                        }
                    }

                    TreeNode::Directory {
                        name,
                        children: dirs.into_iter().chain(files).collect(),
                    }
                }
            }
        }

        let mut root: BTreeMap<String, NodeBuilder> = BTreeMap::new();

        for path in flat {
            let components: Vec<&str> = path.split('/').collect();
            insert(&mut root, &components, max_depth, 1);
        }

        for stub_path in stubs {
            let components: Vec<&str> = stub_path.split('/').collect();
            insert_stub(&mut root, &components);
        }

        let mut dirs: Vec<TreeNode> = Vec::new();
        let mut files: Vec<TreeNode> = Vec::new();

        for (name, node) in root {
            match node {
                NodeBuilder::Dir(_) => dirs.push(convert(name, node)),
                NodeBuilder::File => files.push(convert(name, node)),
            }
        }

        dirs.into_iter().chain(files).collect()
    }
}

// ---------------------------------------------------------------------------
// GitLocks — stale lock file detection and cleanup
// ---------------------------------------------------------------------------

pub struct GitLocks;

impl GitLocks {
    /// Removes `.git/index.lock` if it is older than 30 seconds.
    /// A stale lock is left behind when a process is killed mid-operation.
    pub fn cleanup_stale_index_lock(repo_path: &Path) -> Result<(), AppError> {
        const STALE_LOCK_THRESHOLD_SECS: u64 = 30;

        let lock_path = repo_path.join(".git").join("index.lock");

        let metadata = match std::fs::metadata(&lock_path) {
            Ok(metadata) => metadata,
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(()),
            Err(err) => return Err(AppError::Io(err)),
        };

        let modified_time = metadata.modified()?;

        let lock_age = std::time::SystemTime::now()
            .duration_since(modified_time)
            .unwrap_or_default();

        if lock_age.as_secs() > STALE_LOCK_THRESHOLD_SECS {
            tracing::warn!(
                "Removing stale git lock file at {:?} (age: {}s)",
                lock_path,
                lock_age.as_secs()
            );

            if let Err(err) = std::fs::remove_file(&lock_path) {
                // Another worker may have cleaned the lock in the meantime.
                if err.kind() != std::io::ErrorKind::NotFound {
                    return Err(AppError::Io(err));
                }
            }
        }

        Ok(())
    }

    /// Walks `repos_root` once on startup and removes any leftover `.git/index.lock`
    /// regardless of age — no live operation can hold a lock at boot.
    pub fn cleanup_all_stale_locks(repos_root: &Path) {
        let collections_dir = match std::fs::read_dir(repos_root) {
            Ok(d) => d,
            Err(_) => return,
        };

        for collection_entry_result in collections_dir {
            let Ok(collection_entry) = collection_entry_result else {
                continue;
            };

            let collection_path = collection_entry.path();

            if !collection_path.is_dir() {
                continue;
            }

            let tenants_dir = match std::fs::read_dir(&collection_path) {
                Ok(d) => d,
                Err(_) => continue,
            };

            for tenant_entry_result in tenants_dir {
                let Ok(tenant_entry) = tenant_entry_result else {
                    continue;
                };

                let lock_path = tenant_entry.path().join(".git").join("index.lock");

                if lock_path.exists() {
                    tracing::warn!(
                        "Removing stale git lock file found on startup: {:?}",
                        lock_path
                    );

                    if let Err(remove_err) = std::fs::remove_file(&lock_path) {
                        tracing::error!(
                            "Failed to remove stale lock {:?}: {}",
                            lock_path,
                            remove_err
                        );
                    }
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// GitMaintenance — background loose-object packing and index refresh
// ---------------------------------------------------------------------------

pub struct GitMaintenance;

impl GitMaintenance {
    /// Packs every loose object into a single new packfile (via libgit2 — no
    /// dependency on a `git` binary) and deletes the packed loose files, then
    /// refreshes the on-disk index to match HEAD so `git status` stays
    /// meaningful for humans (the write path never touches the index).
    ///
    /// Must be called while holding the tenant write lock: object writes only
    /// happen under that lock, so the loose object set is frozen. Concurrent
    /// reads are safe — libgit2 refreshes its pack backends on a missed
    /// lookup, so a reader that raced the loose-file deletion finds the
    /// object in the new pack.
    ///
    /// Returns the number of loose objects that were packed.
    pub fn run(repo_path: &Path) -> Result<usize, AppError> {
        // The tenant may have been deleted while the timer was armed.
        if !repo_path.join(".git").exists() {
            tracing::debug!(path = %repo_path.display(), "repository gone, skipping maintenance");

            return Ok(0);
        }

        let repo = Repository::open(repo_path)?;

        let loose_objects = Self::enumerate_loose_objects(repo_path)?;

        tracing::debug!(
            path = %repo_path.display(),
            loose_objects = loose_objects.len(),
            "running repository maintenance"
        );

        if !loose_objects.is_empty() {
            let mut pack_builder = repo.packbuilder()?;

            for (oid, _) in &loose_objects {
                pack_builder.insert_object(*oid, None)?;
            }

            // Stream the pack straight into the ODB — this writes both the
            // .pack and its .idx under .git/objects/pack.
            let odb = repo.odb()?;
            let mut pack_writer = odb.packwriter()?;

            pack_builder.foreach(|chunk| {
                use std::io::Write;

                pack_writer.write_all(chunk).is_ok()
            })?;

            pack_writer.commit()?;

            // Only files that made it into the pack are deleted, so a failure
            // above never loses objects. Empty fan-out directories are pruned
            // best-effort (`remove_dir` refuses non-empty directories).
            for (_, loose_path) in &loose_objects {
                let _ = std::fs::remove_file(loose_path);
            }

            let fanout_dirs: std::collections::HashSet<PathBuf> = loose_objects
                .iter()
                .filter_map(|(_, loose_path)| loose_path.parent().map(PathBuf::from))
                .collect();

            for fanout_dir in fanout_dirs {
                let _ = std::fs::remove_dir(fanout_dir);
            }
        }

        // Refresh the on-disk index to HEAD. Clean a stale index.lock first —
        // this is the only code path left that writes the index.
        GitLocks::cleanup_stale_index_lock(repo_path)?;

        let head_tree = repo.head()?.peel_to_commit()?.tree()?;
        let mut index = repo.index()?;

        index.read_tree(&head_tree)?;
        index.write()?;

        Ok(loose_objects.len())
    }

    /// Walks `.git/objects/` and returns every loose object with its file
    /// path. Non-object entries (`pack/`, `info/`, temporary files) are
    /// skipped by the hex-name filters.
    fn enumerate_loose_objects(repo_path: &Path) -> Result<Vec<(Oid, PathBuf)>, AppError> {
        let objects_dir = repo_path.join(".git").join("objects");
        let mut loose_objects: Vec<(Oid, PathBuf)> = Vec::new();

        let fanout_entries = match std::fs::read_dir(&objects_dir) {
            Ok(entries) => entries,
            Err(_) => return Ok(loose_objects),
        };

        for fanout_entry in fanout_entries.flatten() {
            let fanout_name = fanout_entry.file_name();

            let Some(prefix) = fanout_name.to_str() else {
                continue;
            };

            if prefix.len() != 2 || !prefix.bytes().all(|byte| byte.is_ascii_hexdigit()) {
                continue;
            }

            let Ok(object_entries) = std::fs::read_dir(fanout_entry.path()) else {
                continue;
            };

            for object_entry in object_entries.flatten() {
                let object_name = object_entry.file_name();

                let Some(suffix) = object_name.to_str() else {
                    continue;
                };

                if let Ok(oid) = Oid::from_str(&format!("{}{}", prefix, suffix)) {
                    loose_objects.push((oid, object_entry.path()));
                }
            }
        }

        Ok(loose_objects)
    }
}

// ---------------------------------------------------------------------------
// GitFiles — file CRUD operations
// ---------------------------------------------------------------------------

pub struct GitFiles;

impl GitFiles {
    pub fn list_files(
        repo_path: &Path,
        tenant_id: &str,
        path_prefix: Option<&str>,
        maximum_depth: Option<usize>,
        page: usize,
        per_page: usize,
    ) -> Result<(Vec<TreeNode>, bool), AppError> {
        tracing::debug!(tenant_id = %tenant_id, path_prefix = ?path_prefix, maximum_depth = ?maximum_depth, page = page, per_page = per_page, "listing files");

        let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
        let head_commit = repo.head()?.peel_to_commit()?;

        tracing::trace!(tenant_id = %tenant_id, head_sha = %head_commit.id(), "resolved HEAD for file listing");

        let head_tree = head_commit.tree()?;

        // Resolve the prefix subtree directly so the walk never visits unrelated
        // directories. An absent or non-directory prefix yields an empty result.
        let walk_tree: git2::Tree<'_> = match path_prefix.filter(|p| !p.is_empty()) {
            Some(prefix) => match head_tree.get_path(Path::new(prefix)) {
                Ok(entry) => match repo.find_tree(entry.id()) {
                    Ok(tree) => tree,
                    Err(_) => return Ok((vec![], false)),
                },
                Err(_) => return Ok((vec![], false)),
            },
            None => head_tree,
        };

        // The listing root's immediate entries are already in memory as part
        // of the tree object — no further object reads are needed to
        // enumerate them. Sorting mirrors the response order (directories
        // first, then files, both alphabetical), so the page window is
        // decided before a single subtree is opened: off-page directories
        // are never visited at all.
        let mut root_dirs: Vec<(String, Oid)> = Vec::new();
        let mut root_files: Vec<String> = Vec::new();

        for entry in walk_tree.iter() {
            let Ok(name) = entry.name() else {
                continue;
            };

            match entry.kind() {
                Some(git2::ObjectType::Tree) => root_dirs.push((name.to_string(), entry.id())),
                Some(git2::ObjectType::Blob) => root_files.push(name.to_string()),
                _ => {}
            }
        }

        root_dirs.sort_by(|left, right| left.0.cmp(&right.0));
        root_files.sort();

        let total = root_dirs.len() + root_files.len();
        let offset = ((page - 1) * per_page).min(total);
        let has_more = total > offset + per_page;

        enum RootEntry {
            Directory(String, Oid),
            File(String),
        }

        let page_entries: Vec<RootEntry> = root_dirs
            .into_iter()
            .map(|(name, oid)| RootEntry::Directory(name, oid))
            .chain(root_files.into_iter().map(RootEntry::File))
            .skip(offset)
            .take(per_page)
            .collect();

        let mut nodes: Vec<TreeNode> = Vec::with_capacity(page_entries.len());

        for root_entry in page_entries {
            match root_entry {
                RootEntry::File(name) => nodes.push(TreeNode::File { name }),
                RootEntry::Directory(name, oid) => {
                    // maximum_depth counts levels from the listing root, so a
                    // depth-1 listing renders every directory as a childless
                    // stub without opening its subtree.
                    if maximum_depth == Some(1) {
                        nodes.push(TreeNode::Directory {
                            name,
                            children: Vec::new(),
                        });

                        continue;
                    }

                    let subtree = repo.find_tree(oid)?;

                    // Depth limits below are relative to this subtree, which
                    // sits one level down from the listing root.
                    let subtree_max_depth = maximum_depth.map(|max| max - 1);
                    let children = Self::collect_subtree(&subtree, subtree_max_depth)?;

                    nodes.push(TreeNode::Directory { name, children });
                }
            }
        }

        tracing::debug!(tenant_id = %tenant_id, page = page, returned = nodes.len(), has_more = has_more, "file listing complete");

        Ok((nodes, has_more))
    }

    /// Recursively walks one paged root directory and builds its child nodes.
    /// Only directories inside the requested page window ever reach this
    /// point. Blob objects are never opened — names and kinds come from the
    /// tree objects alone.
    fn collect_subtree(
        subtree: &git2::Tree<'_>,
        max_depth: Option<usize>,
    ) -> Result<Vec<TreeNode>, AppError> {
        let mut flat: Vec<String> = Vec::new();
        let mut dir_stubs: Vec<String> = Vec::new();

        subtree.walk(git2::TreeWalkMode::PreOrder, |root, entry| {
            // Depth of this entry relative to the subtree: "" = depth 1, "a/" = depth 2, …
            let entry_depth = root.chars().filter(|c| *c == '/').count() + 1;

            if entry.kind() == Some(git2::ObjectType::Tree) {
                if let Some(max) = max_depth {
                    if entry_depth >= max {
                        // Record as a stub and skip descending.
                        let name = entry.name().unwrap_or("");
                        dir_stubs.push(format!("{}{}", root, name));
                        return git2::TreeWalkResult::Skip;
                    }
                }
                return git2::TreeWalkResult::Ok;
            }

            if entry.kind() != Some(git2::ObjectType::Blob) {
                return git2::TreeWalkResult::Ok;
            }

            let name = entry.name().unwrap_or("");
            flat.push(format!("{}{}", root, name));

            git2::TreeWalkResult::Ok
        })?;

        Ok(GitUtils::build_tree(flat, dir_stubs, max_depth))
    }

    /// Returns the file content as recorded in HEAD's tree (not from the working
    /// tree) so the response always reflects the last successfully committed state.
    pub fn read_file(
        repo_path: &Path,
        tenant_id: &str,
        file_path: &str,
    ) -> Result<String, AppError> {
        tracing::debug!(tenant_id = %tenant_id, path = %file_path, "reading file");

        let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
        let head_commit = repo.head()?.peel_to_commit()?;

        tracing::trace!(tenant_id = %tenant_id, path = %file_path, head_sha = %head_commit.id(), "resolved HEAD for read");

        let head_tree = head_commit.tree()?;

        GitUtils::blob_content_from_tree(&repo, &head_tree, file_path)
    }

    /// Checks that a file exists in HEAD's tree without reading its content.
    /// Returns `FileNotFound` when the path is absent or resolves to a folder.
    pub fn file_exists(repo_path: &Path, tenant_id: &str, file_path: &str) -> Result<(), AppError> {
        tracing::debug!(tenant_id = %tenant_id, path = %file_path, "checking file existence");

        let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
        let head_commit = repo.head()?.peel_to_commit()?;

        tracing::trace!(tenant_id = %tenant_id, path = %file_path, head_sha = %head_commit.id(), "resolved HEAD for existence check");

        let head_tree = head_commit.tree()?;

        let tree_entry =
            head_tree
                .get_path(Path::new(file_path))
                .map_err(|_err| AppError::FileNotFound {
                    path: file_path.to_string(),
                })?;

        if tree_entry.kind() != Some(git2::ObjectType::Blob) {
            return Err(AppError::FileNotFound {
                path: file_path.to_string(),
            });
        }

        Ok(())
    }

    /// Writes a file to disk, stages it, and creates a commit.
    /// Returns the commit SHA and the type of change (created vs updated).
    pub fn write_file(
        repo_path: &Path,
        file_path: &str,
        content: &str,
        commit_message: Option<&str>,
        author_name: &str,
        author_email: &str,
    ) -> Result<(String, FileChange), AppError> {
        tracing::debug!(path = %file_path, author_name = %author_name, author_email = %author_email, "writing file");

        let repo = GitUtils::open_or_init_repo(repo_path, author_name, author_email)?;

        let parent_commit = repo.head()?.peel_to_commit()?;
        let head_tree = parent_commit.tree()?;

        // Existence is decided from HEAD's tree, never from the working tree,
        // so leftovers from a previously failed operation cannot change the
        // outcome (created vs updated) or the hook event that is emitted.
        let is_new_file = match head_tree.get_path(Path::new(file_path)) {
            Ok(entry) if entry.kind() == Some(git2::ObjectType::Blob) => false,
            Ok(_) => {
                return Err(AppError::InvalidOperation {
                    reason: format!("path is a folder: {}", file_path),
                })
            }
            Err(_) => true,
        };

        tracing::debug!(path = %file_path, is_new_file = is_new_file, "staging file write");

        let absolute_path = repo_path.join(file_path);

        if let Some(parent_dir) = absolute_path.parent() {
            std::fs::create_dir_all(parent_dir)?;
        }

        std::fs::write(&absolute_path, content)?;

        tracing::trace!(path = %file_path, "building updated tree");

        // The commit tree is HEAD's tree plus this single change — O(path
        // depth) instead of the O(repository size) an index round-trip costs,
        // and stray state from a failed past operation can never leak in.
        let blob_oid = repo.blob(content.as_bytes())?;

        let tree_id = TreeUpdateBuilder::new()
            .upsert(file_path, blob_oid, FileMode::Blob)
            .create_updated(&repo, &head_tree)?;

        let tree = repo.find_tree(tree_id)?;
        let signature = GitUtils::git_signature(author_name, author_email)?;

        let auto_message = if is_new_file {
            format!("create: {}", file_path)
        } else {
            format!("update: {}", file_path)
        };
        let message = commit_message.unwrap_or(&auto_message);

        tracing::trace!(path = %file_path, message = %message, "committing file write");

        let commit_oid = repo.commit(
            Some("HEAD"),
            &signature,
            &signature,
            message,
            &tree,
            &[&parent_commit],
        )?;

        tracing::debug!(path = %file_path, sha = %commit_oid, is_new_file = is_new_file, "file write committed");

        let change = if is_new_file {
            FileChange::Created {
                path: file_path.to_string(),
                content: content.to_string(),
            }
        } else {
            FileChange::Updated {
                path: file_path.to_string(),
                content: content.to_string(),
            }
        };

        Ok((commit_oid.to_string(), change))
    }

    /// Removes a file from disk, stages the deletion, and creates a commit.
    pub fn delete_file(
        repo_path: &Path,
        tenant_id: &str,
        file_path: &str,
        commit_message: Option<&str>,
        author_name: &str,
        author_email: &str,
    ) -> Result<(String, FileChange), AppError> {
        tracing::debug!(tenant_id = %tenant_id, path = %file_path, author_name = %author_name, author_email = %author_email, "deleting file");

        let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;

        let parent_commit = repo.head()?.peel_to_commit()?;
        let head_tree = parent_commit.tree()?;

        // Existence is decided from HEAD's tree, never from the working tree.
        match head_tree.get_path(Path::new(file_path)) {
            Ok(entry) if entry.kind() == Some(git2::ObjectType::Blob) => {}
            _ => {
                tracing::debug!(tenant_id = %tenant_id, path = %file_path, "file not found for deletion");

                return Err(AppError::FileNotFound {
                    path: file_path.to_string(),
                });
            }
        }

        tracing::trace!(tenant_id = %tenant_id, path = %file_path, "building updated tree without path");

        // A file already missing from the working tree just means the working
        // tree had diverged from HEAD; there is nothing left to clean up.
        let absolute_path = repo_path.join(file_path);

        match std::fs::remove_file(&absolute_path) {
            Ok(()) => {}
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
            Err(err) => return Err(AppError::Io(err)),
        }

        // The commit tree is HEAD's tree minus this single entry — O(path
        // depth) instead of the O(repository size) an index round-trip costs.
        let tree_id = TreeUpdateBuilder::new()
            .remove(file_path)
            .create_updated(&repo, &head_tree)?;

        let tree = repo.find_tree(tree_id)?;
        let signature = GitUtils::git_signature(author_name, author_email)?;

        let auto_message = format!("delete: {}", file_path);
        let message = commit_message.unwrap_or(&auto_message);

        tracing::trace!(tenant_id = %tenant_id, path = %file_path, message = %message, "committing file deletion");

        let commit_oid = repo.commit(
            Some("HEAD"),
            &signature,
            &signature,
            message,
            &tree,
            &[&parent_commit],
        )?;

        tracing::debug!(tenant_id = %tenant_id, path = %file_path, sha = %commit_oid, "file deletion committed");

        Ok((
            commit_oid.to_string(),
            FileChange::Deleted {
                path: file_path.to_string(),
            },
        ))
    }

    /// Renames a file on disk, stages both sides, and creates a single commit.
    /// This preserves rename semantics so hook receivers know an entity was moved.
    pub fn move_file(
        repo_path: &Path,
        tenant_id: &str,
        from_path: &str,
        to_path: &str,
        commit_message: Option<&str>,
        author_name: &str,
        author_email: &str,
    ) -> Result<(String, FileChange), AppError> {
        tracing::debug!(
            tenant_id = %tenant_id,
            from_path = %from_path,
            to_path = %to_path,
            author_email = %author_email,
            "moving file"
        );

        let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;

        if from_path == to_path {
            tracing::debug!(tenant_id = %tenant_id, path = %from_path, "move rejected: source and destination are identical");

            return Err(AppError::InvalidOperation {
                reason: "destination must differ from source path".to_string(),
            });
        }

        let parent_commit = repo.head()?.peel_to_commit()?;
        let head_tree = parent_commit.tree()?;

        // Existence is decided from HEAD's tree, never from the working tree.
        // The blob oid is kept so the destination entry reuses it verbatim.
        let source_blob_oid = match head_tree.get_path(Path::new(from_path)) {
            Ok(entry) if entry.kind() == Some(git2::ObjectType::Blob) => entry.id(),
            _ => {
                tracing::debug!(tenant_id = %tenant_id, from_path = %from_path, "source file not found for move");

                return Err(AppError::FileNotFound {
                    path: from_path.to_string(),
                });
            }
        };

        // Refuse to clobber an existing destination — the user must delete first.
        if head_tree.get_path(Path::new(to_path)).is_ok() {
            tracing::debug!(tenant_id = %tenant_id, to_path = %to_path, "move rejected: destination already exists");

            return Err(AppError::InvalidOperation {
                reason: format!("destination already exists: {}", to_path),
            });
        }

        // The moved content comes from HEAD's blob — the authoritative state —
        // rather than whatever the working tree currently holds.
        let content = GitUtils::blob_content_from_tree(&repo, &head_tree, from_path)?;

        let absolute_from = repo_path.join(from_path);
        let absolute_to = repo_path.join(to_path);

        match std::fs::remove_file(&absolute_from) {
            Ok(()) => {}
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
            Err(err) => return Err(AppError::Io(err)),
        }

        if let Some(parent_dir) = absolute_to.parent() {
            std::fs::create_dir_all(parent_dir)?;
        }

        std::fs::write(&absolute_to, &content)?;

        tracing::trace!(
            tenant_id = %tenant_id,
            from_path = %from_path,
            to_path = %to_path,
            "building updated tree for move"
        );

        // The commit tree is HEAD's tree with the entry relocated, reusing the
        // existing blob — no content rehash, no index round-trip.
        let tree_id = TreeUpdateBuilder::new()
            .remove(from_path)
            .upsert(to_path, source_blob_oid, FileMode::Blob)
            .create_updated(&repo, &head_tree)?;

        let tree = repo.find_tree(tree_id)?;
        let signature = GitUtils::git_signature(author_name, author_email)?;

        let auto_message = format!("move: {} -> {}", from_path, to_path);
        let message = commit_message.unwrap_or(&auto_message);

        tracing::trace!(
            tenant_id = %tenant_id,
            from_path = %from_path,
            to_path = %to_path,
            message = %message,
            "committing file move"
        );

        let commit_oid = repo.commit(
            Some("HEAD"),
            &signature,
            &signature,
            message,
            &tree,
            &[&parent_commit],
        )?;

        tracing::debug!(
            tenant_id = %tenant_id,
            from_path = %from_path,
            to_path = %to_path,
            sha = %commit_oid,
            "file move committed"
        );

        Ok((
            commit_oid.to_string(),
            FileChange::Moved {
                from_path: from_path.to_string(),
                to_path: to_path.to_string(),
                content,
            },
        ))
    }
}

// ---------------------------------------------------------------------------
// GitCommits — commit history and revert
// ---------------------------------------------------------------------------

pub struct GitCommits;

impl GitCommits {
    pub fn list_commits(
        repo_path: &Path,
        tenant_id: &str,
        page: usize,
        per_page: usize,
        file_path: Option<&str>,
    ) -> Result<(Vec<CommitSummary>, bool), AppError> {
        if let Some(path) = file_path {
            return Self::list_commits_by_file(repo_path, tenant_id, page, per_page, path);
        }

        tracing::debug!(tenant_id = %tenant_id, page = page, per_page = per_page, "listing commits");

        let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;

        let mut revwalk = repo.revwalk()?;

        revwalk.push_head()?;

        // TIME | TOPOLOGICAL gives stable ordering across commits sharing a timestamp.
        revwalk.set_sorting(Sort::TIME | Sort::TOPOLOGICAL)?;

        let skip_count = page.saturating_sub(1).saturating_mul(per_page);

        tracing::trace!(tenant_id = %tenant_id, skip_count = skip_count, per_page = per_page, "walking commit graph");

        // Fetch one extra to detect whether a next page exists without a full count.
        let mut commits: Vec<CommitSummary> = revwalk
            .skip(skip_count)
            .take(per_page + 1)
            .filter_map(|oid_result| oid_result.ok())
            .filter_map(|oid| repo.find_commit(oid).ok())
            .map(|commit| CommitSummary {
                sha: commit.id().to_string(),
                message: commit.message().unwrap_or("").to_string(),
                author: CommitAuthor {
                    name: commit.author().name().unwrap_or("").to_string(),
                    email: commit.author().email().unwrap_or("").to_string(),
                },
                committed_at: GitUtils::timestamp_from_git_time(commit.time()),
            })
            .collect();

        let has_more = commits.len() > per_page;

        commits.truncate(per_page);

        tracing::debug!(tenant_id = %tenant_id, page = page, returned = commits.len(), has_more = has_more, "commit listing complete");

        Ok((commits, has_more))
    }

    /// Walks the commit graph from HEAD, diffing each commit against its parent
    /// with rename detection enabled, and collects only commits that touched
    /// `file_path` (following the file backward through any renames).
    ///
    /// Pagination is applied after matching: we collect up to
    /// `(page-1)*per_page + per_page + 1` matching commits, then slice.
    fn list_commits_by_file(
        repo_path: &Path,
        tenant_id: &str,
        page: usize,
        per_page: usize,
        file_path: &str,
    ) -> Result<(Vec<CommitSummary>, bool), AppError> {
        tracing::debug!(
            tenant_id = %tenant_id,
            page = page,
            per_page = per_page,
            file_path = %file_path,
            "listing commits by file path"
        );

        let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;

        let mut revwalk = repo.revwalk()?;

        revwalk.push_head()?;
        revwalk.set_sorting(Sort::TIME | Sort::TOPOLOGICAL)?;

        let skip_count = page.saturating_sub(1).saturating_mul(per_page);
        // Collect one extra beyond what we need so we can detect has_more.
        let need = skip_count + per_page + 1;

        // The name of the file we are tracking. Updated when we cross a rename.
        let mut current_path = file_path.to_string();
        let mut matching: Vec<CommitSummary> = Vec::new();

        for oid_result in revwalk {
            if matching.len() >= need {
                break;
            }

            let oid = match oid_result {
                Ok(id) => id,
                Err(_) => continue,
            };

            let commit = match repo.find_commit(oid) {
                Ok(c) => c,
                Err(_) => continue,
            };

            let commit_tree = match commit.tree() {
                Ok(t) => t,
                Err(_) => continue,
            };

            // For the root commit there is no parent tree to diff against — the
            // file is "created" here if it exists in the tree under the current name.
            let (is_match, rename_from) = if commit.parent_count() == 0 {
                let exists = commit_tree.get_path(Path::new(&current_path)).is_ok();

                tracing::trace!(
                    tenant_id = %tenant_id,
                    sha = %commit.id(),
                    path = %current_path,
                    exists = exists,
                    "checking root commit for file"
                );

                (exists, None)
            } else {
                let parent_tree = match commit.parent(0).and_then(|p| p.tree()) {
                    Ok(t) => t,
                    Err(_) => continue,
                };

                // Two O(path depth) tree lookups decide whether this commit
                // touched the file at all. A rename-detecting diff (which loads
                // blob contents to score similarity) is only computed for the
                // rare commit that introduced the file under its current name.
                let commit_entry = commit_tree.get_path(Path::new(&current_path)).ok();
                let parent_entry = parent_tree.get_path(Path::new(&current_path)).ok();

                match (commit_entry, parent_entry) {
                    // Untouched by this commit — the overwhelmingly common case.
                    (Some(in_commit), Some(in_parent))
                        if in_commit.id() == in_parent.id()
                            && in_commit.filemode() == in_parent.filemode() =>
                    {
                        (false, None)
                    }
                    // Modified in this commit.
                    (Some(_), Some(_)) => (true, None),
                    // Deleted by this commit (the file was re-created later).
                    (None, Some(_)) => (true, None),
                    // Not present under this name on either side.
                    (None, None) => (false, None),
                    // Introduced by this commit — either created, or renamed
                    // from an older path that must be followed backward.
                    (Some(_), None) => (
                        true,
                        Self::rename_source(&repo, &parent_tree, &commit_tree, &current_path),
                    ),
                }
            };

            if is_match {
                tracing::trace!(
                    tenant_id = %tenant_id,
                    sha = %commit.id(),
                    path = %current_path,
                    "commit matched file path filter"
                );

                matching.push(CommitSummary {
                    sha: commit.id().to_string(),
                    message: commit.message().unwrap_or("").to_string(),
                    author: CommitAuthor {
                        name: commit.author().name().unwrap_or("").to_string(),
                        email: commit.author().email().unwrap_or("").to_string(),
                    },
                    committed_at: GitUtils::timestamp_from_git_time(commit.time()),
                });

                if let Some(old_name) = rename_from {
                    current_path = old_name;
                }
            }
        }

        let has_more = matching.len() > skip_count + per_page;

        let commits = matching
            .into_iter()
            .skip(skip_count)
            .take(per_page)
            .collect();

        tracing::debug!(
            tenant_id = %tenant_id,
            page = page,
            returned = per_page,
            has_more = has_more,
            "commit listing by file complete"
        );

        Ok((commits, has_more))
    }

    /// Runs a rename-detecting diff of a single commit and returns the prior
    /// path when `current_path` was renamed (rather than freshly created) by
    /// it. Only invoked for commits that introduced the file under its
    /// current name, so the similarity scan stays off the hot path.
    fn rename_source(
        repo: &Repository,
        parent_tree: &git2::Tree<'_>,
        commit_tree: &git2::Tree<'_>,
        current_path: &str,
    ) -> Option<String> {
        let mut diff_opts = DiffOptions::new();

        diff_opts.include_untracked(false);

        let mut diff = repo
            .diff_tree_to_tree(Some(parent_tree), Some(commit_tree), Some(&mut diff_opts))
            .ok()?;

        let mut find_opts = DiffFindOptions::new();

        find_opts.renames(true);

        diff.find_similar(Some(&mut find_opts)).ok()?;

        for index in 0..diff.deltas().count() {
            let Some(delta) = diff.get_delta(index) else {
                continue;
            };

            if delta.status() != Delta::Renamed {
                continue;
            }

            let new = delta
                .new_file()
                .path()
                .map(|path| path.to_string_lossy().into_owned());

            if new.as_deref() == Some(current_path) {
                let old = delta
                    .old_file()
                    .path()
                    .map(|path| path.to_string_lossy().into_owned());

                tracing::trace!(
                    from = ?old,
                    to = %current_path,
                    "rename detected, following path backward"
                );

                return old;
            }
        }

        None
    }

    pub fn get_commit(
        repo_path: &Path,
        tenant_id: &str,
        sha: &str,
    ) -> Result<CommitDetail, AppError> {
        tracing::debug!(tenant_id = %tenant_id, sha = %sha, "fetching commit detail");

        let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;

        let object = repo
            .revparse_single(sha)
            .map_err(|_err| AppError::CommitNotFound {
                sha: sha.to_string(),
            })?;

        let commit = object
            .peel_to_commit()
            .map_err(|_err| AppError::CommitNotFound {
                sha: sha.to_string(),
            })?;

        let commit_tree = commit.tree()?;

        let parent_tree = if commit.parent_count() > 0 {
            Some(commit.parent(0)?.tree()?)
        } else {
            None
        };

        tracing::trace!(
            tenant_id = %tenant_id,
            sha = %sha,
            has_parent = parent_tree.is_some(),
            "diffing commit against parent"
        );

        let mut diff_options = DiffOptions::new();

        diff_options.include_untracked(false);

        let mut diff = repo.diff_tree_to_tree(
            parent_tree.as_ref(),
            Some(&commit_tree),
            Some(&mut diff_options),
        )?;

        // Enable rename detection so moved files are identified correctly.
        let mut find_options = DiffFindOptions::new();

        find_options.renames(true);

        diff.find_similar(Some(&mut find_options))?;

        let records: Vec<DeltaRecord> = (0..diff.deltas().count())
            .filter_map(|index| diff.get_delta(index))
            .map(|delta| {
                tracing::trace!(
                    tenant_id = %tenant_id,
                    sha = %sha,
                    status = ?delta.status(),
                    old_path = ?delta.old_file().path(),
                    new_path = ?delta.new_file().path(),
                    "processing diff delta"
                );
                DeltaRecord {
                    status: delta.status(),
                    old_oid: delta.old_file().id(),
                    new_oid: delta.new_file().id(),
                    old_path: delta.old_file().path().map(PathBuf::from),
                    new_path: delta.new_file().path().map(PathBuf::from),
                }
            })
            .collect();

        tracing::trace!(tenant_id = %tenant_id, sha = %sha, delta_count = records.len(), "building per-file diffs");

        // Walk the entire patch once and route each line to its delta's bucket.
        // Linear scan via `position` is fine — commits hold a handful of files.
        let mut per_file_diffs: Vec<String> = vec![String::new(); records.len()];

        diff.print(DiffFormat::Patch, |delta, _hunk, line| {
            let key = (delta.old_file().id(), delta.new_file().id());

            if let Some(idx) = records
                .iter()
                .position(|record| (record.old_oid, record.new_oid) == key)
            {
                let bucket = &mut per_file_diffs[idx];

                match line.origin() {
                    '+' | '-' | ' ' | '\\' => bucket.push(line.origin()),
                    _ => {}
                }

                bucket.push_str(std::str::from_utf8(line.content()).unwrap_or(""));
            }

            true
        })?;

        let mut file_details: Vec<CommitFileDetail> = Vec::with_capacity(records.len());

        for (index, record) in records.iter().enumerate() {
            let (change_label, file_path, from_path) = match record.status {
                Delta::Added => (
                    "created",
                    GitUtils::path_string(record.new_path.as_deref()),
                    None,
                ),
                Delta::Deleted => (
                    "deleted",
                    GitUtils::path_string(record.old_path.as_deref()),
                    None,
                ),
                Delta::Renamed => (
                    "moved",
                    GitUtils::path_string(record.new_path.as_deref()),
                    record
                        .old_path
                        .as_deref()
                        .map(|path| path.to_string_lossy().into_owned()),
                ),
                _ => (
                    "updated",
                    GitUtils::path_string(record.new_path.as_deref()),
                    None,
                ),
            };

            tracing::trace!(
                tenant_id = %tenant_id,
                sha = %sha,
                path = %file_path,
                change = %change_label,
                "assembling commit file detail"
            );

            let content = if record.status == Delta::Deleted {
                String::new()
            } else {
                GitUtils::blob_content_from_tree(&repo, &commit_tree, &file_path)?
            };

            file_details.push(CommitFileDetail {
                path: file_path,
                change: change_label.to_string(),
                from_path,
                content,
                diff: std::mem::take(&mut per_file_diffs[index]),
            });
        }

        // Materialise borrowed values before the struct literal so that the
        // `Signature` temporary returned by `commit.author()` is dropped while
        // `commit` (and the underlying `repo`) is still alive.
        let sha = commit.id().to_string();
        let message = commit.message().unwrap_or("").to_string();

        let author = CommitAuthor {
            name: commit.author().name().unwrap_or("").to_string(),
            email: commit.author().email().unwrap_or("").to_string(),
        };

        let committed_at = GitUtils::timestamp_from_git_time(commit.time());

        tracing::debug!(tenant_id = %tenant_id, sha = %sha, file_count = file_details.len(), "commit detail ready");

        Ok(CommitDetail {
            sha,
            message,
            author,
            committed_at,
            files: file_details,
        })
    }

    /// Reverts all changes introduced by the given commit by applying their inverse,
    /// then records the result as a new commit. Returns the new commit SHA and
    /// the list of file changes (for hook delivery).
    pub fn revert_commit(
        repo_path: &Path,
        tenant_id: &str,
        sha: &str,
        commit_message: Option<&str>,
        author_name: &str,
        author_email: &str,
    ) -> Result<(String, Vec<FileChange>), AppError> {
        tracing::debug!(tenant_id = %tenant_id, sha = %sha, author_name = %author_name, author_email = %author_email, "reverting commit");

        let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;

        let object = repo
            .revparse_single(sha)
            .map_err(|_err| AppError::CommitNotFound {
                sha: sha.to_string(),
            })?;

        let target_commit = object
            .peel_to_commit()
            .map_err(|_err| AppError::CommitNotFound {
                sha: sha.to_string(),
            })?;

        if target_commit.parent_count() == 0 {
            tracing::warn!(tenant_id = %tenant_id, sha = %sha, "cannot revert root commit");

            return Err(AppError::InvalidOperation {
                reason: "cannot revert the initial commit".to_string(),
            });
        }

        let parent_commit = target_commit.parent(0)?;
        let commit_tree = target_commit.tree()?;
        let parent_tree = parent_commit.tree()?;

        // Diff from parent → commit tells us what the commit introduced.
        // Reverting means applying each change in reverse.
        tracing::trace!(tenant_id = %tenant_id, sha = %sha, "computing diff for revert");

        let mut diff = repo.diff_tree_to_tree(Some(&parent_tree), Some(&commit_tree), None)?;

        let mut find_options = DiffFindOptions::new();

        find_options.renames(true);

        diff.find_similar(Some(&mut find_options))?;

        let raw_deltas: Vec<DeltaRecord> = (0..diff.deltas().count())
            .filter_map(|index| diff.get_delta(index))
            .map(|delta| DeltaRecord {
                status: delta.status(),
                old_oid: delta.old_file().id(),
                new_oid: delta.new_file().id(),
                old_path: delta.old_file().path().map(PathBuf::from),
                new_path: delta.new_file().path().map(PathBuf::from),
            })
            .collect();

        tracing::trace!(tenant_id = %tenant_id, sha = %sha, delta_count = raw_deltas.len(), "applying revert deltas");

        let head_commit = repo.head()?.peel_to_commit()?;
        let head_tree = head_commit.tree()?;

        // The revert tree is HEAD's tree plus the inverse of each delta,
        // reusing parent-tree blob oids — no index round-trip, no rehashing.
        let mut tree_update = TreeUpdateBuilder::new();

        let mut file_changes: Vec<FileChange> = Vec::new();

        for raw_delta in &raw_deltas {
            match raw_delta.status {
                Delta::Added => {
                    // Commit added this file → revert removes it.
                    if let Some(new_path) = &raw_delta.new_path {
                        tracing::trace!(
                            tenant_id = %tenant_id,
                            sha = %sha,
                            path = %new_path.display(),
                            "revert: removing added file"
                        );

                        let absolute_path = repo_path.join(new_path);

                        if absolute_path.exists() {
                            std::fs::remove_file(&absolute_path)?;
                        }

                        tree_update.remove(new_path);

                        file_changes.push(FileChange::Deleted {
                            path: new_path.to_string_lossy().into_owned(),
                        });
                    }
                }
                Delta::Deleted => {
                    // Commit deleted this file → revert restores it from the parent tree.
                    if let Some(old_path) = &raw_delta.old_path {
                        tracing::trace!(
                            tenant_id = %tenant_id,
                            sha = %sha,
                            path = %old_path.display(),
                            "revert: restoring deleted file"
                        );

                        let content = GitUtils::blob_content_from_tree(
                            &repo,
                            &parent_tree,
                            &old_path.to_string_lossy(),
                        )?;

                        let absolute_path = repo_path.join(old_path);

                        if let Some(parent_dir) = absolute_path.parent() {
                            std::fs::create_dir_all(parent_dir)?;
                        }

                        std::fs::write(&absolute_path, &content)?;

                        tree_update.upsert(old_path, raw_delta.old_oid, FileMode::Blob);

                        file_changes.push(FileChange::Created {
                            path: old_path.to_string_lossy().into_owned(),
                            content,
                        });
                    }
                }
                Delta::Modified => {
                    // Commit modified this file → revert restores the old version.
                    if let Some(old_path) = &raw_delta.old_path {
                        tracing::trace!(
                            tenant_id = %tenant_id,
                            sha = %sha,
                            path = %old_path.display(),
                            "revert: restoring modified file to previous version"
                        );

                        let content = GitUtils::blob_content_from_tree(
                            &repo,
                            &parent_tree,
                            &old_path.to_string_lossy(),
                        )?;

                        let absolute_path = repo_path.join(old_path);

                        std::fs::write(&absolute_path, &content)?;

                        tree_update.upsert(old_path, raw_delta.old_oid, FileMode::Blob);

                        file_changes.push(FileChange::Updated {
                            path: old_path.to_string_lossy().into_owned(),
                            content,
                        });
                    }
                }
                Delta::Renamed => {
                    // Commit renamed old → new; revert renames new → old.
                    if let (Some(old_path), Some(new_path)) =
                        (&raw_delta.old_path, &raw_delta.new_path)
                    {
                        tracing::trace!(
                            tenant_id = %tenant_id,
                            sha = %sha,
                            from_path = %new_path.display(),
                            to_path = %old_path.display(),
                            "revert: reversing rename"
                        );

                        let content = GitUtils::blob_content_from_tree(
                            &repo,
                            &parent_tree,
                            &old_path.to_string_lossy(),
                        )?;

                        let absolute_old = repo_path.join(old_path);
                        let absolute_new = repo_path.join(new_path);

                        if absolute_new.exists() {
                            std::fs::remove_file(&absolute_new)?;
                        }

                        if let Some(parent_dir) = absolute_old.parent() {
                            std::fs::create_dir_all(parent_dir)?;
                        }

                        std::fs::write(&absolute_old, &content)?;

                        tree_update.remove(new_path);
                        tree_update.upsert(old_path, raw_delta.old_oid, FileMode::Blob);

                        file_changes.push(FileChange::Moved {
                            from_path: new_path.to_string_lossy().into_owned(),
                            to_path: old_path.to_string_lossy().into_owned(),
                            content,
                        });
                    }
                }
                _ => {}
            }
        }

        tracing::trace!(tenant_id = %tenant_id, sha = %sha, "building revert tree and committing");

        let tree_id = tree_update.create_updated(&repo, &head_tree)?;
        let tree = repo.find_tree(tree_id)?;
        let signature = GitUtils::git_signature(author_name, author_email)?;

        let auto_message = format!("revert: {}", target_commit.message().unwrap_or("unknown"));
        let revert_message = commit_message.unwrap_or(&auto_message);

        let new_commit_oid = repo.commit(
            Some("HEAD"),
            &signature,
            &signature,
            revert_message,
            &tree,
            &[&head_commit],
        )?;

        tracing::debug!(
            tenant_id = %tenant_id,
            reverted_sha = %sha,
            new_sha = %new_commit_oid,
            file_change_count = file_changes.len(),
            "revert committed"
        );

        Ok((new_commit_oid.to_string(), file_changes))
    }
}

// ---------------------------------------------------------------------------
// GitTenant — tenant repository lifecycle
// ---------------------------------------------------------------------------

pub struct GitTenant;

impl GitTenant {
    pub fn delete_repo(repo_path: &Path, tenant_id: &str) -> Result<(), AppError> {
        tracing::debug!(tenant_id = %tenant_id, "deleting tenant repository");

        if !repo_path.exists() {
            tracing::debug!(tenant_id = %tenant_id, "tenant repository not found for deletion");

            return Err(AppError::TenantNotFound {
                tenant_id: tenant_id.to_string(),
            });
        }

        std::fs::remove_dir_all(repo_path).map_err(|err| {
            tracing::error!(
                tenant_id = %tenant_id,
                path = %repo_path.display(),
                err = %err,
                "failed to remove tenant repository directory"
            );

            AppError::Io(err)
        })?;

        tracing::info!(tenant_id = %tenant_id, "tenant repository deleted");

        Ok(())
    }
}