oakvcs-core 0.114.0

Core version-control primitives for Oak: BLAKE3 content hashing, content-defined chunking, diff/merge, the Blob/Manifest/Commit/Tree data model, and the client-side local repository (SQLite + git backends).
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
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
//! Wire protocol types for the Oak push/pull/clone sync protocol.
//!
//! These are the request/response DTOs exchanged over HTTP between an Oak
//! client (the `oak` CLI) and an Oak server. They are the **single source of
//! truth** for the wire format, shared by every party that speaks it:
//!
//!   * the `oak` CLI (client), and
//!   * the hosted `oak-server` (the oak.space product).
//!
//! Keeping them here — rather than copied into each crate — means the
//! implementations cannot silently drift apart, which is the failure mode this
//! module exists to prevent.
//!
//! ## Rules for editing
//!
//! 1. **Every type derives both `Serialize` and `Deserialize`.** A given party
//!    only ever serializes one direction (the client serializes requests and
//!    deserializes responses; a server does the reverse), but because the
//!    parties live in different crates we derive both on everything so each can
//!    use a type in whichever direction it needs.
//! 2. **Preserve the serde attributes exactly.** `#[serde(default)]` and
//!    `skip_serializing_if` encode forward/backward compatibility with older
//!    clients and servers (the comments note which fields older peers omit).
//!    Changing them breaks wire compatibility with already-deployed CLIs.
//! 3. **These DTOs are distinct from the domain model** (`Blob`, `Commit`,
//!    `Tree`, …). Don't merge them — they serialize differently. The
//!    [`tree_data_to_core`] / [`tree_to_wire`] helpers convert between the two.

use serde::{Deserialize, Deserializer, Serialize};

use crate::{
    hash_bytes, ChangeType, Commit, FileChange, FileMode, Hash, Tree, TreeEntry, TreeEntryKind,
};

pub const STAGED_ENVELOPE_MAX_COMMITS: usize = 500;
pub const STAGED_OPERATION_MAX_COMMITS: usize = 100_000;
pub const STAGED_MAX_TREE_OBJECTS: usize = 100_000;
pub const STAGED_MAX_DIRECT_TREE_ENTRIES: usize = 1_000_000;
pub const STAGED_MAX_RESOLVED_MANIFEST_ENTRIES: usize = 1_000_000;
pub const STAGED_MAX_FILE_CHANGES: usize = 250_000;
pub const STAGED_MAX_CANONICAL_METADATA_BYTES: usize = 64 * 1024 * 1024;
pub const STAGED_MAX_EXPANDED_PATH_BYTES: usize = 64 * 1024 * 1024;
pub const STAGED_MAX_CHUNK_REFS: usize = 1_000_000;
pub const STAGED_MAX_BLOBS: usize = 50_000;
pub const STAGED_MAX_DECLARED_BLOB_BYTES: u64 = 25 * 1024 * 1024 * 1024;
/// Additive bounded-window admission; old staged-v1 keeps its original totals.
pub const STAGED_WINDOW_BUDGET_PROTOCOL: &str = "window_v1";
pub const STAGED_WINDOW_MAX_RESOLVED_MANIFEST_ENTRIES: usize = 16_000_000;
pub const STAGED_WINDOW_MAX_BLOBS: usize = 250_000;
pub const STAGED_ABORT_PROTOCOL: &str = "v1";
pub const KNOWN_LOSS_PROTOCOL: &str = "report_v1";
/// `retention_protocol=expired_v1`: the client accepts `missing_content`
/// entries with reason [`RETENTION_EXPIRED_REASON`] — historical file versions
/// whose content the server's retention rules expired. Servers without
/// retention ignore the parameter.
pub const RETENTION_PROTOCOL: &str = "expired_v1";
/// `missing_content[].reason_code` for content operator adjudication declared
/// permanently unavailable.
pub const OPERATOR_LOSS_REASON: &str = "operator_adjudicated_loss";
/// `missing_content[].reason_code` for content a retention rule expired.
pub const RETENTION_EXPIRED_REASON: &str = "retention_expired";
pub const MAPPING_PROOF_PROTOCOL: &str = "async_v1";
pub const ORDINARY_BOOTSTRAP_PROTOCOL: &str = "headless_preload_v1";
pub const MAPPING_PROOF_MAX_BLOBS: usize = 128;
pub const MAPPING_PROOF_MAX_SET_CHUNK_REFS: usize = 131_072;
pub const MAPPING_PROOF_MAX_BLOB_CHUNK_REFS: usize = 131_072;
pub const MAPPING_PROOF_MAX_SET_BYTES: u64 = 25 * 1024 * 1024 * 1024;
pub const MAPPING_PROOF_MAX_BLOB_BYTES: u64 = 25 * 1024 * 1024 * 1024;
pub const MAPPING_PROOF_MAX_CHUNK_BYTES: u64 = 64 * 1024 * 1024;
pub const MAPPING_PROOF_PAGE_CHUNK_REFS: usize = 10_000;
pub const MAPPING_PROOF_PAGE_BODY_BYTES: usize = 2 * 1024 * 1024;
pub const MAPPING_PROOF_GENERATION_CONFLICT: &str = "mapping_generation_conflict";

pub fn staged_branch_metadata_bytes(branch: &BranchPushData) -> usize {
    branch
        .name
        .len()
        .saturating_add(branch.description.as_ref().map_or(0, String::len))
        .saturating_add(branch.parent_branch.as_ref().map_or(0, String::len))
        .saturating_add(branch.created_at.len())
        .saturating_add(branch.status.len())
        .saturating_add(branch.close_reason.as_ref().map_or(0, String::len))
}

pub fn staged_commit_metadata_bytes(commit: &CommitData) -> usize {
    commit
        .hash
        .len()
        .saturating_add(commit.branch_name.len())
        .saturating_add(commit.manifest_hash.len())
        .saturating_add(commit.author.len())
        .saturating_add(commit.message.as_ref().map_or(0, String::len))
        .saturating_add(commit.files.iter().fold(0usize, |total, file| {
            total
                .saturating_add(file.path.len())
                .saturating_add(file.old_path.as_ref().map_or(0, String::len))
                .saturating_add(160)
        }))
}

pub fn staged_tree_metadata_bytes(tree: &TreeData) -> usize {
    tree.entries.iter().fold(0usize, |total, entry| {
        total
            .saturating_add(entry.name.len())
            .saturating_add(entry.hash.len())
            .saturating_add(16)
    })
}

// ---------------------------------------------------------------------------
// Repository metadata
// ---------------------------------------------------------------------------

/// Repository info response.
#[derive(Serialize, Deserialize)]
pub struct RepoResponse {
    pub name: String,
    pub description: Option<String>,
    pub head: Option<String>,
    pub is_public: bool,
    pub owner: Option<String>,
    pub emoji: Option<String>,
    pub updated_at: Option<String>,
}

/// List of repositories response.
#[derive(Serialize, Deserialize)]
pub struct RepoListResponse {
    pub repos: Vec<RepoResponse>,
}

/// Create repository request.
#[derive(Serialize, Deserialize)]
pub struct CreateRepoRequest {
    pub name: String,
    pub description: Option<String>,
    #[serde(default)]
    pub is_public: bool,
    /// Slug of the organization to create the repo under. When provided, the repo
    /// is owned by the organization and the caller must have write access to it.
    /// Mutually exclusive with personal ownership — if omitted, the repo is
    /// owned by the authenticated user. (Ignored by org-less servers.)
    #[serde(default)]
    pub organization_slug: Option<String>,
}

// ---------------------------------------------------------------------------
// Shared object carriers
// ---------------------------------------------------------------------------

/// Commit data for transfer.
#[derive(Serialize, Deserialize, Clone)]
pub struct CommitData {
    pub hash: String,
    pub branch_name: String,
    pub parent_hash: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub merge_parent_hash: Option<String>,
    pub manifest_hash: String,
    pub author: String,
    /// Nullable on the wire: only present for main-branch squash-merge
    /// commits, where it's the merged branch's description. Every other
    /// commit has `None` here.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    pub timestamp: String,
    pub files: Vec<FileChangeData>,
}

/// File change data.
#[derive(Serialize, Deserialize, Clone)]
pub struct FileChangeData {
    pub path: String,
    pub change_type: String,
    pub old_blob_hash: Option<String>,
    pub new_blob_hash: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub old_path: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub old_mode: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub new_mode: Option<String>,
}

/// Chunk reference for chunked blob transfer.
#[derive(Serialize, Deserialize, Clone)]
pub struct ChunkRefData {
    pub hash: String,
    pub offset: u64,
    pub size: u32,
}

/// Blob data for transfer.
#[derive(Serialize, Deserialize, Clone)]
pub struct BlobData {
    pub hash: String,
    pub content: Vec<u8>,
    pub size: u64,
    /// Chunk metadata for large/chunked blobs (empty for small blobs).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub chunks: Vec<ChunkRefData>,
    /// Opaque proof identity for the exact inactive mapping generation this
    /// staged blob is asking the server to activate. Ordinary/legacy blobs
    /// omit it, so deployed readers remain wire-compatible.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mapping_proof_token: Option<String>,
}

/// Tree object for wire transfer. One row per directory; entries are the
/// tree's direct children (sub-trees + blobs). The receiver stores via
/// `store_tree`, which computes the hash and persists the entries.
#[derive(Serialize, Deserialize, Clone)]
pub struct TreeData {
    pub hash: String,
    pub entries: Vec<TreeEntryData>,
}

#[derive(Serialize, Deserialize, Clone)]
pub struct TreeEntryData {
    pub name: String,
    /// "tree" or "blob".
    pub kind: String,
    /// Hash of the child tree (when kind=="tree") or blob (when kind=="blob").
    pub hash: String,
    /// "regular" | "executable" | "symlink" for blobs; "tree" for trees.
    pub mode: String,
}

// ---------------------------------------------------------------------------
// Push
// ---------------------------------------------------------------------------

/// Push request.
#[derive(Serialize, Deserialize)]
pub struct PushRequest {
    pub expected_head: Option<String>,
    /// The client's last-known head for the branch being pushed. When set,
    /// the server uses this for conflict detection on the branch (instead of
    /// or in addition to the global `expected_head`). Older clients omit
    /// this field; the server falls back to the legacy global-head check.
    #[serde(default)]
    pub expected_branch_head: Option<String>,
    #[serde(default)]
    pub force: bool,
    pub branch: Option<BranchPushData>,
    pub commits: Vec<CommitData>,
    pub blobs: Vec<BlobData>,
    /// Tree objects reachable from each commit's root tree. Replaces the
    /// pre-trees `manifests` field. Sent in arbitrary order — no FK between
    /// trees, so the server can store them as a batch.
    #[serde(default)]
    pub trees: Vec<TreeData>,
}

/// Versioned staged-push request. It intentionally has a distinct endpoint
/// and DTO so a mixed deployment can never send "do not advance" semantics
/// to an old `/push` handler that ignores unknown fields and moves a head.
#[derive(Serialize, Deserialize)]
pub struct StagedPushRequest {
    /// Opaque operation-scoped session identifier. Every batch and the final
    /// CAS for one logical push must reuse the same value.
    pub stage_id: String,
    /// Exact branch head observed by the whole-operation planner. This field
    /// is required on the wire; JSON null explicitly means "expect no head".
    #[serde(deserialize_with = "deserialize_required_optional_string")]
    pub expected_branch_head: Option<String>,
    pub branch: BranchPushData,
    /// False publishes a fully validated immutable closure without visible
    /// branch metadata/head changes. True performs the final atomic CAS.
    pub finalize: bool,
    /// Permit a deliberate non-descendant branch target. This never bypasses
    /// the expected-head CAS, stage ownership, or closure/receipt validation.
    #[serde(default)]
    pub force: bool,
    /// Required for finalization and forbidden for staging.
    pub target_head: Option<String>,
    pub commits: Vec<CommitData>,
    pub blobs: Vec<BlobData>,
    #[serde(default)]
    pub trees: Vec<TreeData>,
}

/// Best-effort release of an unfinished staged operation. The path supplies
/// the opaque stage id; these fields bind the abort to the same immutable
/// branch boundary as every staged batch.
#[derive(Serialize, Deserialize)]
pub struct StagedAbortRequest {
    pub branch_name: String,
    #[serde(deserialize_with = "deserialize_required_optional_string")]
    pub expected_branch_head: Option<String>,
}

#[derive(Serialize, Deserialize)]
pub struct StagedAbortResponse {
    pub aborted: bool,
    pub state: String,
}

fn deserialize_required_optional_string<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
where
    D: Deserializer<'de>,
{
    Option::<String>::deserialize(deserializer)
}

/// Branch push data (branch-like container metadata).
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct BranchPushData {
    pub name: String,
    pub description: Option<String>,
    pub parent_branch: Option<String>,
    pub status: String,
    pub created_at: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub close_reason: Option<String>,
}

/// Push response.
#[derive(Serialize, Deserialize)]
pub struct PushResponse {
    pub success: bool,
    pub new_head: Option<String>,
    pub message: String,
    /// Present when the push was made from a view (`view_protocol=view_v1`):
    /// `new_head` is then the *view* head, and `view.commits` maps each
    /// pushed view commit to the full commit the server grafted it into.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub view: Option<ViewResponseData>,
}

// ---------------------------------------------------------------------------
// Pull
// ---------------------------------------------------------------------------

/// Pull query parameters.
#[derive(Serialize, Deserialize)]
pub struct PullQuery {
    pub since: Option<String>,
    pub branch_name: Option<String>,
    /// Force pull: skip conflict check and return all commits from remote HEAD.
    #[serde(default)]
    pub force: bool,
    /// Highest branch_renames.id the client has already applied. Server
    /// returns events with id > since_rename_id so the client can replay
    /// any renames performed by other clones since its last pull.
    #[serde(default)]
    pub since_rename_id: i64,
    /// Shallow-clone depth. When set (and no `branch_name` is given — i.e. the
    /// clone case), the server returns only the most recent `depth` commits on
    /// the default branch instead of the full reachable history. `oak clone`
    /// fetches the full history by default (no `depth`); `oak clone --shallow`
    /// sends `depth=1`. Ignored on branch-scoped pulls. A value of `0` is
    /// treated as "no limit" (same as unset).
    pub depth: Option<u32>,
    /// Explicit opt-in to structured operator-adjudicated known-loss reports.
    /// Omitted for legacy peers so adding the protocol does not change their
    /// pull behavior.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub known_loss_protocol: Option<String>,
    /// Explicit opt-in to retention-expired reports
    /// ([`RETENTION_PROTOCOL`]). Omitted for legacy peers.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub retention_protocol: Option<String>,
}

/// Branch pull data (branch-like container metadata).
#[derive(Serialize, Deserialize)]
pub struct BranchPullData {
    pub name: String,
    pub description: Option<String>,
    pub parent_branch: Option<String>,
    pub status: String,
    pub created_at: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub close_reason: Option<String>,
}

/// Branch rename event included in pull responses so other clones can
/// replay renames against their local repos. Ordered by `id` ASC.
#[derive(Serialize, Deserialize)]
pub struct BranchRenameData {
    pub id: i64,
    pub old_name: String,
    pub new_name: String,
    pub renamed_at: String,
}

/// Content deliberately omitted: an operator adjudicated legacy bytes as
/// permanently unavailable ([`OPERATOR_LOSS_REASON`], under
/// [`KNOWN_LOSS_PROTOCOL`]), or a retention rule expired a historical version
/// ([`RETENTION_EXPIRED_REASON`], only to clients that sent
/// [`RETENTION_PROTOCOL`]). This is distinct from access-restricted content and
/// from unexpected corruption, both of which retain their existing behavior.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct MissingContentData {
    pub kind: String,
    pub hash: String,
    pub reason_code: String,
}

/// Pull response.
#[derive(Serialize, Deserialize)]
pub struct PullResponse {
    pub head: Option<String>,
    pub branch: Option<BranchPullData>,
    pub branches: Vec<BranchPullData>,
    pub commits: Vec<CommitData>,
    pub blobs: Vec<BlobData>,
    /// Tree objects reachable from each returned commit's root tree.
    /// Replaces the pre-trees `manifests` field.
    pub trees: Vec<TreeData>,
    /// Rename events with id > the client's `since_rename_id`. Older
    /// servers omit this field; clients should default it to an empty
    /// list when missing.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub renames: Vec<BranchRenameData>,
    /// Blob hashes whose content was withheld from `blobs` because path-based
    /// permissions deny this caller. Distinguishes "an admin restricted this
    /// path" from "the server is missing data" so clients can skip the files
    /// with an access message instead of failing the pull as corrupt.
    /// Sparse-clone (out-of-cone) withholding is not listed — the client asked
    /// for that itself. Older servers omit the field.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub restricted_blobs: Vec<String>,
    /// Operator-adjudicated historical content that the server cannot return.
    /// Older servers omit the field; clients request this behavior explicitly
    /// through the versioned known-loss protocol.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub missing_content: Vec<MissingContentData>,
    /// The tag snapshot for clients that send `tags=v1`. Per-repo releases are
    /// gone, so current servers answer with an empty snapshot, which tells
    /// older CLIs to drop any tags they cached. Absent when not requested.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<TagData>>,
    /// Present when the server answered from a view. `commits` and `trees`
    /// are then view commits and pruned trees; older servers (and requests
    /// without `view_protocol`) omit it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub view: Option<ViewResponseData>,
}

/// Query value for `/pull?tags=` and the `release_protocol` capability.
pub const RELEASE_PROTOCOL_V1: &str = "v1";

/// One tag as `/pull?tags=v1` shipped it while per-repo releases existed.
/// Kept for wire compatibility; current servers send none.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct TagData {
    pub name: String,
    pub commit: String,
    #[serde(default)]
    pub title: Option<String>,
    #[serde(default)]
    pub notes: Option<String>,
    #[serde(default)]
    pub prerelease: bool,
    #[serde(default)]
    pub finalized: bool,
    #[serde(default)]
    pub created_by: String,
    pub created_at: String,
    #[serde(default)]
    pub published_at: Option<String>,
    #[serde(default)]
    pub revision: i64,
    #[serde(default)]
    pub assets: Vec<TagAssetData>,
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct TagAssetData {
    pub name: String,
    pub blob_hash: String,
    pub size: u64,
    #[serde(default = "default_asset_content_type")]
    pub content_type: String,
}

fn default_asset_content_type() -> String {
    "application/octet-stream".to_string()
}

// ---------------------------------------------------------------------------
// Views
// ---------------------------------------------------------------------------

/// View selection for `pull`, `commits/info` and `push`, sent as **query
/// parameters** (`?view_protocol=view_v1&view=...`) next to each endpoint's
/// own query or body. Keeping it out of the request bodies means servers and
/// clients that predate views build those DTOs unchanged, and a server that
/// ignores the parameters answers with full trees and no
/// [`ViewResponseData`] — which is how a client detects it.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ViewQuery {
    /// [`crate::view::VIEW_PROTOCOL`] to opt in.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub view_protocol: Option<String>,
    /// The requested view in [`crate::ViewSpec::to_canonical`] form.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub view: Option<String>,
}

impl ViewQuery {
    /// A `view_v1` request for `view`.
    pub fn new(view: Option<&crate::ViewSpec>) -> Self {
        ViewQuery {
            view_protocol: Some(crate::view::VIEW_PROTOCOL.to_string()),
            view: view.map(|v| v.to_canonical()),
        }
    }

    /// True when the request opts in to the view protocol this crate speaks.
    pub fn is_view_request(&self) -> bool {
        self.view_protocol.as_deref() == Some(crate::view::VIEW_PROTOCOL)
    }
}

/// One full commit and the view commit it maps to.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ViewCommitMapping {
    pub full_hash: String,
    pub view_hash: String,
}

/// What the server says about the view it answered from.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ViewResponseData {
    /// The view actually served, canonical form: the request intersected
    /// with what the caller may read. Clients persist this, not the request.
    pub effective_view: String,
    /// `ViewSpec::id` of `effective_view`.
    pub view_id: String,
    /// Mappings for the commits in this response (and, for push, the full
    /// commits the server created).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub commits: Vec<ViewCommitMapping>,
    /// How many requested prefixes were dropped or narrowed because the
    /// caller can't read them. Names are never listed.
    #[serde(default, skip_serializing_if = "is_zero")]
    pub excluded_by_permission: u32,
}

fn is_zero(value: &u32) -> bool {
    *value == 0
}

// ---------------------------------------------------------------------------
// Blob existence / metadata
// ---------------------------------------------------------------------------

#[derive(Serialize, Deserialize)]
pub struct BlobCheckRequest {
    pub hashes: Vec<String>,
    /// Require the server to omit mappings that do not already have durable,
    /// generation-matched blob and child-chunk receipts. This is a metadata
    /// predicate: it must not trigger object-store reads or consume live-proof
    /// quota. Older servers ignore this append-only field.
    #[serde(default, skip_serializing_if = "is_false")]
    pub require_verified_receipts: bool,
    /// Ask the server to physically read and content-hash every requested
    /// blob it reports as present. This expensive operation is reserved for
    /// explicit diagnosis/repair; routine push planning uses receipt metadata.
    /// Older servers ignore this append-only field, so explicit verifiers must
    /// require [`BlobCheckResponse::verified_content`].
    #[serde(default, skip_serializing_if = "is_false")]
    pub verify_content: bool,
}

#[derive(Serialize, Deserialize)]
pub struct BlobCheckResponse {
    /// Subset of the request's `hashes` the server does NOT have. The
    /// client should send only these in the push payload.
    pub missing: Vec<String>,
    /// True only when every requested hash omitted from `missing` was
    /// physically read and reproduced its declared content hash and size.
    /// Absent on legacy servers and therefore false/fail-closed.
    #[serde(default, skip_serializing_if = "is_false")]
    pub verified_content: bool,
    /// Acknowledge that the server applied the request's strict durable
    /// receipt predicate. Clients require this on strict requests so a mixed
    /// deployment cannot silently route them to an older replica that ignored
    /// the append-only request field.
    #[serde(default, skip_serializing_if = "is_false")]
    pub verified_receipts_required: bool,
}

/// Exact mapping headers submitted before paged chunk metadata. Keeping the
/// mapping itself out of this request lets a 25 GiB blob use bounded requests.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BlobProofRequest {
    pub blobs: Vec<BlobProofDescriptor>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BlobProofDescriptor {
    pub hash: String,
    pub size: u64,
    /// Hash of the canonical ordered `(hash, offset, size)` chunk sequence.
    pub mapping_digest: String,
    pub total_chunks: u32,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BlobProofChunk {
    pub hash: String,
    pub offset: u64,
    pub size: u32,
}

/// Stable identity of one ordered blob-to-chunk layout. This deliberately
/// matches Oakspace's stored receipt digest byte-for-byte; changing it requires
/// a new protocol version and a receipt migration.
pub fn blob_mapping_digest(chunks: &[BlobProofChunk]) -> String {
    let mut canonical = Vec::with_capacity(chunks.len().saturating_mul(84));
    for (index, chunk) in chunks.iter().enumerate() {
        canonical.extend_from_slice(&(index as u64).to_be_bytes());
        canonical.extend_from_slice(&chunk.offset.to_be_bytes());
        canonical.extend_from_slice(&chunk.size.to_be_bytes());
        canonical.extend_from_slice(chunk.hash.as_bytes());
    }
    hash_bytes(&canonical).to_string()
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BlobProofPagesRequest {
    pub pages: Vec<BlobProofMappingPage>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BlobProofMappingPage {
    pub blob_index: u32,
    pub first_chunk_index: u32,
    pub chunks: Vec<BlobProofChunk>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BlobProofPagesResponse {
    pub accepted_chunks: u32,
    pub complete_blobs: Vec<u32>,
    pub all_mappings_complete: bool,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct BlobProofFinalizeRequest {}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BlobProofResponse {
    pub verified: Vec<String>,
    pub missing: Vec<String>,
    /// Opaque identity binding principal, repository, request digest, exact
    /// mapping generation, and its base generation. Required on every
    /// successful proof, including synchronous HTTP 200 responses.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub proof_token: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mapping_proof_job: Option<MappingProofJob>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MappingProofJob {
    pub token: String,
    pub status: String,
    pub retry_after_ms: u64,
}

fn is_false(value: &bool) -> bool {
    !*value
}

#[derive(Serialize, Deserialize)]
pub struct BlobInfoRequest {
    pub hashes: Vec<String>,
}

#[derive(Serialize, Deserialize)]
pub struct BlobInfoResponse {
    /// One entry per hash that the server has. Missing hashes are
    /// silently omitted — callers should diff the returned set against
    /// the requested set to detect unknown hashes.
    pub blobs: Vec<BlobData>,
    /// Requested hashes withheld because path-based permissions deny this
    /// caller their content — as opposed to hashes the server doesn't know.
    /// Older servers omit the field.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub restricted: Vec<String>,
}

#[derive(Serialize, Deserialize)]
pub struct CommitInfoRequest {
    pub hashes: Vec<String>,
    /// Return only verified commit DTOs, without recursively materializing
    /// their tree DAG. Used for small read-only remote existence proofs.
    #[serde(default, skip_serializing_if = "is_false")]
    pub metadata_only: bool,
}

#[derive(Serialize, Deserialize)]
pub struct CommitInfoResponse {
    /// One entry per hash the server has. Missing hashes are omitted.
    pub commits: Vec<CommitData>,
    /// Tree objects reachable from the returned commits' root trees,
    /// deduplicated by hash.
    pub trees: Vec<TreeData>,
    /// Present when the server answered from a view; see [`PullResponse::view`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub view: Option<ViewResponseData>,
}

// ---------------------------------------------------------------------------
// Chunk transfer
// ---------------------------------------------------------------------------

pub const CHUNK_BATCH_PROTOCOL: &str = "bounded_v1";
pub const CHUNK_BATCH_MAX_HASHES: usize = 10_000;

#[derive(Serialize, Deserialize)]
pub struct ChunkCheckRequest {
    pub hashes: Vec<String>,
    /// Sizes of each chunk in `hashes`, in parallel order. When provided, the
    /// server enforces the organization storage quota up front by summing the
    /// sizes of chunks the organization doesn't already have. Older clients
    /// that omit this field skip the up-front check (the server-mediated
    /// `upload_chunk` path still enforces the quota on receipt).
    #[serde(default)]
    pub sizes: Option<Vec<u64>>,
    /// Opt in to the bounded batch contract. New clients page requests to the
    /// advertised limit and send the exact `bounded_v1` token; old clients
    /// omit the field so a compatibility server can retain its legacy limits.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub chunk_batch_protocol: Option<String>,
}

#[derive(Serialize, Deserialize)]
pub struct ChunkUploadInfo {
    pub hash: String,
    /// Presigned PUT URL for direct R2 upload (None if no R2 configured, in
    /// which case the client uploads via the server-mediated `PUT
    /// /chunks/{hash}` path).
    pub upload_url: Option<String>,
}

#[derive(Serialize, Deserialize)]
pub struct ChunkCheckServerResponse {
    pub missing: Vec<ChunkUploadInfo>,
}

#[derive(Serialize, Deserialize)]
pub struct ChunkDownloadRequest {
    pub hashes: Vec<String>,
    /// See [`ChunkCheckRequest::chunk_batch_protocol`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub chunk_batch_protocol: Option<String>,
}

#[derive(Serialize, Deserialize)]
pub struct ChunkDownloadInfo {
    pub hash: String,
    /// Presigned GET URL for direct R2 download (None if content is inline).
    pub download_url: Option<String>,
    /// Chunk content from DB (only when R2 is not configured).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub content: Option<Vec<u8>>,
}

#[derive(Serialize, Deserialize)]
pub struct ChunkDownloadResponse {
    pub chunks: Vec<ChunkDownloadInfo>,
    /// Batch-download endpoint (CDN Worker) carrying a capability token, set
    /// only when the chunk CDN is configured. Clients may POST a
    /// `{ "hashes": [...] }` body here to fetch many small chunks in one
    /// length-framed response instead of one GET per chunk. `None` → fall back
    /// to per-chunk `download_url`/`content`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub batch_url: Option<String>,
    /// Requested chunk hashes withheld because they belong exclusively to
    /// blobs that path-based permissions deny this caller. Older servers omit
    /// the field.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub restricted: Vec<String>,
}

// ---------------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------------

/// Generic JSON error body.
#[derive(Serialize, Deserialize)]
pub struct ErrorResponse {
    pub error: String,
}

// ---------------------------------------------------------------------------
// Conversions between wire DTOs and the core domain model
// ---------------------------------------------------------------------------

/// Convert a wire [`TreeData`] to a core [`Tree`]. Validates `kind` and
/// `mode`, plus entry names and hashes — wire data is untrusted, and a name
/// containing the canonical format's `\t`/`\n` separators (or a hash that
/// isn't hex) would corrupt the stored preimage.
///
/// Crucially, this also **verifies the tree's content-address**: blobs are
/// hash-checked before storage, but trees were not — so a malicious or buggy
/// peer (the pull endpoint) could store a tree under a hash whose
/// entries point at arbitrary blobs, silently breaking the content-addressing
/// invariant. We rebuild the tree through [`Tree::new`] (which canonicalizes
/// entry order and recomputes the hash) and reject any payload whose claimed
/// hash doesn't match the content.
pub fn tree_data_to_core(td: &TreeData) -> Result<Tree, String> {
    let tree_hash = Hash::from_hex(&td.hash).map_err(|e| e.to_string())?;
    let mut entries = Vec::with_capacity(td.entries.len());
    for e in &td.entries {
        crate::tree::validate_entry_name(&e.name).map_err(|err| err.to_string())?;
        let kind = match e.kind.as_str() {
            "tree" => TreeEntryKind::Tree,
            "blob" => TreeEntryKind::Blob,
            other => return Err(format!("invalid tree entry kind: {other}")),
        };
        let mode = match (kind, e.mode.as_str()) {
            (TreeEntryKind::Tree, "tree") => FileMode::Regular,
            (TreeEntryKind::Blob, "regular") => FileMode::Regular,
            (TreeEntryKind::Blob, "executable") => FileMode::Executable,
            (TreeEntryKind::Blob, "symlink") => FileMode::Symlink,
            _ => {
                return Err(format!(
                    "invalid tree entry mode {:?} for kind {}",
                    e.mode,
                    e.kind.as_str()
                ))
            }
        };
        entries.push(TreeEntry {
            name: e.name.clone(),
            kind,
            hash: Hash::from_hex(&e.hash).map_err(|err| err.to_string())?,
            mode,
        });
    }
    // `Tree::new` sorts entries into canonical order and recomputes the hash
    // over the canonical preimage — the same recipe used when the tree was
    // first created. If the recomputed hash differs from what the peer claimed,
    // the content doesn't match its address: reject it.
    let tree = Tree::new(entries).map_err(|e| e.to_string())?;
    if tree.hash != tree_hash {
        return Err(format!(
            "tree hash mismatch: peer claimed {}, content hashes to {}",
            td.hash, tree.hash
        ));
    }
    Ok(tree)
}

fn wire_hash(field: &str, value: &str) -> Result<Hash, String> {
    Hash::from_hex(value).map_err(|e| format!("invalid {field} hash {value:?}: {e}"))
}

fn wire_optional_hash(field: &str, value: Option<&String>) -> Result<Option<Hash>, String> {
    value.map(|s| wire_hash(field, s)).transpose()
}

fn file_change_data_to_core(f: &FileChangeData, index: usize) -> Result<FileChange, String> {
    crate::tree::validate_tree_path(&f.path)
        .map_err(|e| format!("invalid file change #{index} path: {e}"))?;
    if let Some(old_path) = &f.old_path {
        crate::tree::validate_tree_path(old_path)
            .map_err(|e| format!("invalid file change #{index} old_path: {e}"))?;
    }

    let change_type = match f.change_type.as_str() {
        "added" => ChangeType::Added,
        "modified" => ChangeType::Modified,
        "deleted" => ChangeType::Deleted,
        "renamed" => ChangeType::Renamed,
        other => return Err(format!("invalid file change #{index} type: {other}")),
    };
    let parse_mode = |field: &str, mode: Option<&String>| {
        mode.map(|mode| match mode.as_str() {
            "regular" => Ok(FileMode::Regular),
            "executable" => Ok(FileMode::Executable),
            "symlink" => Ok(FileMode::Symlink),
            other => Err(format!("invalid file change #{index} {field}: {other}")),
        })
        .transpose()
    };

    Ok(FileChange {
        path: f.path.clone(),
        change_type,
        old_blob_hash: wire_optional_hash("old blob", f.old_blob_hash.as_ref())?,
        new_blob_hash: wire_optional_hash("new blob", f.new_blob_hash.as_ref())?,
        old_path: f.old_path.clone(),
        old_mode: parse_mode("old_mode", f.old_mode.as_ref())?,
        new_mode: parse_mode("new_mode", f.new_mode.as_ref())?,
    })
}

pub fn file_mode_to_wire(mode: FileMode) -> &'static str {
    match mode {
        FileMode::Regular => "regular",
        FileMode::Executable => "executable",
        FileMode::Symlink => "symlink",
    }
}

/// Convert a wire [`CommitData`] to a core [`Commit`].
///
/// The wire claim is untrusted: validate every hash-position string, validate
/// commit fields through [`Commit::rehydrate_verified`], recompute the current
/// Oak commit hash from canonical fields, and reject any payload whose claimed
/// hash cannot be reproduced from them.
pub fn commit_data_to_core(cd: &CommitData) -> Result<Commit, String> {
    let claimed_hash = wire_hash("commit", &cd.hash)?;
    let parent_hash = wire_optional_hash("parent", cd.parent_hash.as_ref())?;
    let merge_parent_hash = wire_optional_hash("merge parent", cd.merge_parent_hash.as_ref())?;
    let manifest_hash = wire_hash("manifest", &cd.manifest_hash)?;
    let timestamp = chrono::DateTime::parse_from_rfc3339(&cd.timestamp)
        .map_err(|e| format!("invalid commit timestamp {:?}: {e}", cd.timestamp))?
        .with_timezone(&chrono::Utc);
    let files: Vec<FileChange> = cd
        .files
        .iter()
        .enumerate()
        .map(|(i, f)| file_change_data_to_core(f, i))
        .collect::<Result<_, _>>()?;

    // `rehydrate_verified` (rather than a plain recompute-and-compare)
    // tolerates microsecond-truncated timestamps on commits that hashed
    // nanosecond ones — every squash-merge the server stored before
    // `Commit::new` started truncating. See its docs.
    Commit::rehydrate_verified(
        &claimed_hash,
        cd.branch_name.clone(),
        parent_hash,
        merge_parent_hash,
        manifest_hash,
        cd.author.clone(),
        cd.message.clone(),
        files,
        timestamp,
    )
    .map_err(|e| e.to_string())
}

/// Convert a core [`Tree`] to wire [`TreeData`].
pub fn tree_to_wire(tree: &Tree) -> TreeData {
    TreeData {
        hash: tree.hash.to_string(),
        entries: tree
            .entries
            .iter()
            .map(|e| TreeEntryData {
                name: e.name.clone(),
                kind: e.kind.as_str().to_string(),
                hash: e.hash.to_string(),
                mode: match (e.kind, e.mode) {
                    (TreeEntryKind::Tree, _) => "tree".to_string(),
                    (TreeEntryKind::Blob, FileMode::Regular) => "regular".to_string(),
                    (TreeEntryKind::Blob, FileMode::Executable) => "executable".to_string(),
                    (TreeEntryKind::Blob, FileMode::Symlink) => "symlink".to_string(),
                },
            })
            .collect(),
    }
}

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

    #[test]
    fn view_query_is_opt_in_and_url_encodable() {
        let view = crate::ViewSpec::new(["apps/web"], ["apps/web/config"], ["AGENTS.md"]).unwrap();
        let query = ViewQuery::new(Some(&view));
        assert!(query.is_view_request());
        assert_eq!(
            serde_json::to_value(&query).unwrap(),
            serde_json::json!({
                "view_protocol": "view_v1",
                "view": "+apps/web\n-apps/web/config\n=AGENTS.md",
            })
        );
        let parsed = crate::ViewSpec::parse(query.view.as_deref().unwrap()).unwrap();
        assert_eq!(parsed, view);
        assert_eq!(
            serde_json::to_value(ViewQuery::default()).unwrap(),
            serde_json::json!({})
        );
        assert!(!ViewQuery::default().is_view_request());
    }

    #[test]
    fn responses_without_view_data_still_parse_and_omit_the_field() {
        let pull: PullResponse = serde_json::from_value(serde_json::json!({
            "head": null, "branch": null, "branches": [], "commits": [], "blobs": [], "trees": [],
        }))
        .unwrap();
        assert!(pull.view.is_none());
        assert!(serde_json::to_value(&pull).unwrap().get("view").is_none());

        let push: PushResponse = serde_json::from_value(serde_json::json!({
            "success": true, "new_head": "h", "message": "ok",
        }))
        .unwrap();
        assert!(push.view.is_none());

        let info = CommitInfoResponse {
            commits: vec![],
            trees: vec![],
            view: Some(ViewResponseData {
                effective_view: "+apps/web".to_string(),
                view_id: "id".to_string(),
                commits: vec![ViewCommitMapping {
                    full_hash: "f".to_string(),
                    view_hash: "v".to_string(),
                }],
                excluded_by_permission: 0,
            }),
        };
        assert_eq!(
            serde_json::to_value(&info).unwrap()["view"],
            serde_json::json!({
                "effective_view": "+apps/web",
                "view_id": "id",
                "commits": [{ "full_hash": "f", "view_hash": "v" }],
            })
        );
    }

    #[test]
    fn async_mapping_proof_wire_is_versioned_and_exact() {
        let request = BlobProofRequest {
            blobs: vec![BlobProofDescriptor {
                hash: "a".repeat(64),
                size: 3,
                mapping_digest: "6ed22faf011636d53e22b7f48e5c9ac2ef718887ebc0b7009ddb08476fdced82"
                    .to_string(),
                total_chunks: 1,
            }],
        };
        assert_eq!(MAPPING_PROOF_PROTOCOL, "async_v1");
        assert_eq!(
            serde_json::to_value(&request).unwrap(),
            serde_json::json!({
                "blobs": [{
                    "hash": "a".repeat(64),
                    "size": 3,
                    "mapping_digest": "6ed22faf011636d53e22b7f48e5c9ac2ef718887ebc0b7009ddb08476fdced82",
                    "total_chunks": 1
                }]
            })
        );
        assert_eq!(
            serde_json::to_string(&request).unwrap(),
            format!(
                "{{\"blobs\":[{{\"hash\":\"{}\",\"size\":3,\"mapping_digest\":\"6ed22faf011636d53e22b7f48e5c9ac2ef718887ebc0b7009ddb08476fdced82\",\"total_chunks\":1}}]}}",
                "a".repeat(64)
            )
        );

        let created: BlobProofResponse = serde_json::from_value(serde_json::json!({
            "verified": [],
            "missing": [],
            "mapping_proof_job": {
                "token": "proof-token",
                "status": "uploading",
                "retry_after_ms": 500
            }
        }))
        .unwrap();
        assert_eq!(
            created.mapping_proof_job.as_ref().unwrap().token,
            "proof-token"
        );
        assert_eq!(
            serde_json::to_string(&created).unwrap(),
            "{\"verified\":[],\"missing\":[],\"mapping_proof_job\":{\"token\":\"proof-token\",\"status\":\"uploading\",\"retry_after_ms\":500}}"
        );

        let pages = BlobProofPagesRequest {
            pages: vec![BlobProofMappingPage {
                blob_index: 0,
                first_chunk_index: 0,
                chunks: vec![BlobProofChunk {
                    hash: "c".repeat(64),
                    offset: 0,
                    size: 3,
                }],
            }],
        };
        assert_eq!(
            serde_json::to_value(&pages).unwrap(),
            serde_json::json!({
                "pages": [{
                    "blob_index": 0,
                    "first_chunk_index": 0,
                    "chunks": [{
                        "hash": "c".repeat(64),
                        "offset": 0,
                        "size": 3
                    }]
                }]
            })
        );
        assert_eq!(
            serde_json::to_string(&pages).unwrap(),
            format!(
                "{{\"pages\":[{{\"blob_index\":0,\"first_chunk_index\":0,\"chunks\":[{{\"hash\":\"{}\",\"offset\":0,\"size\":3}}]}}]}}",
                "c".repeat(64)
            )
        );

        let accepted: BlobProofPagesResponse = serde_json::from_value(serde_json::json!({
            "accepted_chunks": 1,
            "complete_blobs": [0],
            "all_mappings_complete": true
        }))
        .unwrap();
        assert!(accepted.all_mappings_complete);
        assert_eq!(
            serde_json::to_string(&accepted).unwrap(),
            "{\"accepted_chunks\":1,\"complete_blobs\":[0],\"all_mappings_complete\":true}"
        );

        assert_eq!(
            serde_json::to_value(BlobProofFinalizeRequest {}).unwrap(),
            serde_json::json!({})
        );

        let finalized: BlobProofResponse = serde_json::from_value(serde_json::json!({
            "verified": [],
            "missing": [],
            "mapping_proof_job": {
                "token": "proof-token",
                "status": "pending",
                "retry_after_ms": 500
            }
        }))
        .unwrap();
        assert_eq!(
            finalized.mapping_proof_job.as_ref().unwrap().status,
            "pending"
        );
        assert_eq!(
            serde_json::to_string(&finalized).unwrap(),
            "{\"verified\":[],\"missing\":[],\"mapping_proof_job\":{\"token\":\"proof-token\",\"status\":\"pending\",\"retry_after_ms\":500}}"
        );

        let terminal = serde_json::to_value(BlobProofResponse {
            verified: vec!["a".repeat(64)],
            missing: Vec::new(),
            proof_token: Some("proof-token".to_string()),
            mapping_proof_job: None,
        })
        .unwrap();
        assert_eq!(terminal["proof_token"], "proof-token");
        assert_eq!(
            serde_json::to_string(&BlobProofResponse {
                verified: vec!["a".repeat(64)],
                missing: Vec::new(),
                proof_token: Some("proof-token".to_string()),
                mapping_proof_job: None,
            })
            .unwrap(),
            format!(
                "{{\"verified\":[\"{}\"],\"missing\":[],\"proof_token\":\"proof-token\"}}",
                "a".repeat(64)
            )
        );
    }

    #[test]
    fn mapping_digest_matches_the_stored_receipt_identity() {
        let chunks = vec![
            BlobProofChunk {
                hash: "c".repeat(64),
                offset: 0,
                size: 3,
            },
            BlobProofChunk {
                hash: "c".repeat(64),
                offset: 3,
                size: 3,
            },
        ];

        assert_eq!(
            blob_mapping_digest(&chunks[..1]),
            "6ed22faf011636d53e22b7f48e5c9ac2ef718887ebc0b7009ddb08476fdced82"
        );
        assert_eq!(
            blob_mapping_digest(&chunks),
            "2604417dcfdfa8bc4fc85d2b24a965fb8d7c328d00723c31b75ad7bbdaa194fe"
        );
        assert_eq!(
            blob_mapping_digest(&[]),
            "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262"
        );
    }

    #[test]
    fn blob_check_verified_content_is_append_only_and_fail_closed() {
        let legacy: BlobCheckResponse =
            serde_json::from_value(serde_json::json!({ "missing": [] })).unwrap();
        assert!(!legacy.verified_content);
        assert!(!legacy.verified_receipts_required);

        let ordinary = serde_json::to_value(BlobCheckRequest {
            hashes: vec!["ab".repeat(32)],
            require_verified_receipts: false,
            verify_content: false,
        })
        .unwrap();
        assert!(ordinary.get("verify_content").is_none());
        assert!(ordinary.get("require_verified_receipts").is_none());

        let receipt_strict = serde_json::to_value(BlobCheckRequest {
            hashes: vec!["ab".repeat(32)],
            require_verified_receipts: true,
            verify_content: false,
        })
        .unwrap();
        assert_eq!(receipt_strict["require_verified_receipts"], true);
        assert!(receipt_strict.get("verify_content").is_none());

        let verified = serde_json::to_value(BlobCheckRequest {
            hashes: vec!["ab".repeat(32)],
            require_verified_receipts: false,
            verify_content: true,
        })
        .unwrap();
        assert_eq!(verified["verify_content"], true);
    }

    #[test]
    fn staged_push_protocol_is_structurally_separate_from_legacy_push() {
        let ordinary: PushRequest = serde_json::from_value(serde_json::json!({
            "expected_head": null,
            "branch": null,
            "commits": [],
            "blobs": [],
            "trees": []
        }))
        .unwrap();
        let ordinary = serde_json::to_value(&ordinary).unwrap();
        assert!(ordinary.get("finalize").is_none());

        let staged = serde_json::to_value(StagedPushRequest {
            stage_id: "0123456789abcdef0123456789abcdef".to_string(),
            expected_branch_head: None,
            branch: BranchPushData {
                name: "main".to_string(),
                description: None,
                parent_branch: None,
                status: "open".to_string(),
                created_at: "2026-01-01T00:00:00Z".to_string(),
                close_reason: None,
            },
            finalize: false,
            force: true,
            target_head: None,
            commits: Vec::new(),
            blobs: Vec::new(),
            trees: Vec::new(),
        })
        .unwrap();
        assert_eq!(staged["expected_branch_head"], serde_json::Value::Null);
        assert_eq!(staged["finalize"], false);
        assert_eq!(staged["force"], true);
        assert!(staged["branch"].get("close_reason").is_none());
        let legacy_branch: BranchPushData = serde_json::from_value(serde_json::json!({
            "name": "main",
            "description": null,
            "parent_branch": null,
            "status": "open",
            "created_at": "2026-01-01T00:00:00Z"
        }))
        .unwrap();
        assert_eq!(legacy_branch.close_reason, None);
        let mut missing_boundary = staged.clone();
        missing_boundary
            .as_object_mut()
            .unwrap()
            .remove("expected_branch_head");
        assert!(serde_json::from_value::<StagedPushRequest>(missing_boundary).is_err());

        let legacy_staged: StagedPushRequest = serde_json::from_value(serde_json::json!({
            "stage_id": "0123456789abcdef0123456789abcdef",
            "expected_branch_head": null,
            "branch": {
                "name": "main",
                "description": null,
                "parent_branch": null,
                "status": "open",
                "created_at": "2026-01-01T00:00:00Z"
            },
            "finalize": false,
            "target_head": null,
            "commits": [],
            "blobs": [],
            "trees": []
        }))
        .unwrap();
        assert!(
            !legacy_staged.force,
            "omitted force must remain fail-closed"
        );

        let ordinary_info = serde_json::to_value(CommitInfoRequest {
            hashes: vec!["cd".repeat(32)],
            metadata_only: false,
        })
        .unwrap();
        assert!(ordinary_info.get("metadata_only").is_none());
        let metadata_info = serde_json::to_value(CommitInfoRequest {
            hashes: vec!["cd".repeat(32)],
            metadata_only: true,
        })
        .unwrap();
        assert_eq!(metadata_info["metadata_only"], true);

        let abort = serde_json::to_value(StagedAbortRequest {
            branch_name: "main".to_string(),
            expected_branch_head: None,
        })
        .unwrap();
        assert_eq!(abort["branch_name"], "main");
        assert!(abort.get("expected_branch_head").is_some());
        let response: StagedAbortResponse = serde_json::from_value(serde_json::json!({
            "aborted": true,
            "state": "aborted"
        }))
        .unwrap();
        assert!(response.aborted);
        assert_eq!(response.state, "aborted");
    }

    #[test]
    fn pull_missing_content_is_append_only_and_operator_adjudicated() {
        let legacy: PullResponse = serde_json::from_value(serde_json::json!({
            "head": null,
            "branch": null,
            "branches": [],
            "commits": [],
            "blobs": [],
            "trees": []
        }))
        .unwrap();
        assert!(legacy.missing_content.is_empty());

        let response: PullResponse = serde_json::from_value(serde_json::json!({
            "head": null,
            "branch": null,
            "branches": [],
            "commits": [],
            "blobs": [],
            "trees": [],
            "missing_content": [{
                "kind": "blob",
                "hash": "ab".repeat(32),
                "reason_code": "operator_adjudicated_loss"
            }]
        }))
        .unwrap();
        assert_eq!(response.missing_content.len(), 1);
        assert_eq!(response.missing_content[0].kind, "blob");
        assert_eq!(
            response.missing_content[0].reason_code,
            "operator_adjudicated_loss"
        );
    }

    #[test]
    fn pull_known_loss_protocol_is_explicit_and_omitted_for_legacy_requests() {
        let mut query = PullQuery {
            since: None,
            branch_name: None,
            force: false,
            since_rename_id: 0,
            depth: None,
            known_loss_protocol: None,
            retention_protocol: None,
        };
        let legacy = serde_json::to_value(&query).unwrap();
        assert!(legacy.get("known_loss_protocol").is_none());
        assert!(legacy.get("retention_protocol").is_none());

        query.known_loss_protocol = Some("report_v1".to_string());
        query.retention_protocol = Some(RETENTION_PROTOCOL.to_string());
        let opted_in = serde_json::to_value(&query).unwrap();
        assert_eq!(opted_in["known_loss_protocol"], "report_v1");
        assert_eq!(opted_in["retention_protocol"], "expired_v1");
    }

    #[test]
    fn chunk_batch_protocol_is_append_only_and_explicit() {
        let legacy_check: ChunkCheckRequest = serde_json::from_value(serde_json::json!({
            "hashes": [],
            "sizes": []
        }))
        .unwrap();
        assert_eq!(legacy_check.chunk_batch_protocol, None);
        let legacy_download: ChunkDownloadRequest =
            serde_json::from_value(serde_json::json!({ "hashes": [] })).unwrap();
        assert_eq!(legacy_download.chunk_batch_protocol, None);

        let check = serde_json::to_value(ChunkCheckRequest {
            hashes: vec!["ab".repeat(32)],
            sizes: Some(vec![1]),
            chunk_batch_protocol: Some("bounded_v1".to_string()),
        })
        .unwrap();
        assert_eq!(check["chunk_batch_protocol"], "bounded_v1");
        let download = serde_json::to_value(ChunkDownloadRequest {
            hashes: vec!["ab".repeat(32)],
            chunk_batch_protocol: Some("bounded_v1".to_string()),
        })
        .unwrap();
        assert_eq!(download["chunk_batch_protocol"], "bounded_v1");
    }

    fn sample_tree() -> Tree {
        Tree::new(vec![
            TreeEntry {
                name: "a.txt".to_string(),
                kind: TreeEntryKind::Blob,
                hash: Hash::from_hex(&"11".repeat(32)).unwrap(),
                mode: FileMode::Regular,
            },
            TreeEntry {
                name: "b.txt".to_string(),
                kind: TreeEntryKind::Blob,
                hash: Hash::from_hex(&"22".repeat(32)).unwrap(),
                mode: FileMode::Regular,
            },
        ])
        .unwrap()
    }

    #[test]
    fn tree_data_to_core_round_trips_a_valid_tree() {
        let tree = sample_tree();
        let wire = tree_to_wire(&tree);
        let back = tree_data_to_core(&wire).expect("valid tree must convert");
        assert_eq!(back.hash, tree.hash);
        assert_eq!(back.entries.len(), 2);
    }

    #[test]
    fn tree_data_to_core_rejects_tampered_entry_under_claimed_hash() {
        // A peer keeps the legitimate tree hash but swaps an entry's blob hash
        // to point at arbitrary content. This must be rejected, not stored.
        let tree = sample_tree();
        let mut wire = tree_to_wire(&tree);
        wire.entries[0].hash = "99".repeat(32); // different blob, same tree hash claimed
        let err = tree_data_to_core(&wire)
            .expect_err("a tree whose content doesn't match its hash must be rejected");
        assert!(
            err.contains("hash mismatch"),
            "expected a hash-mismatch error, got: {err}"
        );
    }

    #[test]
    fn tree_data_to_core_canonicalizes_entry_order() {
        // Even if a peer sends entries out of canonical order, the verified
        // tree comes back sorted and still matches the claimed hash.
        let tree = sample_tree();
        let mut wire = tree_to_wire(&tree);
        wire.entries.reverse();
        let back = tree_data_to_core(&wire).expect("order must not affect validity");
        assert_eq!(back.hash, tree.hash);
        assert_eq!(back.entries[0].name, "a.txt");
    }

    #[test]
    fn tree_data_to_core_rejects_invalid_mode() {
        let tree = sample_tree();
        let mut wire = tree_to_wire(&tree);
        wire.entries[0].mode = "mystery".to_string();
        let err = tree_data_to_core(&wire).expect_err("invalid mode must be rejected");
        assert!(
            err.contains("invalid tree entry mode"),
            "unexpected error: {err}"
        );
    }

    fn commit_to_wire(commit: &Commit) -> CommitData {
        CommitData {
            hash: commit.hash.to_string(),
            branch_name: commit.branch_name.clone(),
            parent_hash: commit.parent_hash.as_ref().map(|h| h.to_string()),
            merge_parent_hash: commit.merge_parent_hash.as_ref().map(|h| h.to_string()),
            manifest_hash: commit.manifest_hash.to_string(),
            author: commit.author.clone(),
            message: commit.message.clone(),
            timestamp: commit.timestamp.to_rfc3339(),
            files: commit
                .files
                .iter()
                .map(|f| FileChangeData {
                    path: f.path.clone(),
                    change_type: match f.change_type {
                        ChangeType::Added => "added".to_string(),
                        ChangeType::Modified => "modified".to_string(),
                        ChangeType::Deleted => "deleted".to_string(),
                        ChangeType::Renamed => "renamed".to_string(),
                    },
                    old_blob_hash: f.old_blob_hash.as_ref().map(|h| h.to_string()),
                    new_blob_hash: f.new_blob_hash.as_ref().map(|h| h.to_string()),
                    old_path: f.old_path.clone(),
                    old_mode: f.old_mode.map(|mode| file_mode_to_wire(mode).to_string()),
                    new_mode: f.new_mode.map(|mode| file_mode_to_wire(mode).to_string()),
                })
                .collect(),
        }
    }

    fn sample_commit() -> CommitData {
        let timestamp = chrono::DateTime::parse_from_rfc3339("2026-06-24T00:00:00Z")
            .unwrap()
            .with_timezone(&chrono::Utc);
        let commit = Commit::with_timestamp(
            "main".to_string(),
            None,
            None,
            Tree::empty_hash(),
            "tester".to_string(),
            None,
            vec![FileChange {
                path: "src/lib.rs".to_string(),
                change_type: ChangeType::Modified,
                old_blob_hash: Some(Hash::from_hex(&"11".repeat(32)).unwrap()),
                new_blob_hash: Some(Hash::from_hex(&"22".repeat(32)).unwrap()),
                old_path: None,
                old_mode: None,
                new_mode: None,
            }],
            timestamp,
        )
        .unwrap();
        commit_to_wire(&commit)
    }

    #[test]
    fn commit_data_to_core_round_trips_valid_commit() {
        let wire = sample_commit();
        let commit = commit_data_to_core(&wire).expect("valid commit must convert");
        assert_eq!(commit.hash.to_string(), wire.hash);
        assert_eq!(commit.branch_name, "main");
        assert_eq!(commit.files.len(), 1);
    }

    /// Pin the actual commit hash produced for `sample_commit`'s fixed inputs.
    ///
    /// `commit_data_to_core_round_trips_valid_commit` only proves the wire hash
    /// and the recomputed hash agree — but both are produced by the same code,
    /// so a change to the commit hash format moves them together and that test
    /// stays green. This freezes the concrete value, so any drift in the v1
    /// commit preimage is caught at the exact boundary where it would otherwise
    /// surface in production: a server commit failing `commit hash mismatch`
    /// against a client that hashes differently.
    #[test]
    fn commit_data_to_core_hash_is_stable() {
        let wire = sample_commit();
        assert_eq!(
            wire.hash,
            "93dd864faf6f23324fa2010c7f6d51b5aa456686586a2b65c132575661866b0a"
        );
    }

    #[test]
    fn commit_data_to_core_rejects_hash_mismatch() {
        let mut wire = sample_commit();
        wire.hash = "99".repeat(32);
        let err = commit_data_to_core(&wire).expect_err("tampered commit hash must be rejected");
        assert!(
            err.contains("commit hash mismatch"),
            "expected a commit hash mismatch, got: {err}"
        );
    }

    /// A commit hashed with a nanosecond timestamp whose stored/wire timestamp
    /// was truncated to microseconds (Postgres `TIMESTAMPTZ`) must still
    /// verify — with the lost digits provably recovered, not trusted. Every
    /// squash-merge the server created before `Commit::new` truncated is in
    /// this state.
    #[test]
    fn commit_data_to_core_recovers_micro_truncated_timestamp() {
        let nano_ts = chrono::DateTime::parse_from_rfc3339("2026-07-04T08:25:15.778307228Z")
            .unwrap()
            .with_timezone(&chrono::Utc);
        let commit = Commit::with_timestamp(
            "main".to_string(),
            None,
            None,
            Tree::empty_hash(),
            "tester".to_string(),
            Some("squash message".to_string()),
            Vec::new(),
            nano_ts,
        )
        .unwrap();

        let mut wire = commit_to_wire(&commit);
        // Simulate the microsecond truncation the server's store applied.
        wire.timestamp = "2026-07-04T08:25:15.778307+00:00".to_string();

        let back = commit_data_to_core(&wire).expect("truncated timestamp must be recovered");
        assert_eq!(back.hash, commit.hash);
        // The recovered timestamp is the original nanosecond one, so the
        // returned commit is exactly self-verifying when re-stored.
        assert_eq!(back.timestamp, nano_ts);

        // Truncation tolerance must not accept genuinely wrong fields.
        let mut tampered = commit_to_wire(&commit);
        tampered.timestamp = "2026-07-04T08:25:15.778307+00:00".to_string();
        tampered.author = "someone-else".to_string();
        let err = commit_data_to_core(&tampered).expect_err("tampered fields must be rejected");
        assert!(
            err.contains("commit hash mismatch"),
            "expected a commit hash mismatch, got: {err}"
        );
    }

    #[test]
    fn commit_data_to_core_rejects_invalid_hash_fields_and_change_types() {
        let mut wire = sample_commit();
        wire.parent_hash = Some("not-a-hash".to_string());
        let err = commit_data_to_core(&wire).expect_err("invalid parent hash must be rejected");
        assert!(
            err.contains("invalid parent hash"),
            "unexpected error: {err}"
        );

        let mut wire = sample_commit();
        wire.files[0].change_type = "rewritten".to_string();
        let err = commit_data_to_core(&wire).expect_err("invalid change type must be rejected");
        assert!(
            err.contains("invalid file change #0 type"),
            "unexpected error: {err}"
        );
    }
}