arks-server 1.3.5

Git server: upload-pack / receive-pack + smart/dumb HTTP + daemon (M11/M25)
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
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
//! Unified `RefUpdateGate` for all server-side Git ref mutations.
//!
//! Enforces per-repository in-process + cross-process serialization (`arks-ref-gate.lock`),
//! internal `refs/arks/*` confidentiality, archived repository immutability, branch
//! protection rules (`block_delete`, `block_force_push`),
//! [`PushPolicy`](crate::push_policy::PushPolicy), non-bare checkout safety
//! (`receive.denyCurrentBranch`), Git receive hooks (`pre-receive`, `update`,
//! `post-receive`, `post-update`), atomic CAS ref mutation, dumb HTTP `info/refs`
//! refresh, webhooks, and Actions CI.
//!
//! Spec: `.spec/sot/arks-self-host-server.sot.md` §38–§43.

use crate::hooks::{
    HookEnv, HookGate, run_post_receive, run_post_update, run_pre_receive, run_update,
};
use crate::push_policy::{Pusher, RefUpdate, installed_push_policy, verdicts};
use crate::web_ui::store::ForgeStore;
use arks_config::ConfigSet;
use arks_object::{Commit, ObjectKind, RawObject, TreeMode};
use arks_oid::{Oid, OidKind};
use arks_refs::RefTarget;
use arks_repo::{Repository, commit_tree_map};
use std::collections::{HashMap, HashSet, VecDeque};
use std::fmt;
use std::fs;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Condvar, Mutex, OnceLock, Weak};
use std::time::{Duration, Instant};

const REF_GATE_LOCK_FILE: &str = "arks-ref-gate.lock";
const REF_GATE_STALE_SECS: u64 = 30;
const REF_GATE_TIMEOUT_SECS: u64 = 30;

#[derive(Default)]
struct RepoSlot {
    locked: Mutex<bool>,
    cvar: Condvar,
}

struct OwnedRepoSlotGuard {
    slot: Arc<RepoSlot>,
}

impl OwnedRepoSlotGuard {
    fn lock(slot: Arc<RepoSlot>) -> Self {
        let mut locked = slot.locked.lock().unwrap_or_else(|e| e.into_inner());
        while *locked {
            locked = slot.cvar.wait(locked).unwrap_or_else(|e| e.into_inner());
        }
        *locked = true;
        drop(locked);
        Self { slot }
    }
}

impl Drop for OwnedRepoSlotGuard {
    fn drop(&mut self) {
        let mut locked = self.slot.locked.lock().unwrap_or_else(|e| e.into_inner());
        *locked = false;
        self.slot.cvar.notify_one();
    }
}

struct FileLockGuard {
    lock_path: PathBuf,
}

impl Drop for FileLockGuard {
    fn drop(&mut self) {
        let _ = fs::remove_file(&self.lock_path);
    }
}

/// RAII lock guard serializing ref updates per repository across both threads
/// (via an `Arc`-backed slot map with zero `Box::leak`) and OS processes
/// (via sibling lockfile `<common_dir>/arks-ref-gate.lock`).
pub struct RefGateGuard {
    common_dir_key: PathBuf,
    // Drop order is declaration order: remove the lockfile BEFORE releasing the in-process guard.
    _file_lock: FileLockGuard,
    _in_proc: OwnedRepoSlotGuard,
}

/// Canonical description of one server-side ref create, update, or delete.
#[derive(Debug, Clone)]
pub struct GatedRefUpdate {
    pub refname: String,
    pub old_oid: Option<Oid>,
    pub new_oid: Option<Oid>,
    pub allow_non_ff: bool,
    pub pusher: Pusher,
    pub allow_internal_arks_ref: bool,
    pub trigger_ci: bool,
}

/// Structured rejection reason returned by [`RefUpdateGate`](apply_gated_ref_update).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GateReject {
    Forbidden(String),
    Conflict(String),
    PreconditionFailed(String),
    Internal(String),
}

impl GateReject {
    pub fn message(&self) -> &str {
        match self {
            Self::Forbidden(m)
            | Self::Conflict(m)
            | Self::PreconditionFailed(m)
            | Self::Internal(m) => m.as_str(),
        }
    }

    pub fn http_status(&self) -> u16 {
        match self {
            Self::Forbidden(_) => 403,
            Self::Conflict(_) => 409,
            Self::PreconditionFailed(_) => 412,
            Self::Internal(_) => 500,
        }
    }
}

impl fmt::Display for GateReject {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.message())
    }
}

impl std::error::Error for GateReject {}

fn canonical_repo_key(common_dir: &Path) -> PathBuf {
    common_dir
        .canonicalize()
        .unwrap_or_else(|_| common_dir.to_path_buf())
}

fn acquire_in_process_repo_lock(key: &Path) -> OwnedRepoSlotGuard {
    static LOCKS: OnceLock<Mutex<HashMap<PathBuf, Weak<RepoSlot>>>> = OnceLock::new();
    let map_lock = LOCKS.get_or_init(|| Mutex::new(HashMap::new()));
    let slot = {
        let mut map = map_lock.lock().unwrap_or_else(|e| e.into_inner());
        match map.get(key).and_then(Weak::upgrade) {
            Some(existing) => existing,
            None => {
                if map.len() > 64 {
                    map.retain(|_, w| w.strong_count() > 0);
                }
                let fresh = Arc::new(RepoSlot::default());
                map.insert(key.to_path_buf(), Arc::downgrade(&fresh));
                fresh
            }
        }
    };
    OwnedRepoSlotGuard::lock(slot)
}

fn is_lock_stale(lock_path: &Path, stale_after: Duration) -> bool {
    if let Some(pid) = crate::web_ui::store::parse_lockfile_pid(lock_path) {
        if crate::web_ui::store::is_other_pid_alive_strict(pid) == Some(false) {
            return true;
        }
    }
    match fs::metadata(lock_path).and_then(|m| m.modified()) {
        Ok(mtime) => mtime
            .elapsed()
            .map(|age| age >= stale_after)
            .unwrap_or(false),
        Err(_) => false,
    }
}

fn acquire_file_lock_with(
    lock_path: &Path,
    stale_after: Duration,
    timeout: Duration,
) -> Result<FileLockGuard, String> {
    if let Some(parent) = lock_path.parent() {
        fs::create_dir_all(parent)
            .map_err(|e| format!("failed to prepare lock directory {}: {e}", parent.display()))?;
    }
    let deadline = Instant::now() + timeout;
    let mut backoff_ms = 2u64;
    loop {
        match fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(lock_path)
        {
            Ok(mut f) => {
                let payload = format!("pid={}\n", std::process::id());
                let _ = f.write_all(payload.as_bytes());
                drop(f);
                return Ok(FileLockGuard {
                    lock_path: lock_path.to_path_buf(),
                });
            }
            Err(e)
                if e.kind() == std::io::ErrorKind::AlreadyExists
                    || (cfg!(windows) && e.kind() == std::io::ErrorKind::PermissionDenied) =>
            {
                if e.kind() == std::io::ErrorKind::AlreadyExists
                    && is_lock_stale(lock_path, stale_after)
                {
                    let _ = fs::remove_file(lock_path);
                    continue;
                }
                if Instant::now() >= deadline {
                    return Err(format!(
                        "timed out acquiring repository ref gate lock {}",
                        lock_path.display()
                    ));
                }
                std::thread::sleep(Duration::from_millis(backoff_ms));
                backoff_ms = (backoff_ms * 2).min(20);
            }
            Err(e) => {
                return Err(format!(
                    "failed to create repository ref gate lock {}: {e}",
                    lock_path.display()
                ));
            }
        }
    }
}

/// Acquire the per-repository serialization lock (both in-process and cross-process
/// `<common_dir>/arks-ref-gate.lock`).
pub fn acquire_repo_ref_lock(common_dir: &Path) -> Result<RefGateGuard, String> {
    let key = canonical_repo_key(common_dir);
    let in_proc = acquire_in_process_repo_lock(&key);
    let lock_path = common_dir.join(REF_GATE_LOCK_FILE);
    let file_lock = acquire_file_lock_with(
        &lock_path,
        Duration::from_secs(REF_GATE_STALE_SECS),
        Duration::from_secs(REF_GATE_TIMEOUT_SECS),
    )?;
    Ok(RefGateGuard {
        common_dir_key: key,
        _file_lock: file_lock,
        _in_proc: in_proc,
    })
}

fn zero_oid(kind: OidKind) -> Result<Oid, GateReject> {
    let zeros = [0u8; 32];
    Oid::from_bytes(kind, &zeros[..kind.digest_len()])
        .map_err(|e| GateReject::Internal(format!("zero oid error: {e}")))
}

fn zero_hex(kind: OidKind) -> String {
    "0".repeat(kind.hex_len())
}

pub(crate) fn branch_rule_matches(pattern: &str, branch: &str) -> bool {
    pattern == "*" || pattern == branch || glob_match(pattern, branch)
}

fn glob_match(pattern: &str, text: &str) -> bool {
    let p: Vec<char> = pattern.chars().collect();
    let t: Vec<char> = text.chars().collect();
    let (mut pi, mut ti) = (0usize, 0usize);
    let (mut star_pi, mut star_ti) = (None, 0usize);
    while ti < t.len() {
        if pi < p.len() && (p[pi] == '?' || p[pi] == t[ti]) {
            pi += 1;
            ti += 1;
        } else if pi < p.len() && p[pi] == '*' {
            star_pi = Some(pi);
            star_ti = ti;
            pi += 1;
        } else if let Some(sp) = star_pi {
            pi = sp + 1;
            star_ti += 1;
            ti = star_ti;
        } else {
            return false;
        }
    }
    while pi < p.len() && p[pi] == '*' {
        pi += 1;
    }
    pi == p.len()
}

fn is_valid_refname(refname: &str) -> bool {
    !refname.is_empty()
        && !refname.starts_with('/')
        && !refname.ends_with('/')
        && !refname.contains("..")
        && !refname.contains('\\')
        && !refname.contains("@{")
        && !refname.bytes().any(|b| b <= 0x20 || b == 0x7f)
}

fn is_internal_arks_ref(refname: &str) -> bool {
    refname == "refs/arks" || refname.starts_with("refs/arks/")
}

fn is_commit_ancestor(repo: &Repository, ancestor: Oid, descendant: Oid) -> bool {
    if ancestor == descendant {
        return true;
    }
    let mut queue = VecDeque::new();
    let mut visited = HashSet::new();
    queue.push_back(descendant);
    visited.insert(descendant);
    let mut steps = 0usize;
    while let Some(cur) = queue.pop_front() {
        steps += 1;
        if steps > 100_000 {
            break;
        }
        let Ok(obj) = repo.get_object(&cur) else {
            continue;
        };
        if obj.kind != ObjectKind::Commit {
            continue;
        }
        let Ok(commit) = Commit::decode(&obj.payload) else {
            continue;
        };
        for parent in commit.parents {
            if parent == ancestor {
                return true;
            }
            if visited.insert(parent) {
                queue.push_back(parent);
            }
        }
    }
    false
}

/// Check non-bare checkout safety per `receive.denyCurrentBranch` / `receive.denyDeleteCurrent`.
///
/// Returns:
/// - `Ok(true)` when `receive.denyCurrentBranch=updateInstead` is configured, `refname` is
///   currently checked out, and the working tree is clean (caller must sync worktree after CAS).
/// - `Ok(false)` when bare, `refname` is not checked out, or config allows update without sync.
/// - `Err(GateReject::Conflict(..))` when updating/deleting the checked-out branch is refused
///   (default `refuse`) or the working tree has uncommitted changes under `updateInstead`.
pub fn check_non_bare_deny_current_branch(
    repo: &Repository,
    refname: &str,
    new_oid: Option<&Oid>,
) -> Result<bool, GateReject> {
    check_non_bare_deny_current_branch_with_default(repo, refname, new_oid, false)
}

/// Like [`check_non_bare_deny_current_branch`], except when `receive.denyCurrentBranch` is
/// unset in repository config and `default_update_instead` is `true` (used for interactive
/// Web UI merges/edits on a local non-bare checkout), defaults to guarded `updateInstead`
/// (still failing closed on dirty working trees and syncing both worktree and `.git/index`).
pub(crate) fn check_non_bare_deny_current_branch_with_default(
    repo: &Repository,
    refname: &str,
    new_oid: Option<&Oid>,
    default_update_instead: bool,
) -> Result<bool, GateReject> {
    let cfg = ConfigSet::load(Some(repo.git_dir()));
    if cfg.get_bool("core.bare") == Some(true) {
        return Ok(false);
    }
    let Some(work_tree) = repo.work_tree() else {
        return Ok(false);
    };
    let head_matches =
        matches!(repo.head_target(), Ok(RefTarget::Symbolic(ref sym)) if sym == refname);
    if !head_matches {
        return Ok(false);
    }

    if new_oid.is_none() {
        let mode = cfg
            .get("receive.denydeletecurrent")
            .unwrap_or_else(|| "refuse".to_string());
        return match mode.trim().to_ascii_lowercase().as_str() {
            "ignore" | "false" | "warn" => Ok(false),
            _ => Err(GateReject::Conflict(format!(
                "refusing to delete checked-out branch '{refname}' in non-bare repository (receive.denyDeleteCurrent)"
            ))),
        };
    }

    let mode = cfg.get("receive.denycurrentbranch").unwrap_or_else(|| {
        if default_update_instead {
            "updateInstead".to_string()
        } else {
            "refuse".to_string()
        }
    });
    match mode.trim().to_ascii_lowercase().as_str() {
        "ignore" | "false" | "warn" => Ok(false),
        "updateinstead" => {
            verify_worktree_clean_for_update_instead(
                repo,
                work_tree,
                refname,
                new_oid,
                cfg.autocrlf_to_lf(),
            )?;
            Ok(true)
        }
        _ => Err(GateReject::Conflict(format!(
            "refusing to update checked-out branch '{refname}' in non-bare repository (receive.denyCurrentBranch=refuse)"
        ))),
    }
}

fn read_worktree_entry_bytes(path: &Path) -> Option<(Vec<u8>, bool)> {
    let meta = fs::symlink_metadata(path).ok()?;
    if meta.file_type().is_symlink() {
        let target = fs::read_link(path).ok()?;
        Some((target.to_string_lossy().as_bytes().to_vec(), true))
    } else if meta.is_file() {
        Some((fs::read(path).ok()?, false))
    } else {
        None
    }
}

fn crlf_to_lf(bytes: &[u8]) -> Vec<u8> {
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'\r' && i + 1 < bytes.len() && bytes[i + 1] == b'\n' {
            out.push(b'\n');
            i += 2;
        } else {
            out.push(bytes[i]);
            i += 1;
        }
    }
    out
}

fn worktree_bytes_match_blob(
    repo: &Repository,
    disk_bytes: &[u8],
    is_symlink: bool,
    expected_oid: &Oid,
    autocrlf: bool,
) -> Result<bool, GateReject> {
    let format = repo.object_format();
    let actual_oid = RawObject::new(ObjectKind::Blob, disk_bytes.to_vec())
        .oid(format)
        .map_err(|e| GateReject::Internal(format!("blob hash error: {e}")))?;
    if actual_oid == *expected_oid {
        return Ok(true);
    }
    if !is_symlink
        && autocrlf
        && !disk_bytes[..disk_bytes.len().min(8000)].contains(&0)
        && disk_bytes.windows(2).any(|w| w == b"\r\n")
    {
        let normalized = crlf_to_lf(disk_bytes);
        let norm_oid = RawObject::new(ObjectKind::Blob, normalized)
            .oid(format)
            .map_err(|e| GateReject::Internal(format!("blob hash error: {e}")))?;
        return Ok(norm_oid == *expected_oid);
    }
    Ok(false)
}

fn verify_worktree_clean_for_update_instead(
    repo: &Repository,
    work_tree: &Path,
    refname: &str,
    new_oid: Option<&Oid>,
    autocrlf: bool,
) -> Result<(), GateReject> {
    let head_files = match repo.refs().resolve(refname).ok() {
        Some(cur_head) => commit_tree_map(repo, &cur_head)
            .map_err(|e| GateReject::Internal(format!("failed to read HEAD tree: {e}")))?,
        None => HashMap::new(),
    };

    for (rel_path, expected_oid) in &head_files {
        if !is_safe_worktree_rel_path(rel_path) {
            return Err(GateReject::Conflict(format!(
                "refusing updateInstead on '{refname}': unsafe path '{rel_path}'"
            )));
        }
        let full = work_tree.join(rel_path);
        let Some((disk_bytes, is_symlink)) = read_worktree_entry_bytes(&full) else {
            return Err(GateReject::Conflict(format!(
                "refusing updateInstead on '{refname}': working tree has missing or modified tracked path '{rel_path}'"
            )));
        };
        if !worktree_bytes_match_blob(repo, &disk_bytes, is_symlink, expected_oid, autocrlf)? {
            return Err(GateReject::Conflict(format!(
                "refusing updateInstead on '{refname}': working tree has uncommitted modifications at '{rel_path}'"
            )));
        }
    }

    if let Some(target_oid) = new_oid {
        if let Ok(new_files) = commit_tree_map(repo, target_oid) {
            for (rel_path, new_blob_oid) in new_files {
                if head_files.contains_key(&rel_path) {
                    continue;
                }
                if !is_safe_worktree_rel_path(&rel_path) {
                    return Err(GateReject::Conflict(format!(
                        "refusing updateInstead on '{refname}': unsafe target path '{rel_path}'"
                    )));
                }
                let full = work_tree.join(&rel_path);
                if fs::symlink_metadata(&full).is_ok() {
                    let matches_new = read_worktree_entry_bytes(&full)
                        .and_then(|(b, is_sym)| {
                            worktree_bytes_match_blob(repo, &b, is_sym, &new_blob_oid, autocrlf)
                                .ok()
                        })
                        .unwrap_or(false);
                    if !matches_new {
                        return Err(GateReject::Conflict(format!(
                            "refusing updateInstead on '{refname}': untracked working tree file '{rel_path}' would be overwritten"
                        )));
                    }
                }
            }
        }
    }
    Ok(())
}

fn is_safe_worktree_rel_path(rel: &str) -> bool {
    !rel.is_empty()
        && !rel.starts_with('/')
        && !rel.ends_with('/')
        && !rel.contains('\\')
        && !rel
            .split('/')
            .any(|seg| seg.is_empty() || seg == "." || seg == ".." || seg == ".git")
}

fn flatten_tree_with_modes(
    repo: &Repository,
    tree_oid: &Oid,
    prefix: &str,
    out: &mut HashMap<String, (TreeMode, Oid)>,
) -> Result<(), GateReject> {
    let raw = repo
        .get_object(tree_oid)
        .map_err(|e| GateReject::Internal(format!("worktree sync load tree: {e}")))?;
    if raw.kind != ObjectKind::Tree {
        return Err(GateReject::Internal(
            "worktree sync: object is not a tree".into(),
        ));
    }
    let tree = arks_object::Tree::decode(&raw.payload, repo.oid_kind())
        .map_err(|e| GateReject::Internal(format!("worktree sync decode tree: {e}")))?;
    for entry in tree.entries {
        let path = if prefix.is_empty() {
            entry.name
        } else {
            format!("{prefix}/{}", entry.name)
        };
        if entry.mode == TreeMode::Tree {
            flatten_tree_with_modes(repo, &entry.oid, &path, out)?;
        } else {
            out.insert(path, (entry.mode, entry.oid));
        }
    }
    Ok(())
}

pub(crate) fn sync_worktree_for_update_instead(
    repo: &Repository,
    old_head: Option<&Oid>,
    new_oid: &Oid,
) -> Result<(), GateReject> {
    let Some(work_tree) = repo.work_tree() else {
        return Ok(());
    };
    let old_files = old_head
        .and_then(|o| commit_tree_map(repo, o).ok())
        .unwrap_or_default();
    let new_commit_raw = repo
        .get_object(new_oid)
        .map_err(|e| GateReject::Internal(format!("worktree sync load commit: {e}")))?;
    let new_commit = Commit::decode(&new_commit_raw.payload)
        .map_err(|e| GateReject::Internal(format!("worktree sync decode commit: {e}")))?;
    let mut new_map: HashMap<String, (TreeMode, Oid)> = HashMap::new();
    flatten_tree_with_modes(repo, &new_commit.tree, "", &mut new_map)?;

    // Remove tracked files deleted in the new commit.
    for old_path in old_files.keys() {
        if !new_map.contains_key(old_path) && is_safe_worktree_rel_path(old_path) {
            let full = work_tree.join(old_path);
            let _ = fs::remove_file(&full);
            let mut cur = full.parent();
            while let Some(dir) = cur {
                if dir == work_tree {
                    break;
                }
                if fs::remove_dir(dir).is_err() {
                    break;
                }
                cur = dir.parent();
            }
        }
    }

    // Materialize added or modified files in the new commit.
    for (rel_path, (mode, blob_oid)) in &new_map {
        if !is_safe_worktree_rel_path(rel_path) {
            continue;
        }
        if mode == &TreeMode::Gitlink {
            continue;
        }
        if old_files.get(rel_path) == Some(blob_oid) && work_tree.join(rel_path).exists() {
            continue;
        }
        let Ok(blob) = repo.get_object(blob_oid) else {
            continue;
        };
        let full = work_tree.join(rel_path);
        if let Some(parent) = full.parent() {
            let _ = fs::create_dir_all(parent);
        }
        let _ = fs::remove_file(&full);
        #[cfg(unix)]
        if mode == &TreeMode::Symlink {
            let target = String::from_utf8_lossy(&blob.payload);
            let _ = std::os::unix::fs::symlink(target.as_ref(), &full);
            continue;
        }
        if fs::write(&full, &blob.payload).is_ok() {
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                let perm = if mode == &TreeMode::Executable {
                    0o755
                } else {
                    0o644
                };
                let _ = fs::set_permissions(&full, fs::Permissions::from_mode(perm));
            }
        }
    }

    // Atomically synchronize `.git/index` to `new_commit.tree` so `git status` and
    // `git diff --cached` never see reverse-deletions after non-bare checkout updates.
    sync_index_for_tree_map(repo, work_tree, &new_map)?;
    Ok(())
}

fn sync_index_for_tree_map(
    repo: &Repository,
    work_tree: &Path,
    new_map: &HashMap<String, (TreeMode, Oid)>,
) -> Result<(), GateReject> {
    let mut entries = Vec::with_capacity(new_map.len());
    for (rel_path, (mode, oid)) in new_map {
        let mode_u32 = match mode {
            TreeMode::Gitlink => 0o160000,
            TreeMode::Symlink => 0o120000,
            TreeMode::Executable => 0o100755,
            TreeMode::File | TreeMode::Tree => 0o100644,
        };
        let (ctime_sec, ctime_nsec, mtime_sec, mtime_nsec, dev, ino, uid, gid, size) =
            if *mode == TreeMode::Gitlink {
                (0, 0, 0, 0, 0, 0, 0, 0, 0)
            } else if let Ok(meta) = fs::symlink_metadata(work_tree.join(rel_path)) {
                let (ms, mn) = meta
                    .modified()
                    .ok()
                    .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                    .map(|d| (d.as_secs() as u32, d.subsec_nanos()))
                    .unwrap_or((0, 0));
                let sz = meta.len().min(u32::MAX as u64) as u32;
                #[cfg(unix)]
                let (cs, cn, d, i, u, g) = {
                    use std::os::unix::fs::MetadataExt;
                    (
                        meta.ctime() as u32,
                        meta.ctime_nsec() as u32,
                        meta.dev() as u32,
                        meta.ino() as u32,
                        meta.uid(),
                        meta.gid(),
                    )
                };
                #[cfg(not(unix))]
                let (cs, cn, d, i, u, g) = (ms, mn, 0u32, 0u32, 0u32, 0u32);
                (cs, cn, ms, mn, d, i, u, g, sz)
            } else {
                (0, 0, 0, 0, 0, 0, 0, 0, 0)
            };
        let flags = rel_path.len().min(0x0fff) as u16;
        entries.push(arks_index::IndexEntry {
            ctime_sec,
            ctime_nsec,
            mtime_sec,
            mtime_nsec,
            dev,
            ino,
            mode: mode_u32,
            uid,
            gid,
            size,
            oid: *oid,
            flags,
            flags_extended: None,
            path: rel_path.clone(),
        });
    }
    arks_index::sort_entries(&mut entries);
    let idx = arks_index::Index {
        version: 2,
        entries,
        extensions: Vec::new(),
    };
    let encoded = idx
        .write(repo.oid_kind())
        .map_err(|e| GateReject::Internal(format!("index encode failed: {e}")))?;
    arks_index::write_index_locked(&repo.index_path(), &encoded)
        .map_err(|e| GateReject::Internal(format!("index write failed: {e}")))?;
    Ok(())
}

/// Enforce internal ref isolation, archived-repo immutability, `ForgeStore.branch_rules`
/// (`block_delete`, `block_force_push`), non-ff rules, and the
/// installed process-wide [`PushPolicy`](crate::push_policy::PushPolicy).
pub fn enforce_branch_rules_and_policy(
    repo: &Repository,
    upd: &GatedRefUpdate,
) -> Result<(), GateReject> {
    if !is_valid_refname(&upd.refname) {
        return Err(GateReject::Forbidden(format!(
            "invalid ref name '{}'",
            upd.refname
        )));
    }
    // (a) Internal `refs/arks/*` confidentiality unless explicitly allowed.
    if !upd.allow_internal_arks_ref && is_internal_arks_ref(&upd.refname) {
        return Err(GateReject::Forbidden(format!(
            "ref '{}' is reserved for internal arks metadata",
            upd.refname
        )));
    }

    // (b) ForgeStore corrupt (fail-closed) and archived checks.
    let store = ForgeStore::load_shared(repo.common_dir());
    if store.corrupt {
        return Err(GateReject::Internal(
            "forge store is corrupted; refusing ref update (fail-closed)".into(),
        ));
    }
    if store.archived {
        return Err(GateReject::Forbidden(
            "repository is archived (read-only)".into(),
        ));
    }

    let live_old = repo.refs().resolve(&upd.refname).ok();

    // Enforce fast-forward unless caller explicitly opted in to non-ff.
    if let (Some(old_oid), Some(new_oid)) = (live_old, upd.new_oid) {
        if old_oid != new_oid && !upd.allow_non_ff && !is_commit_ancestor(repo, old_oid, new_oid) {
            return Err(GateReject::Conflict(format!(
                "non-fast-forward update rejected for '{}'",
                upd.refname
            )));
        }
    }

    // (c) `ForgeStore.branch_rules` enforcement for `refs/heads/<branch>`.
    if let Some(branch) = upd.refname.strip_prefix("refs/heads/") {
        let matching: Vec<_> = store
            .branch_rules
            .iter()
            .filter(|r| branch_rule_matches(&r.pattern, branch))
            .collect();

        if upd.new_oid.is_none() {
            if matching.iter().any(|r| r.block_delete) {
                return Err(GateReject::Forbidden(format!(
                    "branch deletion of '{branch}' blocked by branch protection rule"
                )));
            }
        } else if let Some(new_oid) = upd.new_oid {
            if let Some(old_oid) = live_old {
                if old_oid != new_oid
                    && matching.iter().any(|r| r.block_force_push)
                    && !is_commit_ancestor(repo, old_oid, new_oid)
                {
                    return Err(GateReject::Forbidden(format!(
                        "force push to '{branch}' blocked by branch protection rule"
                    )));
                }
            }
        }
    }

    // (d) Process-wide `installed_push_policy()` rulesets.
    if let Some(policy) = installed_push_policy() {
        let zero = zero_oid(repo.oid_kind())?;
        let old = upd.old_oid.or(live_old).unwrap_or(zero);
        let new = upd.new_oid.unwrap_or(zero);
        let ref_upd = RefUpdate {
            name: upd.refname.clone(),
            old,
            new,
        };
        let results = verdicts(Some(policy.as_ref()), repo, &upd.pusher, &[ref_upd]);
        if let Some(Some(reason)) = results.into_iter().next() {
            return Err(GateReject::Forbidden(reason));
        }
    }

    Ok(())
}

/// Apply a single gated ref update acquiring the per-repository [`RefGateGuard`].
/// Drops [`RefGateGuard`] BEFORE dispatching synchronous webhooks and CI workflows.
pub fn apply_gated_ref_update(
    repo: &mut Repository,
    upd: &GatedRefUpdate,
) -> Result<(), GateReject> {
    let guard = acquire_repo_ref_lock(repo.common_dir()).map_err(GateReject::Internal)?;
    let live_old = apply_gated_ref_update_locked_full(repo, upd, &guard, true, false)?;
    drop(guard);
    post_receive_external_effects(
        repo,
        &[(upd.refname.clone(), live_old, upd.new_oid)],
        upd.trigger_ci,
    );
    Ok(())
}

/// Apply a single gated ref update when the caller already holds [`RefGateGuard`]
/// for `repo.common_dir()`. Executes only lock-scoped effects (`update_server_info`);
/// callers needing external webhooks/CI should invoke [`post_receive_external_effects`]
/// after dropping `guard`.
pub fn apply_gated_ref_update_locked(
    repo: &mut Repository,
    upd: &GatedRefUpdate,
    guard: &RefGateGuard,
) -> Result<(), GateReject> {
    apply_gated_ref_update_locked_full(repo, upd, guard, true, false).map(|_| ())
}

/// Interactive Web UI entry point: respects explicit `receive.denyCurrentBranch`
/// config, and when unset defaults to guarded `updateInstead` (failing closed on dirty worktrees
/// while syncing both working tree and `.git/index` when clean).
/// Drops [`RefGateGuard`] BEFORE dispatching synchronous webhooks and CI workflows.
pub(crate) fn apply_gated_ref_update_interactive(
    repo: &mut Repository,
    upd: &GatedRefUpdate,
) -> Result<(), GateReject> {
    let guard = acquire_repo_ref_lock(repo.common_dir()).map_err(GateReject::Internal)?;
    let live_old = apply_gated_ref_update_locked_full(repo, upd, &guard, true, true)?;
    drop(guard);
    post_receive_external_effects(
        repo,
        &[(upd.refname.clone(), live_old, upd.new_oid)],
        upd.trigger_ci,
    );
    Ok(())
}

fn apply_gated_ref_update_locked_full(
    repo: &mut Repository,
    upd: &GatedRefUpdate,
    guard: &RefGateGuard,
    reconcile_internal: bool,
    default_update_instead: bool,
) -> Result<Option<Oid>, GateReject> {
    let repo_key = canonical_repo_key(repo.common_dir());
    if guard.common_dir_key != repo_key {
        return Err(GateReject::Internal(
            "RefGateGuard held for a different repository".into(),
        ));
    }

    let live_old = repo.refs().resolve(&upd.refname).ok();
    if let Some(expected_old) = upd.old_oid {
        match live_old {
            Some(actual) if actual == expected_old => {}
            Some(actual) => {
                return Err(GateReject::Conflict(format!(
                    "CAS mismatch on '{}': expected {}, found {}",
                    upd.refname,
                    expected_old.to_hex(),
                    actual.to_hex()
                )));
            }
            None => {
                return Err(GateReject::Conflict(format!(
                    "CAS mismatch on '{}': expected {}, ref does not exist",
                    upd.refname,
                    expected_old.to_hex()
                )));
            }
        }
    }

    if let Some(new_oid) = upd.new_oid {
        if repo.get_object(&new_oid).is_err() {
            return Err(GateReject::PreconditionFailed(format!(
                "target object {} missing from repository object store",
                new_oid.to_hex()
            )));
        }
    }

    enforce_branch_rules_and_policy(repo, upd)?;
    let should_update_worktree = check_non_bare_deny_current_branch_with_default(
        repo,
        &upd.refname,
        upd.new_oid.as_ref(),
        default_update_instead,
    )?;

    let old_hex = live_old
        .map(|o| o.to_hex())
        .unwrap_or_else(|| zero_hex(repo.oid_kind()));
    let new_hex = upd
        .new_oid
        .map(|o| o.to_hex())
        .unwrap_or_else(|| zero_hex(repo.oid_kind()));
    let stdin_line = format!("{old_hex} {new_hex} {}\n", upd.refname);
    let hook_env = HookEnv::default();

    if run_pre_receive(repo.git_dir(), stdin_line.as_bytes(), &hook_env)
        .map_err(|e| GateReject::Internal(e.to_string()))?
        == HookGate::Decline
    {
        return Err(GateReject::Forbidden("pre-receive hook declined".into()));
    }
    if run_update(repo.git_dir(), &upd.refname, &old_hex, &new_hex, &hook_env)
        .map_err(|e| GateReject::Internal(e.to_string()))?
        == HookGate::Decline
    {
        return Err(GateReject::Forbidden("update hook declined".into()));
    }

    if let Some(new_oid) = upd.new_oid {
        repo.refs_mut()
            .update(&upd.refname, &new_oid, live_old.as_ref())
            .map_err(|e| GateReject::Conflict(format!("atomic ref update failed: {e}")))?;
        if should_update_worktree {
            if let Err(rej) = sync_worktree_for_update_instead(repo, live_old.as_ref(), &new_oid) {
                if let Some(prev) = live_old.as_ref() {
                    let _ = repo.refs_mut().update(&upd.refname, prev, Some(&new_oid));
                } else {
                    let _ = repo.refs_mut().delete(&upd.refname, Some(&new_oid));
                }
                return Err(rej);
            }
        }
    } else {
        repo.refs_mut()
            .delete(&upd.refname, live_old.as_ref())
            .map_err(|e| GateReject::Conflict(format!("atomic ref delete failed: {e}")))?;
    }

    run_post_receive(repo.git_dir(), stdin_line.as_bytes(), &hook_env);
    run_post_update(repo.git_dir(), &[upd.refname.as_str()], &hook_env);

    post_receive_locked_effects(
        repo,
        &[(upd.refname.clone(), live_old, upd.new_oid)],
        reconcile_internal,
    );
    Ok(live_old)
}

/// Shared post-receive side effects combining lock-scoped repository refreshes and
/// external notifications:
/// 1. Refresh dumb HTTP `info/refs` & `objects/info/packs` (best-effort).
/// 2. Dispatch signed `"push"` webhook events for non-internal refs.
/// 3. Trigger opt-in local Actions CI workflows when `trigger_ci` is true.
pub fn post_receive_side_effects(
    repo: &Repository,
    updates: &[(String, Option<Oid>, Option<Oid>)],
    trigger_ci: bool,
) {
    post_receive_locked_effects(repo, updates, true);
    post_receive_external_effects(repo, updates, trigger_ci);
}

/// Lock-scoped post-receive effects (run while holding [`RefGateGuard`]):
/// 1. Best-effort dumb HTTP `info/refs` & `objects/info/packs` refresh.
pub(crate) fn post_receive_locked_effects(
    repo: &Repository,
    updates: &[(String, Option<Oid>, Option<Oid>)],
    _reconcile_internal: bool,
) {
    if updates.is_empty() {
        return;
    }

    // Best-effort dumb HTTP metadata refresh (`info/refs`, `objects/info/packs`).
    let _ = crate::dumb::update_server_info(repo);
}

/// External post-receive effects (MUST run AFTER dropping [`RefGateGuard`]):
/// 3. Dispatch signed `"push"` webhook events for public/normal refs.
/// 3. Trigger opt-in local Actions CI workflows when `trigger_ci` is true.
pub(crate) fn post_receive_external_effects(
    repo: &Repository,
    updates: &[(String, Option<Oid>, Option<Oid>)],
    trigger_ci: bool,
) {
    if updates.is_empty() {
        return;
    }

    // 3. Dispatch `"push"` webhooks for public/normal refs (skip internal `refs/arks/*`).
    let zero = zero_hex(repo.oid_kind());
    let mut has_non_internal_update = false;
    for (refname, old_oid, new_oid) in updates {
        if is_internal_arks_ref(refname) {
            continue;
        }
        if new_oid.is_some() {
            has_non_internal_update = true;
        }
        let before = old_oid.map(|o| o.to_hex()).unwrap_or_else(|| zero.clone());
        let after = new_oid.map(|o| o.to_hex()).unwrap_or_else(|| zero.clone());
        let payload = serde_json::json!({
            "event": "push",
            "ref": refname,
            "before": before,
            "after": after,
        })
        .to_string();
        crate::web_ui::dispatch_webhook_event(repo.common_dir(), "push", &payload);
    }

    // 4. Trigger opt-in local Actions CI workflows.
    if trigger_ci && has_non_internal_update {
        crate::web_ui::trigger_event_workflows(repo.common_dir(), "push");
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::web_ui::store::BranchRule;
    use arks_object::{Signature, Tree, TreeEntry};
    use arks_store::ObjectStore;
    use tempfile::TempDir;

    fn make_commit(
        repo: &mut Repository,
        parents: Vec<Oid>,
        files: &[(&str, &[u8])],
        msg: &str,
    ) -> (Oid, Oid) {
        let fmt = repo.object_format();
        let mut entries = Vec::new();
        for (name, content) in files {
            let blob_oid = repo
                .store_mut()
                .put(fmt, &RawObject::new(ObjectKind::Blob, content.to_vec()))
                .unwrap();
            entries.push(TreeEntry {
                mode: TreeMode::File,
                name: (*name).to_string(),
                oid: blob_oid,
            });
        }
        entries.sort_by(|a, b| a.name.cmp(&b.name));
        let tree_oid = repo
            .store_mut()
            .put(
                fmt,
                &RawObject::new(ObjectKind::Tree, Tree { entries }.encode().unwrap()),
            )
            .unwrap();
        let sig = Signature {
            name: "test".into(),
            email: "test@example.invalid".into(),
            timestamp: 1_700_000_000,
            timezone: "+0000".into(),
        };
        let commit = Commit {
            tree: tree_oid,
            parents,
            author: sig.clone(),
            committer: sig,
            gpgsig: None,
            message: msg.into(),
        };
        let oid = repo
            .store_mut()
            .put(
                fmt,
                &RawObject::new(ObjectKind::Commit, commit.encode().unwrap()),
            )
            .unwrap();
        (oid, tree_oid)
    }

    fn init_bare_classic(root: &Path) -> (Repository, Oid) {
        fs::create_dir_all(root.join("objects")).unwrap();
        fs::create_dir_all(root.join("refs/heads")).unwrap();
        fs::write(root.join("HEAD"), b"ref: refs/heads/main\n").unwrap();
        fs::write(root.join("config"), b"[core]\n\tbare = true\n").unwrap();
        let mut repo = Repository::open(root).unwrap();
        let (c1, _) = make_commit(&mut repo, Vec::new(), &[("a.txt", b"v1\n")], "init\n");
        repo.refs_mut()
            .update("refs/heads/main", &c1, None)
            .unwrap();
        (repo, c1)
    }

    fn init_non_bare(root: &Path) -> (Repository, Oid) {
        let git_dir = root.join(".git");
        fs::create_dir_all(git_dir.join("objects")).unwrap();
        fs::create_dir_all(git_dir.join("refs/heads")).unwrap();
        fs::write(git_dir.join("HEAD"), b"ref: refs/heads/main\n").unwrap();
        fs::write(git_dir.join("config"), b"[core]\n\tbare = false\n").unwrap();
        fs::write(root.join("a.txt"), b"v1\n").unwrap();
        let mut repo = Repository::open(&git_dir).unwrap();
        let (c1, _) = make_commit(&mut repo, Vec::new(), &[("a.txt", b"v1\n")], "init\n");
        repo.refs_mut()
            .update("refs/heads/main", &c1, None)
            .unwrap();
        (repo, c1)
    }

    #[test]
    fn ref_gate_rejects_internal_refs_and_archived_and_respects_od1() {
        let tmp = TempDir::new().unwrap();
        let (mut repo, c1) = init_bare_classic(tmp.path());
        let (c2, _) = make_commit(&mut repo, vec![c1], &[("a.txt", b"v2\n")], "second\n");

        // Internal refs/arks/* rejected unless allow_internal_arks_ref is true.
        let bad_internal = GatedRefUpdate {
            refname: "refs/arks/v2/keep/fake".into(),
            old_oid: None,
            new_oid: Some(c2),
            allow_non_ff: true,
            pusher: Pusher::local(),
            allow_internal_arks_ref: false,
            trigger_ci: false,
        };
        assert!(matches!(
            apply_gated_ref_update(&mut repo, &bad_internal),
            Err(GateReject::Forbidden(_))
        ));

        // Normal update succeeds AND preserves OD-1 (does not create `.git/arks/v2/`).
        let good = GatedRefUpdate {
            refname: "refs/heads/main".into(),
            old_oid: Some(c1),
            new_oid: Some(c2),
            allow_non_ff: false,
            pusher: Pusher::local(),
            allow_internal_arks_ref: false,
            trigger_ci: false,
        };
        apply_gated_ref_update(&mut repo, &good).unwrap();
        assert_eq!(repo.refs().resolve("refs/heads/main").unwrap(), c2);
        assert!(
            !repo.common_dir().join("arks").join("v2").exists(),
            "RefUpdateGate must not create arks/v2/ on a classic repository"
        );
        assert!(
            repo.common_dir().join("info/refs").is_file(),
            "RefUpdateGate must refresh dumb HTTP info/refs"
        );

        // Archived repo rejects updates.
        ForgeStore::update(repo.common_dir(), |s| s.archived = true).unwrap();
        let (c3, _) = make_commit(&mut repo, vec![c2], &[("a.txt", b"v3\n")], "third\n");
        let archived_upd = GatedRefUpdate {
            refname: "refs/heads/main".into(),
            old_oid: Some(c2),
            new_oid: Some(c3),
            allow_non_ff: false,
            pusher: Pusher::local(),
            allow_internal_arks_ref: false,
            trigger_ci: false,
        };
        assert!(matches!(
            apply_gated_ref_update(&mut repo, &archived_upd),
            Err(GateReject::Forbidden(_))
        ));
    }

    #[test]
    fn ref_gate_enforces_branch_rules_delete_and_force_push() {
        let tmp = TempDir::new().unwrap();
        let (mut repo, c1) = init_bare_classic(tmp.path());
        let (c2, _) = make_commit(&mut repo, vec![c1], &[("a.txt", b"v2\n")], "c2\n");
        let (c_div, _) = make_commit(&mut repo, Vec::new(), &[("a.txt", b"div\n")], "div\n");

        ForgeStore::update(repo.common_dir(), |s| {
            s.branch_rules.push(BranchRule {
                pattern: "main".into(),
                require_pr: false,
                block_force_push: true,
                block_delete: true,
                required_reviews: 0,
            });
        })
        .unwrap();

        // Deletion blocked.
        let del = GatedRefUpdate {
            refname: "refs/heads/main".into(),
            old_oid: Some(c1),
            new_oid: None,
            allow_non_ff: true,
            pusher: Pusher::local(),
            allow_internal_arks_ref: false,
            trigger_ci: false,
        };
        assert!(matches!(
            apply_gated_ref_update(&mut repo, &del),
            Err(GateReject::Forbidden(_))
        ));

        // Force-push blocked even when allow_non_ff is true.
        let force = GatedRefUpdate {
            refname: "refs/heads/main".into(),
            old_oid: Some(c1),
            new_oid: Some(c_div),
            allow_non_ff: true,
            pusher: Pusher::local(),
            allow_internal_arks_ref: false,
            trigger_ci: false,
        };
        assert!(matches!(
            apply_gated_ref_update(&mut repo, &force),
            Err(GateReject::Forbidden(_))
        ));

        // Fast-forward update succeeds!
        let ff = GatedRefUpdate {
            refname: "refs/heads/main".into(),
            old_oid: Some(c1),
            new_oid: Some(c2),
            allow_non_ff: false,
            pusher: Pusher::local(),
            allow_internal_arks_ref: false,
            trigger_ci: false,
        };
        apply_gated_ref_update(&mut repo, &ff).unwrap();
        assert_eq!(repo.refs().resolve("refs/heads/main").unwrap(), c2);
    }

    #[test]
    fn non_bare_deny_current_branch_refuses_by_default_and_handles_update_instead() {
        let tmp = TempDir::new().unwrap();
        let (mut repo, c1) = init_non_bare(tmp.path());
        let (c2, _) = make_commit(&mut repo, vec![c1], &[("a.txt", b"v2\n")], "v2\n");

        // Default receive.denyCurrentBranch=refuse rejects checked-out main.
        let upd = GatedRefUpdate {
            refname: "refs/heads/main".into(),
            old_oid: Some(c1),
            new_oid: Some(c2),
            allow_non_ff: false,
            pusher: Pusher::local(),
            allow_internal_arks_ref: false,
            trigger_ci: false,
        };
        assert!(matches!(
            apply_gated_ref_update(&mut repo, &upd),
            Err(GateReject::Conflict(_))
        ));
        assert_eq!(repo.refs().resolve("refs/heads/main").unwrap(), c1);

        // Configure updateInstead: dirty worktree must still be refused!
        fs::write(
            repo.git_dir().join("config"),
            b"[core]\n\tbare = false\n[receive]\n\tdenyCurrentBranch = updateInstead\n",
        )
        .unwrap();
        fs::write(tmp.path().join("a.txt"), b"dirty local edit\n").unwrap();
        assert!(matches!(
            apply_gated_ref_update(&mut repo, &upd),
            Err(GateReject::Conflict(_))
        ));

        // Clean worktree succeeds and updates worktree file to v2!
        fs::write(tmp.path().join("a.txt"), b"v1\n").unwrap();
        apply_gated_ref_update(&mut repo, &upd).unwrap();
        assert_eq!(repo.refs().resolve("refs/heads/main").unwrap(), c2);
        assert_eq!(
            fs::read_to_string(tmp.path().join("a.txt")).unwrap(),
            "v2\n"
        );
    }

    #[test]
    fn ref_gate_reclaims_stale_lockfile() {
        let tmp = TempDir::new().unwrap();
        let lock_path = tmp.path().join(REF_GATE_LOCK_FILE);
        fs::write(&lock_path, b"pid=999999\n").unwrap();
        std::thread::sleep(Duration::from_millis(15));
        let guard =
            acquire_file_lock_with(&lock_path, Duration::from_millis(5), Duration::from_secs(2))
                .expect("stale ref gate lockfile must be reclaimed");
        assert!(lock_path.is_file());
        drop(guard);
        assert!(!lock_path.exists());
    }

    #[test]
    fn ref_gate_drops_lock_before_webhook_dispatch() {
        use crate::web_ui::allow_loopback_webhooks_for_repo;
        use crate::web_ui::store::WebhookRecord;
        use std::io::{Read as _, Write as _};
        use std::net::TcpListener;

        let tmp = TempDir::new().unwrap();
        let (mut repo, c1) = init_bare_classic(tmp.path());
        let (c2, _) = make_commit(&mut repo, vec![c1], &[("a.txt", b"v2\n")], "v2\n");

        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        let common_dir_bg = repo.common_dir().to_path_buf();
        let lock_path_bg = common_dir_bg.join(REF_GATE_LOCK_FILE);

        let srv = std::thread::spawn(move || {
            let (mut stream, _) = listener.accept().unwrap();
            let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
            let mut req = Vec::new();
            let mut buf = [0u8; 2048];
            let mut header_end = None;
            let mut content_len = 0usize;
            loop {
                match stream.read(&mut buf) {
                    Ok(0) | Err(_) => break,
                    Ok(n) => {
                        req.extend_from_slice(&buf[..n]);
                        if header_end.is_none() {
                            if let Some(pos) = req.windows(4).position(|w| w == b"\r\n\r\n") {
                                header_end = Some(pos + 4);
                                let hdrs = String::from_utf8_lossy(&req[..pos]);
                                for line in hdrs.lines() {
                                    if let Some((k, v)) = line.split_once(':') {
                                        if k.trim().eq_ignore_ascii_case("content-length") {
                                            content_len = v.trim().parse().unwrap_or(0);
                                        }
                                    }
                                }
                            }
                        }
                        if let Some(end) = header_end {
                            if req.len() >= end + content_len {
                                break;
                            }
                        }
                    }
                }
            }
            let lock_file_absent = !lock_path_bg.exists();
            // Acquiring the repository ref gate lock inside the synchronous webhook receiver
            // would deadlock if RefGateGuard were still held during webhook dispatch.
            let acquired_while_in_webhook = acquire_repo_ref_lock(&common_dir_bg).is_ok();
            let _ = stream
                .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok");
            let _ = stream.flush();
            let _ = stream.shutdown(std::net::Shutdown::Write);
            (lock_file_absent, acquired_while_in_webhook)
        });

        let _loopback_guard = allow_loopback_webhooks_for_repo(repo.common_dir());
        ForgeStore::update(repo.common_dir(), |s| {
            s.next_webhook_id = 2;
            s.webhooks.push(WebhookRecord {
                id: 1,
                url: format!("http://{addr}/hook"),
                secret: "sec".into(),
                events: vec!["push".into()],
                active: true,
                created_at: 1,
            });
        })
        .unwrap();

        let upd = GatedRefUpdate {
            refname: "refs/heads/main".into(),
            old_oid: Some(c1),
            new_oid: Some(c2),
            allow_non_ff: false,
            pusher: Pusher::local(),
            allow_internal_arks_ref: false,
            trigger_ci: false,
        };
        apply_gated_ref_update(&mut repo, &upd).unwrap();

        let (lock_file_absent, acquired_while_in_webhook) = srv.join().unwrap();
        assert!(
            lock_file_absent,
            "arks-ref-gate.lock must be removed before synchronous webhook dispatch"
        );
        assert!(
            acquired_while_in_webhook,
            "RefGateGuard must be dropped before synchronous webhook dispatch"
        );
        let st = ForgeStore::load_shared(repo.common_dir());
        assert_eq!(st.webhook_deliveries.len(), 1);
        assert_eq!(st.webhook_deliveries[0].status, 200);
    }

    #[test]
    fn update_instead_accepts_crlf_checkout_when_core_autocrlf_enabled() {
        let tmp = TempDir::new().unwrap();
        let wt = tmp.path();
        let git_dir = wt.join(".git");
        fs::create_dir_all(git_dir.join("objects")).unwrap();
        fs::create_dir_all(git_dir.join("refs/heads")).unwrap();
        fs::write(git_dir.join("HEAD"), b"ref: refs/heads/main\n").unwrap();
        fs::write(
            git_dir.join("config"),
            b"[core]\n\trepositoryformatversion = 0\n\tbare = false\n\tautocrlf = true\n[receive]\n\tdenyCurrentBranch = updateInstead\n",
        )
        .unwrap();
        let mut repo = Repository::open(&git_dir).unwrap();
        let (c1, _) = make_commit(&mut repo, vec![], &[("f.txt", b"line1\nline2\n")], "c1\n");
        let (c2, _) = make_commit(&mut repo, vec![c1], &[("f.txt", b"line1\nline3\n")], "c2\n");
        repo.refs_mut()
            .update("refs/heads/main", &c1, None)
            .unwrap();

        // Simulate Windows Git checkout with CRLF on disk matching LF blob in HEAD.
        fs::write(wt.join("f.txt"), b"line1\r\nline2\r\n").unwrap();
        assert!(
            check_non_bare_deny_current_branch(&repo, "refs/heads/main", Some(&c2)).unwrap(),
            "CRLF checkout of LF blob must be considered clean when core.autocrlf=true"
        );

        // Actual content modification must still fail closed with 409 Conflict.
        fs::write(wt.join("f.txt"), b"line1\r\ndirty\r\n").unwrap();
        assert!(
            matches!(
                check_non_bare_deny_current_branch(&repo, "refs/heads/main", Some(&c2)),
                Err(GateReject::Conflict(_))
            ),
            "actual uncommitted edit must still be rejected"
        );
    }
}