suture-protocol 0.10.0

A patch-based version control system with semantic merge and format-aware drivers
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
//! Suture Protocol — wire format for client-server communication.
//!
//! Defines the request/response types used by the Suture Hub for
//! push, pull, authentication, and repository management operations.
//! All types are serializable via `serde` for JSON transport.

use serde::{Deserialize, Serialize};

pub const PROTOCOL_VERSION: u32 = 1;
pub const PROTOCOL_VERSION_V2: u32 = 2;

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct HandshakeRequest {
    pub client_version: u32,
    pub client_name: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct HandshakeResponse {
    pub server_version: u32,
    pub server_name: String,
    pub compatible: bool,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum AuthMethod {
    None,
    Signature {
        public_key: String,
        signature: String,
    },
    Token(String),
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AuthRequest {
    pub method: AuthMethod,
    pub timestamp: u64,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct HashProto {
    pub value: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PatchProto {
    pub id: HashProto,
    pub operation_type: String,
    pub touch_set: Vec<String>,
    pub target_path: Option<String>,
    pub payload: String,
    pub parent_ids: Vec<HashProto>,
    pub author: String,
    pub message: String,
    pub timestamp: u64,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BranchProto {
    pub name: String,
    pub target_id: HashProto,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BlobRef {
    pub hash: HashProto,
    pub data: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct PushRequest {
    pub repo_id: String,
    pub patches: Vec<PatchProto>,
    pub branches: Vec<BranchProto>,
    pub blobs: Vec<BlobRef>,
    /// Optional Ed25519 signature (64 bytes, base64-encoded).
    /// Required when the hub has authorized keys configured.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signature: Option<Vec<u8>>,
    /// Client's known state of branches at time of push.
    /// Used for fast-forward validation on the hub.
    /// Optional for backward compatibility.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub known_branches: Option<Vec<BranchProto>>,
    /// If true, skip fast-forward validation on push.
    #[serde(default)]
    pub force: bool,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct PushResponse {
    pub success: bool,
    pub error: Option<String>,
    pub existing_patches: Vec<HashProto>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct PullRequest {
    pub repo_id: String,
    pub known_branches: Vec<BranchProto>,
    /// Limit the number of patches returned from each branch tip.
    /// None = full history, Some(n) = last n patches per branch.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_depth: Option<u32>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct PullResponse {
    pub success: bool,
    pub error: Option<String>,
    pub patches: Vec<PatchProto>,
    pub branches: Vec<BranchProto>,
    pub blobs: Vec<BlobRef>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ListReposResponse {
    pub repo_ids: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct RepoInfoResponse {
    pub repo_id: String,
    pub patch_count: u64,
    pub branches: Vec<BranchProto>,
    pub success: bool,
    pub error: Option<String>,
}

pub fn hash_to_hex(h: &HashProto) -> String {
    h.value.clone()
}

pub fn compress(data: &[u8]) -> Result<Vec<u8>, String> {
    zstd::encode_all(data, 3).map_err(|e| format!("zstd compression failed: {e}"))
}

pub fn decompress(data: &[u8]) -> Result<Vec<u8>, String> {
    zstd::decode_all(data).map_err(|e| format!("zstd decompression failed: {e}"))
}

pub fn hex_to_hash(hex: &str) -> HashProto {
    HashProto {
        value: hex.to_string(),
    }
}

/// Build canonical bytes for push request signing.
/// Format: repo_id \0 patch_count \0 (each patch: id \0 op \0 author \0 msg \0 timestamp \0) ... branch_count \0 (each: name \0 target \0) ...
pub fn canonical_push_bytes(req: &PushRequest) -> Vec<u8> {
    let mut buf = Vec::new();

    buf.extend_from_slice(req.repo_id.as_bytes());
    buf.push(0);

    buf.extend_from_slice(&(req.patches.len() as u64).to_le_bytes());
    for patch in &req.patches {
        buf.extend_from_slice(patch.id.value.as_bytes());
        buf.push(0);
        buf.extend_from_slice(patch.operation_type.as_bytes());
        buf.push(0);
        buf.extend_from_slice(patch.author.as_bytes());
        buf.push(0);
        buf.extend_from_slice(patch.message.as_bytes());
        buf.push(0);
        buf.extend_from_slice(&patch.timestamp.to_le_bytes());
        buf.push(0);
    }

    buf.extend_from_slice(&(req.branches.len() as u64).to_le_bytes());
    for branch in &req.branches {
        buf.extend_from_slice(branch.name.as_bytes());
        buf.push(0);
        buf.extend_from_slice(branch.target_id.value.as_bytes());
        buf.push(0);
    }

    buf
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum DeltaEncoding {
    BinaryPatch,
    FullBlob,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BlobDelta {
    pub base_hash: HashProto,
    pub target_hash: HashProto,
    pub encoding: DeltaEncoding,
    pub delta_data: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ClientCapabilities {
    pub supports_delta: bool,
    pub supports_compression: bool,
    pub max_blob_size: u64,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ServerCapabilities {
    pub supports_delta: bool,
    pub supports_compression: bool,
    pub max_blob_size: u64,
    pub protocol_versions: Vec<u32>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct PullRequestV2 {
    pub repo_id: String,
    pub known_branches: Vec<BranchProto>,
    pub max_depth: Option<u32>,
    pub known_blob_hashes: Vec<HashProto>,
    pub capabilities: ClientCapabilities,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct PullResponseV2 {
    pub success: bool,
    pub error: Option<String>,
    pub patches: Vec<PatchProto>,
    pub branches: Vec<BranchProto>,
    pub blobs: Vec<BlobRef>,
    pub deltas: Vec<BlobDelta>,
    pub protocol_version: u32,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct PushRequestV2 {
    pub repo_id: String,
    pub patches: Vec<PatchProto>,
    pub branches: Vec<BranchProto>,
    pub blobs: Vec<BlobRef>,
    pub deltas: Vec<BlobDelta>,
    pub signature: Option<Vec<u8>>,
    pub known_branches: Option<Vec<BranchProto>>,
    pub force: bool,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct HandshakeRequestV2 {
    pub client_version: u32,
    pub client_name: String,
    pub capabilities: ClientCapabilities,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct HandshakeResponseV2 {
    pub server_version: u32,
    pub server_name: String,
    pub compatible: bool,
    pub server_capabilities: ServerCapabilities,
}

pub fn compute_delta(base: &[u8], target: &[u8]) -> (Vec<u8>, Vec<u8>) {
    let prefix_len = base
        .iter()
        .zip(target.iter())
        .take_while(|(a, b)| a == b)
        .count();

    let max_suffix_base = base.len().saturating_sub(prefix_len);
    let max_suffix_target = target.len().saturating_sub(prefix_len);
    let suffix_len = base[prefix_len..]
        .iter()
        .rev()
        .zip(target[prefix_len..].iter().rev())
        .take_while(|(a, b)| a == b)
        .count()
        .min(max_suffix_base)
        .min(max_suffix_target);

    let changed_start = prefix_len;
    let changed_end_target = target.len().saturating_sub(suffix_len);
    let changed = &target[changed_start..changed_end_target];

    if changed.len() < target.len() {
        let mut delta = Vec::new();
        delta.extend_from_slice(&(prefix_len as u64).to_le_bytes());
        delta.extend_from_slice(&(suffix_len as u64).to_le_bytes());
        delta.extend_from_slice(&(target.len() as u64).to_le_bytes());
        delta.extend_from_slice(changed);
        (base.to_vec(), delta)
    } else {
        (base.to_vec(), target.to_vec())
    }
}

pub fn apply_delta(base: &[u8], delta: &[u8]) -> Vec<u8> {
    if delta.len() < 24 {
        return delta.to_vec();
    }
    let prefix_len = u64::from_le_bytes(delta[0..8].try_into().unwrap_or([0; 8])) as usize;
    let suffix_len = u64::from_le_bytes(delta[8..16].try_into().unwrap_or([0; 8])) as usize;
    let total_len = u64::from_le_bytes(delta[16..24].try_into().unwrap_or([0; 8])) as usize;
    let changed = &delta[24..];

    let mut result = Vec::with_capacity(total_len);
    result.extend_from_slice(&base[..prefix_len.min(base.len())]);
    result.extend_from_slice(changed);
    result.extend_from_slice(&base[base.len().saturating_sub(suffix_len)..]);
    result
}

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

    fn roundtrip<T: Serialize + for<'de> Deserialize<'de>>(val: &T) -> T {
        let json = serde_json::to_string(val).expect("serialize");
        serde_json::from_str(&json).expect("deserialize")
    }

    fn make_hash(hex: &str) -> HashProto {
        HashProto {
            value: hex.to_string(),
        }
    }

    fn make_patch(id: &str, op: &str, parents: &[&str]) -> PatchProto {
        PatchProto {
            id: make_hash(id),
            operation_type: op.to_string(),
            touch_set: vec![format!("file_{id}")],
            target_path: Some(format!("file_{id}")),
            payload: String::new(),
            parent_ids: parents.iter().map(|p| make_hash(p)).collect(),
            author: "alice".to_string(),
            message: format!("patch {id}"),
            timestamp: 1000,
        }
    }

    fn make_branch(name: &str, target: &str) -> BranchProto {
        BranchProto {
            name: name.to_string(),
            target_id: make_hash(target),
        }
    }

    #[test]
    fn test_handshake_roundtrip() {
        let req = HandshakeRequest {
            client_version: 1,
            client_name: "test".to_string(),
        };
        let rt: HandshakeRequest = roundtrip(&req);
        assert_eq!(rt.client_version, 1);
        assert_eq!(rt.client_name, "test");

        let resp = HandshakeResponse {
            server_version: 1,
            server_name: "hub".to_string(),
            compatible: true,
        };
        let rt: HandshakeResponse = roundtrip(&resp);
        assert!(rt.compatible);
    }

    #[test]
    fn test_auth_method_roundtrip() {
        let methods = vec![
            AuthMethod::None,
            AuthMethod::Signature {
                public_key: "pk".to_string(),
                signature: "sig".to_string(),
            },
            AuthMethod::Token("tok".to_string()),
        ];
        for m in &methods {
            let rt: AuthMethod = roundtrip(m);
            match (m, &rt) {
                (AuthMethod::None, AuthMethod::None) => {}
                (
                    AuthMethod::Signature {
                        public_key: a,
                        signature: b,
                    },
                    AuthMethod::Signature {
                        public_key: c,
                        signature: d,
                    },
                ) => {
                    assert_eq!(a, c);
                    assert_eq!(b, d);
                }
                (AuthMethod::Token(a), AuthMethod::Token(b)) => assert_eq!(a, b),
                _ => panic!("auth method mismatch"),
            }
        }
    }

    #[test]
    fn test_patch_proto_roundtrip() {
        let p = make_patch("a".repeat(64).as_str(), "Create", &[]);
        let rt: PatchProto = roundtrip(&p);
        assert_eq!(rt.operation_type, "Create");
        assert_eq!(rt.touch_set.len(), 1);
        assert!(rt.target_path.is_some());
        assert!(rt.parent_ids.is_empty());
        assert_eq!(rt.author, "alice");
    }

    #[test]
    fn test_patch_proto_with_parents() {
        let parent = "b".repeat(64);
        let p = make_patch("a".repeat(64).as_str(), "Modify", &[&parent]);
        let rt: PatchProto = roundtrip(&p);
        assert_eq!(rt.parent_ids.len(), 1);
        assert_eq!(hash_to_hex(&rt.parent_ids[0]), parent);
    }

    #[test]
    fn test_push_request_roundtrip() {
        let req = PushRequest {
            repo_id: "my-repo".to_string(),
            patches: vec![make_patch("a".repeat(64).as_str(), "Create", &[])],
            branches: vec![make_branch("main", "a".repeat(64).as_str())],
            blobs: vec![BlobRef {
                hash: make_hash("deadbeef"),
                data: "aGVsbG8=".to_string(),
            }],
            signature: Some(vec![1u8; 64]),
            known_branches: Some(vec![make_branch("main", "prev".repeat(32).as_str())]),
            force: true,
        };
        let rt: PushRequest = roundtrip(&req);
        assert_eq!(rt.repo_id, "my-repo");
        assert_eq!(rt.patches.len(), 1);
        assert_eq!(rt.branches.len(), 1);
        assert_eq!(rt.blobs.len(), 1);
        assert!(rt.signature.is_some());
        assert!(rt.known_branches.is_some());
        assert!(rt.force);
    }

    #[test]
    fn test_push_request_defaults() {
        let req = PushRequest {
            repo_id: "r".to_string(),
            patches: vec![],
            branches: vec![],
            blobs: vec![],
            signature: None,
            known_branches: None,
            force: false,
        };
        let json = serde_json::to_string(&req).unwrap();
        let rt: PushRequest = serde_json::from_str(&json).unwrap();
        assert!(rt.signature.is_none());
        assert!(rt.known_branches.is_none());
        assert!(!rt.force);
    }

    #[test]
    fn test_pull_request_roundtrip() {
        let req = PullRequest {
            repo_id: "r".to_string(),
            known_branches: vec![make_branch("main", "a".repeat(32).as_str())],
            max_depth: Some(10),
        };
        let rt: PullRequest = roundtrip(&req);
        assert_eq!(rt.max_depth, Some(10));

        let req2 = PullRequest {
            repo_id: "r".to_string(),
            known_branches: vec![],
            max_depth: None,
        };
        let rt2: PullRequest = roundtrip(&req2);
        assert!(rt2.max_depth.is_none());
    }

    #[test]
    fn test_pull_response_roundtrip() {
        let resp = PullResponse {
            success: true,
            error: None,
            patches: vec![make_patch("a".repeat(64).as_str(), "Create", &[])],
            branches: vec![make_branch("main", "a".repeat(64).as_str())],
            blobs: vec![BlobRef {
                hash: make_hash("abc"),
                data: "dGVzdA==".to_string(),
            }],
        };
        let rt: PullResponse = roundtrip(&resp);
        assert!(rt.success);
        assert_eq!(rt.patches.len(), 1);
        assert_eq!(rt.blobs.len(), 1);
    }

    #[test]
    fn test_pull_response_error() {
        let resp = PullResponse {
            success: false,
            error: Some("not found".to_string()),
            patches: vec![],
            branches: vec![],
            blobs: vec![],
        };
        let rt: PullResponse = roundtrip(&resp);
        assert!(!rt.success);
        assert_eq!(rt.error, Some("not found".to_string()));
    }

    #[test]
    fn test_blob_ref_roundtrip() {
        let blob = BlobRef {
            hash: make_hash("cafebabe"),
            data: "SGVsbG8gV29ybGQ=".to_string(),
        };
        let rt: BlobRef = roundtrip(&blob);
        assert_eq!(rt.data, "SGVsbG8gV29ybGQ=");
    }

    #[test]
    fn test_hash_helpers() {
        let h = hex_to_hash("abcdef1234");
        assert_eq!(hash_to_hex(&h), "abcdef1234");
    }

    #[test]
    fn test_canonical_push_bytes_deterministic() {
        let req = PushRequest {
            repo_id: "test".to_string(),
            patches: vec![make_patch("a".repeat(64).as_str(), "Create", &[])],
            branches: vec![make_branch("main", "a".repeat(64).as_str())],
            blobs: vec![],
            signature: None,
            known_branches: None,
            force: false,
        };
        let b1 = canonical_push_bytes(&req);
        let b2 = canonical_push_bytes(&req);
        assert_eq!(b1, b2);
    }

    #[test]
    fn test_canonical_push_bytes_different_repos() {
        let make_req = |repo: &str| PushRequest {
            repo_id: repo.to_string(),
            patches: vec![],
            branches: vec![],
            blobs: vec![],
            signature: None,
            known_branches: None,
            force: false,
        };
        let b1 = canonical_push_bytes(&make_req("repo-a"));
        let b2 = canonical_push_bytes(&make_req("repo-b"));
        assert_ne!(b1, b2);
    }

    #[test]
    fn test_repo_info_response_roundtrip() {
        let resp = RepoInfoResponse {
            repo_id: "my-repo".to_string(),
            patch_count: 42,
            branches: vec![make_branch("main", "a".repeat(32).as_str())],
            success: true,
            error: None,
        };
        let rt: RepoInfoResponse = roundtrip(&resp);
        assert_eq!(rt.patch_count, 42);
        assert!(rt.success);

        let err = RepoInfoResponse {
            repo_id: "x".to_string(),
            patch_count: 0,
            branches: vec![],
            success: false,
            error: Some("not found".to_string()),
        };
        let rt2: RepoInfoResponse = roundtrip(&err);
        assert!(!rt2.success);
        assert_eq!(rt2.error, Some("not found".to_string()));
    }

    #[test]
    fn test_list_repos_response_roundtrip() {
        let resp = ListReposResponse {
            repo_ids: vec!["a".to_string(), "b".to_string()],
        };
        let rt: ListReposResponse = roundtrip(&resp);
        assert_eq!(rt.repo_ids, vec!["a", "b"]);
    }

    #[test]
    fn test_push_response_roundtrip() {
        let resp = PushResponse {
            success: true,
            error: None,
            existing_patches: vec![make_hash("abc"), make_hash("def")],
        };
        let rt: PushResponse = roundtrip(&resp);
        assert_eq!(rt.existing_patches.len(), 2);
    }

    #[test]
    fn test_delta_roundtrip() {
        let base = b"Hello, World!";
        let target = b"Hello, Rust!";
        let (_base_copy, delta) = compute_delta(base, target);
        let result = apply_delta(base, &delta);
        assert_eq!(result, target);
    }

    #[test]
    fn test_delta_no_change() {
        let base = b"identical data here";
        let target = b"identical data here";
        let (_base_copy, delta) = compute_delta(base, target);
        assert!(delta.len() < target.len() + 24);
        let result = apply_delta(base, &delta);
        assert_eq!(result, target);
    }

    #[test]
    fn test_delta_completely_different() {
        let base = b"AAAA";
        let target = b"BBBB";
        let (_base_copy, delta) = compute_delta(base, target);
        let result = apply_delta(base, &delta);
        assert_eq!(result, target);
    }

    #[test]
    fn test_pull_request_v2_roundtrip() {
        let req = PullRequestV2 {
            repo_id: "my-repo".to_string(),
            known_branches: vec![make_branch("main", "a".repeat(32).as_str())],
            max_depth: Some(10),
            known_blob_hashes: vec![make_hash("deadbeef")],
            capabilities: ClientCapabilities {
                supports_delta: true,
                supports_compression: true,
                max_blob_size: 1024 * 1024,
            },
        };
        let rt: PullRequestV2 = roundtrip(&req);
        assert_eq!(rt.repo_id, "my-repo");
        assert_eq!(rt.max_depth, Some(10));
        assert!(rt.capabilities.supports_delta);
        assert_eq!(rt.known_blob_hashes.len(), 1);
    }

    #[test]
    fn test_handshake_v2_roundtrip() {
        let req = HandshakeRequestV2 {
            client_version: 2,
            client_name: "suture-cli".to_string(),
            capabilities: ClientCapabilities {
                supports_delta: true,
                supports_compression: false,
                max_blob_size: 512 * 1024,
            },
        };
        let rt: HandshakeRequestV2 = roundtrip(&req);
        assert_eq!(rt.client_version, 2);
        assert!(rt.capabilities.supports_delta);
        assert!(!rt.capabilities.supports_compression);

        let resp = HandshakeResponseV2 {
            server_version: 2,
            server_name: "suture-hub".to_string(),
            compatible: true,
            server_capabilities: ServerCapabilities {
                supports_delta: true,
                supports_compression: true,
                max_blob_size: 10 * 1024 * 1024,
                protocol_versions: vec![1, 2],
            },
        };
        let rt: HandshakeResponseV2 = roundtrip(&resp);
        assert!(rt.compatible);
        assert_eq!(rt.server_capabilities.protocol_versions, vec![1, 2]);
    }

    #[test]
    fn test_client_capabilities_roundtrip() {
        let caps = ClientCapabilities {
            supports_delta: false,
            supports_compression: true,
            max_blob_size: 999,
        };
        let rt: ClientCapabilities = roundtrip(&caps);
        assert!(!rt.supports_delta);
        assert!(rt.supports_compression);
        assert_eq!(rt.max_blob_size, 999);
    }

    #[test]
    fn test_blob_delta_roundtrip() {
        let delta = BlobDelta {
            base_hash: make_hash("aaa"),
            target_hash: make_hash("bbb"),
            encoding: DeltaEncoding::BinaryPatch,
            delta_data: "ZGF0YQ==".to_string(),
        };
        let rt: BlobDelta = roundtrip(&delta);
        assert_eq!(hash_to_hex(&rt.base_hash), "aaa");
        assert_eq!(hash_to_hex(&rt.target_hash), "bbb");
        assert!(matches!(rt.encoding, DeltaEncoding::BinaryPatch));
        assert_eq!(rt.delta_data, "ZGF0YQ==");

        let full = BlobDelta {
            base_hash: make_hash("aaa"),
            target_hash: make_hash("bbb"),
            encoding: DeltaEncoding::FullBlob,
            delta_data: "Ynl0ZXM=".to_string(),
        };
        let rt: BlobDelta = roundtrip(&full);
        assert!(matches!(rt.encoding, DeltaEncoding::FullBlob));
    }
}