arks-server 1.3.11

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
//! receive-pack service (push path).
//!
//! Claimed caps: `report-status`, `report-status-v2` (classic ok/ng + FS2
//! proc-receive option rewrite when diverted), `delete-refs`,
//! `push-options` (O4; forward to hooks), `proc-receive` (FS2 when hook
//! present), `agent`.
//! Cite: <https://git-scm.com/docs/gitprotocol-capabilities>,
//! <https://git-scm.com/docs/git-receive-pack> (quarantine environment).

use crate::advertise::{encode_http_advertisement, encode_pack_advertisement};
use crate::error::ServerError;
use crate::hooks::{
    HookEnv, HookGate, ProcReceiveCmd, proc_receive_hook_present, proc_receive_ref_prefixes,
    ref_matches_proc_receive, run_post_receive, run_post_update, run_pre_receive, run_proc_receive,
    run_update,
};
use crate::push_policy::{PushPolicy, Pusher, RefUpdate, installed_push_policy, verdicts};
use arks_oid::Oid;
use arks_pack::DecodedPack;
use arks_protocol::{Packet, decode_packet, decode_text_line, encode_packet};
use arks_refs::RefTarget;
use arks_repo::Repository;
use arks_store::{FilesystemGitStore, ObjectStore};
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

type RefsAndCaps = (Vec<(String, Oid)>, Vec<String>);

fn receive_refs_and_caps(repo: &Repository) -> Result<RefsAndCaps, ServerError> {
    let mut refs = repo
        .refs()
        .list_refs("refs/")
        .map_err(|e| ServerError::Msg(e.to_string()))?;
    refs.retain(|(name, _)| !crate::advertise::is_internal_arks_ref(name));
    refs.sort_by(|a, b| a.0.cmp(&b.0));
    if let Ok(oid) = repo.refs().resolve("HEAD") {
        let head_points_internal = matches!(
            repo.head_target(),
            Ok(RefTarget::Symbolic(ref sym)) if crate::advertise::is_internal_arks_ref(sym)
        );
        if !head_points_internal && !refs.iter().any(|(n, _)| n == "HEAD") {
            refs.insert(0, ("HEAD".into(), oid));
        }
    } else if let Ok(RefTarget::Direct(oid)) = repo.head_target() {
        refs.insert(0, ("HEAD".into(), oid));
    }
    // Advertise only real caps. FS2: advertise `proc-receive` when hook present.
    // Cite: https://git-scm.com/docs/gitprotocol-capabilities
    let mut caps = vec![
        "report-status".into(),
        "report-status-v2".into(),
        "delete-refs".into(),
        "push-options".into(),
        "agent=arks/0.0.0".into(),
    ];
    if proc_receive_hook_present(repo.git_dir()) {
        caps.insert(caps.len() - 1, "proc-receive".into());
    }
    Ok((refs, caps))
}

/// Smart-HTTP receive-pack advertisement.
pub fn receive_advertisement(repo: &Repository) -> Result<Vec<u8>, ServerError> {
    let (refs, caps) = receive_refs_and_caps(repo)?;
    encode_http_advertisement("git-receive-pack", &caps, &refs)
}

/// Pack-protocol duplex receive-pack advertisement (SSH / stdio).
pub fn receive_pack_advertisement(repo: &Repository) -> Result<Vec<u8>, ServerError> {
    let (refs, caps) = receive_refs_and_caps(repo)?;
    encode_pack_advertisement(&caps, &refs)
}

/// receive-pack with the installed push policy and a local pusher.
pub fn receive_pack(repo: &mut Repository, body: &[u8]) -> Result<Vec<u8>, ServerError> {
    receive_pack_as(repo, body, &Pusher::local())
}

/// receive-pack with the installed push policy ([`crate::install_push_policy`]).
pub fn receive_pack_as(
    repo: &mut Repository,
    body: &[u8],
    pusher: &Pusher,
) -> Result<Vec<u8>, ServerError> {
    let policy = installed_push_policy();
    receive_pack_with(repo, body, pusher, policy.as_deref())
}

/// receive-pack gated by an explicit push policy: each refused ref is reported
/// `ng <ref> <reason>` and left unchanged; other refs proceed.
pub fn receive_pack_with(
    repo: &mut Repository,
    body: &[u8],
    pusher: &Pusher,
    policy: Option<&dyn PushPolicy>,
) -> Result<Vec<u8>, ServerError> {
    let (commands, push_options, pack) = split_commands(body)?;

    // Fail closed on corrupted or archived ForgeStore before touching objects/refs.
    let store_check = crate::web_ui::store::ForgeStore::load_shared(repo.common_dir());
    if store_check.corrupt {
        let declined: Vec<(String, Result<(), String>)> = commands
            .iter()
            .map(|cmd| {
                (
                    cmd.name.clone(),
                    Err("forge store is corrupted; refusing push (fail-closed)".into()),
                )
            })
            .collect();
        return encode_report_status_owned("ok", &declined);
    }
    if store_check.archived {
        let declined: Vec<(String, Result<(), String>)> = commands
            .iter()
            .map(|cmd| {
                (
                    cmd.name.clone(),
                    Err("repository is archived (read-only)".into()),
                )
            })
            .collect();
        return encode_report_status_owned("ok", &declined);
    }

    let quarantine = Quarantine::create(repo.git_dir())?;
    let hook_env = HookEnv {
        quarantine_path: Some(quarantine.path.clone()),
        push_options,
    };

    if !pack.is_empty() {
        if !pack.starts_with(b"PACK") {
            quarantine.discard();
            return encode_report_status("unpack unpacker error", &[]);
        }
        let decoded =
            match DecodedPack::decode_with_external_base(&pack, repo.object_format(), |base_oid| {
                repo.get_object(base_oid).ok()
            }) {
                Ok(d) => d,
                Err(e) => {
                    quarantine.discard();
                    return encode_report_status(&format!("unpack {e}"), &[]);
                }
            };
        let mut qstore = FilesystemGitStore::new(&quarantine.path)
            .map_err(|e| ServerError::Msg(e.to_string()))?;
        for object in decoded.objects {
            qstore
                .put(repo.object_format(), &object.object)
                .map_err(|e| ServerError::Msg(e.to_string()))?;
        }
    }

    // Serialize ref verification and mutation across stock `git push`, `arks push --onto`,
    // Headless API, and Web UI via the shared `RefUpdateGate` repository lock.
    let gate_lock =
        crate::ref_gate::acquire_repo_ref_lock(repo.common_dir()).map_err(ServerError::Msg)?;

    // Reload ForgeStore under the ref gate lock so concurrent archive/corrupt transitions
    // or branch protection updates cannot race past the pre-lock check.
    let store_check = crate::web_ui::store::ForgeStore::load_shared(repo.common_dir());
    if store_check.corrupt {
        quarantine.discard();
        let declined: Vec<(String, Result<(), String>)> = commands
            .iter()
            .map(|cmd| {
                (
                    cmd.name.clone(),
                    Err("forge store is corrupted; refusing push (fail-closed)".into()),
                )
            })
            .collect();
        return encode_report_status_owned("ok", &declined);
    }
    if store_check.archived {
        quarantine.discard();
        let declined: Vec<(String, Result<(), String>)> = commands
            .iter()
            .map(|cmd| {
                (
                    cmd.name.clone(),
                    Err("repository is archived (read-only)".into()),
                )
            })
            .collect();
        return encode_report_status_owned("ok", &declined);
    }

    // Honor list: pre-receive once after unpack, before any ref update.
    // Cite: https://git-scm.com/docs/githooks , https://git-scm.com/docs/git-receive-pack
    let pre_stdin = hook_stdin_lines(&commands);
    if run_pre_receive(repo.git_dir(), &pre_stdin, &hook_env)? == HookGate::Decline {
        quarantine.discard();
        let declined: Vec<(String, Result<(), String>)> = commands
            .iter()
            .map(|cmd| (cmd.name.clone(), Err("pre-receive hook declined".into())))
            .collect();
        return encode_report_status_owned("ok", &declined);
    }

    // Migrate quarantined objects into the main store only after pre-receive.
    quarantine.migrate_into(repo).map_err(ServerError::Msg)?;

    let prefixes = proc_receive_ref_prefixes(repo.git_dir());
    let use_proc = proc_receive_hook_present(repo.git_dir()) && !prefixes.is_empty();

    // Push policy (forge rulesets): decided per ref after unpack, before any ref moves.
    let updates: Vec<RefUpdate> = commands
        .iter()
        .map(|c| RefUpdate {
            name: c.name.clone(),
            old: c.old,
            new: c.new,
        })
        .collect();
    let refused = verdicts(policy, repo, pusher, &updates);

    let mut results: Vec<(String, Result<(), String>)> = Vec::new();
    let mut success_cmds: Vec<ReceiveCommand> = Vec::new();
    let mut applied_side_effects: Vec<(String, Option<Oid>, Option<Oid>)> = Vec::new();
    let mut diverted: Vec<ReceiveCommand> = Vec::new();
    let mut ordinary: Vec<&ReceiveCommand> = Vec::new();
    for (cmd, refusal) in commands.iter().zip(refused) {
        if crate::advertise::is_internal_arks_ref(&cmd.name) {
            results.push((
                cmd.name.clone(),
                Err(format!(
                    "ref '{}' is reserved for internal arks metadata",
                    cmd.name
                )),
            ));
            continue;
        }
        if let Some(reason) = refusal {
            results.push((cmd.name.clone(), Err(reason)));
            continue;
        }
        if use_proc && ref_matches_proc_receive(&cmd.name, &prefixes) {
            diverted.push(cmd.clone());
        } else {
            ordinary.push(cmd);
        }
    }

    for cmd in ordinary {
        let old = repo.refs().resolve(&cmd.name).ok();
        // Expect old matches when peer sent non-zero old (fast-forward check deferred:
        // accept if old is None or matches cmd.old, else refuse).
        if !cmd.old.as_bytes().iter().all(|b| *b == 0) {
            match old {
                Some(oid) if oid != cmd.old => {
                    results.push((cmd.name.clone(), Err("non-fast-forward".into())));
                    continue;
                }
                None => {
                    results.push((cmd.name.clone(), Err("old oid mismatch".into())));
                    continue;
                }
                _ => {}
            }
        }
        let target_new = if is_delete(cmd) { None } else { Some(cmd.new) };
        let should_update_worktree = match crate::ref_gate::check_non_bare_deny_current_branch(
            repo,
            &cmd.name,
            target_new.as_ref(),
        ) {
            Ok(v) => v,
            Err(rej) => {
                results.push((cmd.name.clone(), Err(rej.message().to_string())));
                continue;
            }
        };
        let old_hex = cmd.old.to_hex();
        let new_hex = cmd.new.to_hex();
        if run_update(repo.git_dir(), &cmd.name, &old_hex, &new_hex, &hook_env)?
            == HookGate::Decline
        {
            results.push((cmd.name.clone(), Err("hook declined".into())));
            continue;
        }
        if let Err(reason) =
            check_branch_protection_rules(repo, &store_check, &cmd.name, old, target_new)
        {
            results.push((cmd.name.clone(), Err(reason)));
            continue;
        }
        if is_delete(cmd) {
            match repo.refs_mut().delete(&cmd.name, old.as_ref()) {
                Ok(()) => {
                    results.push((cmd.name.clone(), Ok(())));
                    success_cmds.push(cmd.clone());
                    applied_side_effects.push((cmd.name.clone(), old, None));
                }
                Err(e) => results.push((cmd.name.clone(), Err(e.to_string()))),
            }
            continue;
        }
        match repo.refs_mut().update(&cmd.name, &cmd.new, old.as_ref()) {
            Ok(()) => {
                if should_update_worktree {
                    if let Err(rej) = crate::ref_gate::sync_worktree_for_update_instead(
                        repo,
                        old.as_ref(),
                        &cmd.new,
                    ) {
                        if let Some(prev) = old.as_ref() {
                            let _ = repo.refs_mut().update(&cmd.name, prev, Some(&cmd.new));
                        } else {
                            let _ = repo.refs_mut().delete(&cmd.name, Some(&cmd.new));
                        }
                        results.push((cmd.name.clone(), Err(rej.message().to_string())));
                        continue;
                    }
                }
                results.push((cmd.name.clone(), Ok(())));
                success_cmds.push(cmd.clone());
                applied_side_effects.push((cmd.name.clone(), old, Some(cmd.new)));
            }
            Err(e) => results.push((cmd.name.clone(), Err(e.to_string()))),
        }
    }

    if !diverted.is_empty() {
        // FS8 / HOOK-008 closest: refuse concurrent proc-receive under lock.
        let pr_lock = repo.git_dir().join("hooks").join("proc-receive.lock");
        if pr_lock.is_file() {
            return Err(ServerError::Msg(format!(
                "{} (HOOK-008 — concurrent proc-receive refuse; serialize push-options/proc-receive; lease ≠ skip)",
                pr_lock.display()
            )));
        }
        let _ = fs::write(&pr_lock, b"arks-proc-receive\n");
        let pr_cmds: Vec<ProcReceiveCmd> = diverted
            .iter()
            .map(|c| ProcReceiveCmd {
                old_hex: c.old.to_hex(),
                new_hex: c.new.to_hex(),
                name: c.name.clone(),
            })
            .collect();
        let pr_results = match run_proc_receive(repo.git_dir(), &pr_cmds, &hook_env) {
            Ok(r) => {
                let _ = fs::remove_file(&pr_lock);
                r
            }
            Err(e) => {
                let _ = fs::remove_file(&pr_lock);
                return Err(e);
            }
        };
        for pr in pr_results {
            if !pr.ok {
                results.push((
                    pr.name,
                    Err(pr.error.unwrap_or_else(|| "proc-receive declined".into())),
                ));
                continue;
            }
            // Apply rewrite if hook provided option refname / new-oid; else
            // treat ok as "hook handled ref" without receive-pack updating the
            // original name (stock git behavior for successful proc-receive).
            let target_name = pr.rewrite_ref.clone().unwrap_or_else(|| pr.name.clone());
            if !arks_refs::is_valid_refname(&target_name) {
                results.push((pr.name, Err(format!("invalid ref name '{target_name}'"))));
                continue;
            }
            if crate::advertise::is_internal_arks_ref(&target_name) {
                results.push((
                    pr.name,
                    Err(format!(
                        "ref '{target_name}' is reserved for internal arks metadata"
                    )),
                ));
                continue;
            }
            let new_oid = if let Some(hex) = &pr.rewrite_new {
                Oid::from_hex(hex).map_err(|e| ServerError::Msg(e.to_string()))?
            } else {
                diverted
                    .iter()
                    .find(|c| c.name == pr.name)
                    .map(|c| c.new)
                    .ok_or_else(|| ServerError::Msg("proc-receive missing cmd".into()))?
            };
            let live_old = repo.refs().resolve(&target_name).ok();
            let old_hint = if let Some(hex) = &pr.rewrite_old {
                Some(Oid::from_hex(hex).map_err(|e| ServerError::Msg(e.to_string()))?)
            } else {
                live_old
            };
            let is_del = new_oid.as_bytes().iter().all(|b| *b == 0);
            let target_new = if is_del { None } else { Some(new_oid) };
            if pr.rewrite_ref.is_some() && policy.is_some() {
                let target_upd = RefUpdate {
                    name: target_name.clone(),
                    old: live_old.unwrap_or_else(zero_oid),
                    new: new_oid,
                };
                if let Some(Some(reason)) = verdicts(policy, repo, pusher, &[target_upd])
                    .into_iter()
                    .next()
                {
                    results.push((pr.name, Err(reason)));
                    continue;
                }
            }
            if let Err(reason) = check_branch_protection_rules(
                repo,
                &store_check,
                &target_name,
                live_old,
                target_new,
            ) {
                results.push((pr.name, Err(reason)));
                continue;
            }
            let should_update_worktree = match crate::ref_gate::check_non_bare_deny_current_branch(
                repo,
                &target_name,
                target_new.as_ref(),
            ) {
                Ok(v) => v,
                Err(rej) => {
                    results.push((pr.name, Err(rej.message().to_string())));
                    continue;
                }
            };
            if is_del {
                match repo.refs_mut().delete(&target_name, old_hint.as_ref()) {
                    Ok(()) => {
                        results.push((pr.name, Ok(())));
                        applied_side_effects.push((target_name.clone(), old_hint, None));
                        success_cmds.push(ReceiveCommand {
                            old: old_hint.unwrap_or_else(zero_oid),
                            new: new_oid,
                            name: target_name,
                        });
                    }
                    Err(e) => results.push((pr.name, Err(e.to_string()))),
                }
            } else {
                match repo
                    .refs_mut()
                    .update(&target_name, &new_oid, old_hint.as_ref())
                {
                    Ok(()) => {
                        if should_update_worktree {
                            if let Err(rej) = crate::ref_gate::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(&target_name, prev, Some(&new_oid));
                                } else {
                                    let _ = repo.refs_mut().delete(&target_name, Some(&new_oid));
                                }
                                results.push((pr.name, Err(rej.message().to_string())));
                                continue;
                            }
                        }
                        results.push((pr.name, Ok(())));
                        applied_side_effects.push((target_name.clone(), old_hint, Some(new_oid)));
                        success_cmds.push(ReceiveCommand {
                            old: old_hint.unwrap_or_else(zero_oid),
                            new: new_oid,
                            name: target_name,
                        });
                    }
                    Err(e) => results.push((pr.name, Err(e.to_string()))),
                }
            }
        }
    }

    if !success_cmds.is_empty() {
        let post_stdin = hook_stdin_lines_refs(success_cmds.iter());
        run_post_receive(repo.git_dir(), &post_stdin, &hook_env);
        let names: Vec<&str> = success_cmds.iter().map(|c| c.name.as_str()).collect();
        run_post_update(repo.git_dir(), &names, &hook_env);
        crate::ref_gate::post_receive_locked_effects(repo, &applied_side_effects, true);
    }

    drop(gate_lock);

    if !success_cmds.is_empty() {
        crate::ref_gate::post_receive_external_effects(repo, &applied_side_effects, true);
    }

    encode_report_status_owned("ok", &results)
}

fn check_branch_protection_rules(
    repo: &Repository,
    _store: &crate::web_ui::store::ForgeStore,
    refname: &str,
    old: Option<Oid>,
    new_oid: Option<Oid>,
) -> Result<(), String> {
    let Some(branch) = refname.strip_prefix("refs/heads/") else {
        return Ok(());
    };
    match new_oid {
        None => {
            if crate::web_ui::is_branch_delete_protected(repo, branch) {
                return Err("branch deletion blocked by branch protection rule".into());
            }
        }
        Some(new_target) => {
            if let Some(old_oid) = old {
                if old_oid != new_target
                    && crate::web_ui::is_force_push_blocked(repo.common_dir(), branch)
                    && !is_commit_ancestor(repo, old_oid, new_target)
                {
                    return Err("force push blocked by branch protection rule".into());
                }
            }
        }
    }
    Ok(())
}

/// Quarantine object dir under `$GIT_DIR/objects` (git-receive-pack).
struct Quarantine {
    path: PathBuf,
}

impl Quarantine {
    fn create(git_dir: &Path) -> Result<Self, ServerError> {
        let objects = git_dir.join("objects");
        fs::create_dir_all(&objects)?;
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        let path = objects.join(format!("incoming-{nanos}-{}", std::process::id()));
        fs::create_dir_all(&path)?;
        Ok(Self { path })
    }

    fn discard(self) {
        let _ = fs::remove_dir_all(&self.path);
    }

    fn migrate_into(self, repo: &mut Repository) -> Result<(), String> {
        // Walk quarantine loose objects and put into the main store.
        let Ok(entries) = fs::read_dir(&self.path) else {
            let _ = fs::remove_dir_all(&self.path);
            return Ok(());
        };
        for entry in entries.flatten() {
            let name = entry.file_name();
            let name = name.to_string_lossy();
            if name.len() != 2 {
                continue;
            }
            let fanout = entry.path();
            let Ok(objs) = fs::read_dir(&fanout) else {
                continue;
            };
            for obj in objs.flatten() {
                let fname = obj.file_name();
                let rest = fname.to_string_lossy();
                let hex = format!("{name}{rest}");
                let Ok(oid) = Oid::from_hex(&hex) else {
                    continue;
                };
                // Read via a store rooted at quarantine so packed/overlay stays honest.
                let qstore = FilesystemGitStore::open(&self.path);
                match qstore.get(&oid) {
                    Ok(raw) => {
                        let format = repo.object_format();
                        repo.store_mut()
                            .put(format, &raw)
                            .map_err(|e| e.to_string())?;
                    }
                    Err(_) => continue,
                }
            }
        }
        let _ = fs::remove_dir_all(&self.path);
        Ok(())
    }
}

fn is_delete(cmd: &ReceiveCommand) -> bool {
    cmd.new.as_bytes().iter().all(|b| *b == 0)
}

fn zero_oid() -> Oid {
    Oid::from_hex("0000000000000000000000000000000000000000").expect("zero oid")
}

fn hook_stdin_lines(commands: &[ReceiveCommand]) -> Vec<u8> {
    hook_stdin_lines_refs(commands.iter())
}

fn hook_stdin_lines_refs<'a, I>(commands: I) -> Vec<u8>
where
    I: IntoIterator<Item = &'a ReceiveCommand>,
{
    let mut out = Vec::new();
    for cmd in commands {
        out.extend(format!("{} {} {}\n", cmd.old.to_hex(), cmd.new.to_hex(), cmd.name).as_bytes());
    }
    out
}

#[derive(Debug, Clone)]
struct ReceiveCommand {
    old: Oid,
    new: Oid,
    name: String,
}

type SplitCommands = (Vec<ReceiveCommand>, Vec<String>, Vec<u8>);

fn split_commands(body: &[u8]) -> Result<SplitCommands, ServerError> {
    let mut offset = 0;
    let mut commands = Vec::new();
    let mut saw_push_options_cap = false;
    while offset < body.len() {
        let (packet, n) =
            decode_packet(&body[offset..]).map_err(|e| ServerError::Protocol(e.to_string()))?;
        offset += n;
        match packet {
            Packet::Flush => break,
            Packet::Data(payload) => {
                let owned = if let Some(nul) = payload.iter().position(|b| *b == 0) {
                    let text = std::str::from_utf8(&payload[..nul])
                        .map_err(|_| ServerError::Protocol("command not utf-8".into()))?
                        .to_string();
                    let caps = std::str::from_utf8(&payload[nul + 1..]).unwrap_or("");
                    if caps.split_whitespace().any(|c| c == "push-options") {
                        saw_push_options_cap = true;
                    }
                    text
                } else {
                    decode_text_line(&payload).map_err(|e| ServerError::Protocol(e.to_string()))?
                };
                let text = owned.trim_end_matches('\n');
                let mut parts = text.splitn(3, ' ');
                let old_hex = parts
                    .next()
                    .ok_or_else(|| ServerError::Protocol("bad command".into()))?;
                let new_hex = parts
                    .next()
                    .ok_or_else(|| ServerError::Protocol("bad command".into()))?;
                let name = parts
                    .next()
                    .ok_or_else(|| ServerError::Protocol("bad command".into()))?;
                // Capability list may trail the first command after a NUL already handled;
                // also accept space-separated caps after the refname on some peers.
                if name.contains("push-options") || text.contains(" push-options") {
                    saw_push_options_cap = true;
                }
                let refname = name.split('\0').next().unwrap_or(name).to_string();
                commands.push(ReceiveCommand {
                    old: Oid::from_hex(old_hex)
                        .map_err(|e| ServerError::Protocol(e.to_string()))?,
                    new: Oid::from_hex(new_hex)
                        .map_err(|e| ServerError::Protocol(e.to_string()))?,
                    name: refname,
                });
            }
            _ => {}
        }
    }
    let mut push_options = Vec::new();
    if saw_push_options_cap {
        while offset < body.len() {
            if body[offset..].starts_with(b"PACK") {
                break;
            }
            let (packet, n) =
                decode_packet(&body[offset..]).map_err(|e| ServerError::Protocol(e.to_string()))?;
            offset += n;
            match packet {
                Packet::Flush => break,
                Packet::Data(payload) => {
                    let line = decode_text_line(&payload)
                        .map_err(|e| ServerError::Protocol(e.to_string()))?;
                    let line = line.trim_end_matches('\n');
                    if let Some(rest) = line.strip_prefix("push-option ") {
                        push_options.push(rest.to_string());
                    } else if line == "push-option" {
                        push_options.push(String::new());
                    } else {
                        return Err(ServerError::Protocol(format!(
                            "expected push-option line, got {line}"
                        )));
                    }
                }
                _ => {}
            }
        }
    }
    Ok((commands, push_options, body[offset..].to_vec()))
}

fn encode_report_status_owned(
    unpack: &str,
    refs: &[(String, Result<(), String>)],
) -> Result<Vec<u8>, ServerError> {
    let borrowed: Vec<(&str, Result<(), &str>)> = refs
        .iter()
        .map(|(n, r)| {
            (
                n.as_str(),
                match r {
                    Ok(()) => Ok(()),
                    Err(e) => Err(e.as_str()),
                },
            )
        })
        .collect();
    encode_report_status(unpack, &borrowed)
}

fn encode_report_status(
    unpack: &str,
    refs: &[(&str, Result<(), &str>)],
) -> Result<Vec<u8>, ServerError> {
    // Classic unpack/ok/ng lines are valid report-status and report-status-v2
    // when no proc-receive rewrite options are needed.
    let mut out = Vec::new();
    out.extend(text_pkt(&format!("unpack {unpack}"))?);
    for (name, result) in refs {
        match result {
            Ok(()) => out.extend(text_pkt(&format!("ok {name}"))?),
            Err(err) => out.extend(text_pkt(&format!("ng {name} {err}"))?),
        }
    }
    out.extend(encode_packet(&Packet::Flush).map_err(|e| ServerError::Protocol(e.to_string()))?);
    Ok(out)
}

fn text_pkt(text: &str) -> Result<Vec<u8>, ServerError> {
    let mut payload = text.as_bytes().to_vec();
    if !payload.ends_with(b"\n") {
        payload.push(b'\n');
    }
    encode_packet(&Packet::Data(payload)).map_err(|e| ServerError::Protocol(e.to_string()))
}

fn is_commit_ancestor(repo: &Repository, ancestor: Oid, descendant: Oid) -> bool {
    if ancestor == descendant {
        return true;
    }
    let mut queue = std::collections::VecDeque::new();
    let mut visited = std::collections::HashSet::new();
    queue.push_back(descendant);
    visited.insert(descendant);
    let mut steps = 0usize;
    while let Some(cur) = queue.pop_front() {
        steps += 1;
        if steps > 4096 {
            break;
        }
        let Ok(obj) = repo.get_object(&cur) else {
            continue;
        };
        if obj.kind != arks_object::ObjectKind::Commit {
            continue;
        }
        let Ok(commit) = arks_object::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
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::web_ui::allow_loopback_webhooks_for_repo;
    use crate::web_ui::store::{ForgeStore, WebhookRecord};
    use arks_object::{Commit, ObjectKind, RawObject, Signature, Tree, TreeEntry, TreeMode};
    use tempfile::TempDir;

    fn make_commit(
        repo: &mut Repository,
        parents: Vec<Oid>,
        files: &[(&str, &[u8])],
        msg: &str,
    ) -> 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(),
        };
        repo.store_mut()
            .put(
                fmt,
                &RawObject::new(ObjectKind::Commit, commit.encode().unwrap()),
            )
            .unwrap()
    }

    fn init_bare(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, config: &str) -> (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"), config).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)
    }

    fn make_receive_body(old: Oid, new: Oid, refname: &str) -> Vec<u8> {
        let mut body = Vec::new();
        let line = format!(
            "{} {} {}\0report-status\n",
            old.to_hex(),
            new.to_hex(),
            refname
        );
        body.extend(encode_packet(&Packet::Data(line.into_bytes())).unwrap());
        body.extend(encode_packet(&Packet::Flush).unwrap());
        body
    }

    #[test]
    fn receive_pack_propagates_update_instead_worktree_sync_error_and_rolls_back() {
        let tmp = TempDir::new().unwrap();
        let (mut repo, c1) = init_non_bare(
            tmp.path(),
            "[core]\n\tbare = false\n[receive]\n\tdenyCurrentBranch = updateInstead\n",
        );
        let c2 = make_commit(&mut repo, vec![c1], &[("a.txt", b"v2\n")], "v2\n");

        // Pre-create `.git/index.lock` so `sync_worktree_for_update_instead` fails on index write.
        fs::write(repo.git_dir().join("index.lock"), b"locked\n").unwrap();

        let body = make_receive_body(c1, c2, "refs/heads/main");
        let report_bytes = receive_pack(&mut repo, &body).unwrap();
        let report = String::from_utf8_lossy(&report_bytes);
        assert!(
            report.contains("ng refs/heads/main "),
            "worktree sync failure must report ng instead of swallowing error: {report}"
        );
        assert!(
            !report.contains("ok refs/heads/main"),
            "failed worktree sync must not report ok: {report}"
        );
        assert_eq!(
            repo.refs().resolve("refs/heads/main").unwrap(),
            c1,
            "ref update must roll back when updateInstead worktree/index sync fails"
        );
    }

    #[test]
    fn receive_pack_drops_ref_gate_lock_before_webhook_dispatch() {
        use std::io::{Read as _, Write as _};
        use std::net::TcpListener;

        let tmp = TempDir::new().unwrap();
        let (mut repo, c1) = init_bare(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("arks-ref-gate.lock");

        let srv = std::thread::spawn(move || {
            let (mut stream, _) = listener.accept().unwrap();
            let _ = stream.set_read_timeout(Some(std::time::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();
            let acquired_in_webhook =
                crate::ref_gate::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_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 body = make_receive_body(c1, c2, "refs/heads/main");
        let report_bytes = receive_pack(&mut repo, &body).unwrap();
        let report = String::from_utf8_lossy(&report_bytes);
        assert!(report.contains("ok refs/heads/main"), "report={report}");

        let (lock_file_absent, acquired_in_webhook) = srv.join().unwrap();
        assert!(
            lock_file_absent,
            "ref gate lockfile must be removed before webhook dispatch"
        );
        assert!(
            acquired_in_webhook,
            "RefGateGuard must be dropped before 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);
    }

    #[cfg(unix)]
    fn write_proc_receive_hook(git_dir: &Path, response_lines: &[&str]) {
        use std::os::unix::fs::PermissionsExt;
        let hooks_dir = git_dir.join("hooks");
        fs::create_dir_all(&hooks_dir).unwrap();
        let mut pkt_out = Vec::new();
        pkt_out.extend(encode_packet(&Packet::Data(b"version=0\n".to_vec())).unwrap());
        pkt_out.extend(encode_packet(&Packet::Flush).unwrap());
        for line in response_lines {
            let mut payload = line.as_bytes().to_vec();
            payload.push(b'\n');
            pkt_out.extend(encode_packet(&Packet::Data(payload)).unwrap());
        }
        pkt_out.extend(encode_packet(&Packet::Flush).unwrap());
        let resp_file = hooks_dir.join("proc-receive.out");
        fs::write(&resp_file, &pkt_out).unwrap();
        let hook = hooks_dir.join("proc-receive");
        let script = format!("#!/bin/sh\ncat >/dev/null\ncat '{}'\n", resp_file.display());
        fs::write(&hook, script).unwrap();
        fs::set_permissions(&hook, fs::Permissions::from_mode(0o755)).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn proc_receive_enforces_refname_branch_rules_and_non_bare_checks() {
        use crate::web_ui::store::BranchRule;

        // 1. Bare repo: invalid target refname + branch protection rules (delete, force-push, attestation).
        let tmp_bare = TempDir::new().unwrap();
        let (mut bare_repo, c1) = init_bare(tmp_bare.path());
        fs::write(
            bare_repo.git_dir().join("config"),
            b"[core]\n\tbare = true\n[receive]\n\tprocReceiveRefs = refs/for/\n",
        )
        .unwrap();
        let c2 = make_commit(&mut bare_repo, vec![c1], &[("a.txt", b"v2\n")], "v2\n");
        let c_div = make_commit(&mut bare_repo, Vec::new(), &[("a.txt", b"div\n")], "div\n");

        // Invalid rewritten refname (`..`) rejected.
        write_proc_receive_hook(
            bare_repo.git_dir(),
            &[
                "ok refs/for/main",
                "option refname refs/heads/../escape",
                &format!("option new-oid {}", c2.to_hex()),
            ],
        );
        let rep_invalid = String::from_utf8_lossy(
            &receive_pack(
                &mut bare_repo,
                &make_receive_body(zero_oid(), c2, "refs/for/main"),
            )
            .unwrap(),
        )
        .into_owned();
        assert!(
            rep_invalid.contains("ng refs/for/main invalid ref name"),
            "invalid proc-receive refname must be rejected: {rep_invalid}"
        );

        // Configure branch protection on `main`.
        ForgeStore::update(bare_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();

        // Protected delete rejected.
        write_proc_receive_hook(
            bare_repo.git_dir(),
            &[
                "ok refs/for/main",
                "option refname refs/heads/main",
                &format!("option new-oid {}", zero_oid().to_hex()),
            ],
        );
        let rep_del = String::from_utf8_lossy(
            &receive_pack(
                &mut bare_repo,
                &make_receive_body(zero_oid(), c2, "refs/for/main"),
            )
            .unwrap(),
        )
        .into_owned();
        assert!(
            rep_del.contains("ng refs/for/main branch deletion blocked"),
            "proc-receive delete of protected branch must be blocked: {rep_del}"
        );
        assert_eq!(bare_repo.refs().resolve("refs/heads/main").unwrap(), c1);

        // Protected force-push rejected.
        write_proc_receive_hook(
            bare_repo.git_dir(),
            &[
                "ok refs/for/main",
                "option refname refs/heads/main",
                &format!("option new-oid {}", c_div.to_hex()),
            ],
        );
        let rep_force = String::from_utf8_lossy(
            &receive_pack(
                &mut bare_repo,
                &make_receive_body(zero_oid(), c_div, "refs/for/main"),
            )
            .unwrap(),
        )
        .into_owned();
        assert!(
            rep_force.contains("ng refs/for/main force push blocked"),
            "proc-receive force-push to protected branch must be blocked: {rep_force}"
        );
        assert_eq!(bare_repo.refs().resolve("refs/heads/main").unwrap(), c1);

        // 2. Non-bare repo: denyCurrentBranch=refuse + updateInstead sync failure rollback.
        let tmp_nb = TempDir::new().unwrap();
        let (mut nb_repo, nb_c1) = init_non_bare(
            tmp_nb.path(),
            "[core]\n\tbare = false\n[receive]\n\tprocReceiveRefs = refs/for/\n\tdenyCurrentBranch = refuse\n",
        );
        let nb_c2 = make_commit(&mut nb_repo, vec![nb_c1], &[("a.txt", b"v2\n")], "v2\n");
        write_proc_receive_hook(
            nb_repo.git_dir(),
            &[
                "ok refs/for/main",
                "option refname refs/heads/main",
                &format!("option new-oid {}", nb_c2.to_hex()),
            ],
        );
        let rep_nb_refuse = String::from_utf8_lossy(
            &receive_pack(
                &mut nb_repo,
                &make_receive_body(zero_oid(), nb_c2, "refs/for/main"),
            )
            .unwrap(),
        )
        .into_owned();
        assert!(
            rep_nb_refuse.contains("ng refs/for/main refusing to update checked-out branch"),
            "proc-receive to checked-out branch must be refused: {rep_nb_refuse}"
        );
        assert_eq!(nb_repo.refs().resolve("refs/heads/main").unwrap(), nb_c1);

        // With updateInstead and a locked index, worktree sync failure must report ng and roll back.
        fs::write(
            nb_repo.git_dir().join("config"),
            b"[core]\n\tbare = false\n[receive]\n\tprocReceiveRefs = refs/for/\n\tdenyCurrentBranch = updateInstead\n",
        )
        .unwrap();
        fs::write(nb_repo.git_dir().join("index.lock"), b"locked\n").unwrap();
        let rep_nb_sync = String::from_utf8_lossy(
            &receive_pack(
                &mut nb_repo,
                &make_receive_body(zero_oid(), nb_c2, "refs/for/main"),
            )
            .unwrap(),
        )
        .into_owned();
        assert!(
            rep_nb_sync.contains("ng refs/for/main "),
            "proc-receive worktree sync error must be propagated: {rep_nb_sync}"
        );
        assert_eq!(nb_repo.refs().resolve("refs/heads/main").unwrap(), nb_c1);
    }

    #[test]
    fn receive_pack_unpacks_thin_pack_against_existing_repo_objects() {
        use flate2::{Compression, write::ZlibEncoder};
        use std::io::Write;

        let tmp = TempDir::new().unwrap();
        let bare_path = crate::init_bare_repo(tmp.path(), "thin", "").unwrap();
        let mut repo = Repository::open(&bare_path).unwrap();
        let fmt = repo.object_format();

        let base_bytes = b"hello thin pack base content line 1\nline 2\n".to_vec();
        let base_blob_oid = repo
            .store_mut()
            .put(fmt, &RawObject::new(ObjectKind::Blob, base_bytes.clone()))
            .unwrap();
        let c1_tree = repo
            .store_mut()
            .put(
                fmt,
                &RawObject::new(
                    ObjectKind::Tree,
                    Tree {
                        entries: vec![TreeEntry {
                            mode: TreeMode::File,
                            name: "a.txt".into(),
                            oid: base_blob_oid,
                        }],
                    }
                    .encode()
                    .unwrap(),
                ),
            )
            .unwrap();
        let sig = Signature {
            name: "Thin Tester".into(),
            email: "test@example.invalid".into(),
            timestamp: 1_700_000_000,
            timezone: "+0000".into(),
        };
        let c1 = repo
            .store_mut()
            .put(
                fmt,
                &RawObject::new(
                    ObjectKind::Commit,
                    Commit {
                        tree: c1_tree,
                        parents: vec![],
                        author: sig.clone(),
                        committer: sig.clone(),
                        gpgsig: None,
                        message: "base\n".into(),
                    }
                    .encode()
                    .unwrap(),
                ),
            )
            .unwrap();
        repo.refs_mut()
            .update("refs/heads/main", &c1, None)
            .unwrap();

        // Build c2 whose blob is sent ONLY as a thin OBJ_REF_DELTA against `base_blob_oid`!
        let new_bytes = b"hello thin pack base content line 1\nline 2 updated!\n".to_vec();
        let new_blob_raw = RawObject::new(ObjectKind::Blob, new_bytes.clone());
        let new_blob_oid = new_blob_raw.oid(fmt).unwrap();
        let c2_tree_raw = RawObject::new(
            ObjectKind::Tree,
            Tree {
                entries: vec![TreeEntry {
                    mode: TreeMode::File,
                    name: "a.txt".into(),
                    oid: new_blob_oid,
                }],
            }
            .encode()
            .unwrap(),
        );
        let c2_tree_oid = c2_tree_raw.oid(fmt).unwrap();
        let c2_raw = RawObject::new(
            ObjectKind::Commit,
            Commit {
                tree: c2_tree_oid,
                parents: vec![c1],
                author: sig.clone(),
                committer: sig,
                gpgsig: None,
                message: "thin delta update\n".into(),
            }
            .encode()
            .unwrap(),
        );
        let c2 = c2_raw.oid(fmt).unwrap();

        let delta = arks_pack::create_delta(&base_bytes, &new_bytes, 4096).unwrap();

        let push_hdr = |buf: &mut Vec<u8>, ty: u8, mut sz: usize| {
            let mut b = ((ty & 0x07) << 4) | ((sz & 0x0f) as u8);
            sz >>= 4;
            while sz > 0 {
                buf.push(b | 0x80);
                b = (sz & 0x7f) as u8;
                sz >>= 7;
            }
            buf.push(b);
        };
        let zlib_of = |data: &[u8]| -> Vec<u8> {
            let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
            enc.write_all(data).unwrap();
            enc.finish().unwrap()
        };

        let mut pack = Vec::new();
        pack.extend_from_slice(b"PACK");
        pack.extend_from_slice(&2u32.to_be_bytes());
        pack.extend_from_slice(&3u32.to_be_bytes());
        // 1) OBJ_REF_DELTA (type 7) referencing `base_blob_oid` already in repo ODB
        push_hdr(&mut pack, 7, delta.len());
        pack.extend_from_slice(base_blob_oid.as_bytes());
        pack.extend_from_slice(&zlib_of(&delta));
        // 2) OBJ_TREE (type 2)
        push_hdr(&mut pack, 2, c2_tree_raw.payload.len());
        pack.extend_from_slice(&zlib_of(&c2_tree_raw.payload));
        // 3) OBJ_COMMIT (type 1)
        push_hdr(&mut pack, 1, c2_raw.payload.len());
        pack.extend_from_slice(&zlib_of(&c2_raw.payload));
        arks_pack::trailer(&mut pack, fmt);

        let mut body = make_receive_body(c1, c2, "refs/heads/main");
        body.extend_from_slice(&pack);

        let reply = String::from_utf8_lossy(&receive_pack(&mut repo, &body).unwrap()).into_owned();
        assert!(
            reply.contains("unpack ok"),
            "thin pack unpack must succeed against existing repo objects: {reply}"
        );
        assert!(
            reply.contains("ok refs/heads/main"),
            "ref update after thin pack unpack must succeed: {reply}"
        );
        assert_eq!(repo.refs().resolve("refs/heads/main").unwrap(), c2);
        assert_eq!(repo.get_object(&new_blob_oid).unwrap().payload, new_bytes);
    }
}