git-internal 0.8.4

High-performance Rust library for Git internal objects, Pack files, and AI-assisted development objects (Intent, Plan, Task, Run, Evidence, Decision) with delta compression, streaming I/O, and smart protocol support.
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
//! Core Git protocol implementation
//!
//! This module provides the main `GitProtocol` struct and `RepositoryAccess` trait
//! that form the core interface of the git-internal library.
use std::{collections::HashMap, str::FromStr};

use async_trait::async_trait;
use bytes::{BufMut, Bytes, BytesMut};
use futures::stream::StreamExt;

use crate::{
    hash::ObjectHash,
    internal::object::ObjectTrait,
    protocol::{
        smart::SmartProtocol,
        types::{Capability, ProtocolError, ProtocolStream, ServiceType, SideBand},
    },
};

/// Repository access trait for storage operations
///
/// This trait only handles storage-level operations, not Git protocol details.
/// The git-internal library handles all Git protocol formatting and parsing.
#[async_trait]
pub trait RepositoryAccess: Send + Sync + Clone {
    /// Get repository references as raw (name, hash) pairs
    async fn get_repository_refs(&self) -> Result<Vec<(String, String)>, ProtocolError>;

    /// Check if an object exists in the repository
    async fn has_object(&self, object_hash: &str) -> Result<bool, ProtocolError>;

    /// Get raw object data by hash
    async fn get_object(&self, object_hash: &str) -> Result<Vec<u8>, ProtocolError>;

    /// Store pack data in the repository
    async fn store_pack_data(&self, pack_data: &[u8]) -> Result<(), ProtocolError>;

    /// Update a single reference
    async fn update_reference(
        &self,
        ref_name: &str,
        old_hash: Option<&str>,
        new_hash: &str,
    ) -> Result<(), ProtocolError>;

    /// Get objects needed for pack generation
    async fn get_objects_for_pack(
        &self,
        wants: &[String],
        haves: &[String],
    ) -> Result<Vec<String>, ProtocolError>;

    /// Check if repository has a default branch
    async fn has_default_branch(&self) -> Result<bool, ProtocolError>;

    /// Post-receive hook after successful push
    async fn post_receive_hook(&self) -> Result<(), ProtocolError>;

    /// Get blob data by hash
    ///
    /// Default implementation parses the object data using the internal object module.
    /// Override this method if you need custom blob handling logic.
    async fn get_blob(
        &self,
        object_hash: &str,
    ) -> Result<crate::internal::object::blob::Blob, ProtocolError> {
        let data = self.get_object(object_hash).await?;
        let hash = ObjectHash::from_str(object_hash)
            .map_err(|e| ProtocolError::repository_error(format!("Invalid hash format: {e}")))?;

        crate::internal::object::blob::Blob::from_bytes(&data, hash)
            .map_err(|e| ProtocolError::repository_error(format!("Failed to parse blob: {e}")))
    }

    /// Get commit data by hash
    ///
    /// Default implementation parses the object data using the internal object module.
    /// Override this method if you need custom commit handling logic.
    async fn get_commit(
        &self,
        commit_hash: &str,
    ) -> Result<crate::internal::object::commit::Commit, ProtocolError> {
        let data = self.get_object(commit_hash).await?;
        let hash = ObjectHash::from_str(commit_hash)
            .map_err(|e| ProtocolError::repository_error(format!("Invalid hash format: {e}")))?;

        crate::internal::object::commit::Commit::from_bytes(&data, hash)
            .map_err(|e| ProtocolError::repository_error(format!("Failed to parse commit: {e}")))
    }

    /// Get tree data by hash
    ///
    /// Default implementation parses the object data using the internal object module.
    /// Override this method if you need custom tree handling logic.
    async fn get_tree(
        &self,
        tree_hash: &str,
    ) -> Result<crate::internal::object::tree::Tree, ProtocolError> {
        let data = self.get_object(tree_hash).await?;
        let hash = ObjectHash::from_str(tree_hash)
            .map_err(|e| ProtocolError::repository_error(format!("Invalid hash format: {e}")))?;

        crate::internal::object::tree::Tree::from_bytes(&data, hash)
            .map_err(|e| ProtocolError::repository_error(format!("Failed to parse tree: {e}")))
    }

    /// Check if a commit exists
    ///
    /// Default implementation checks object existence and validates it's a commit.
    /// Override this method if you have more efficient commit existence checking.
    async fn commit_exists(&self, commit_hash: &str) -> Result<bool, ProtocolError> {
        match self.has_object(commit_hash).await {
            Ok(exists) => {
                if !exists {
                    return Ok(false);
                }

                // Verify it's actually a commit by trying to parse it
                match self.get_commit(commit_hash).await {
                    Ok(_) => Ok(true),
                    Err(_) => Ok(false), // Object exists but is not a valid commit
                }
            }
            Err(e) => Err(e),
        }
    }

    /// Handle pack objects after unpacking
    ///
    /// Default implementation stores each object individually using store_pack_data.
    /// Override this method if you need batch processing or custom storage logic.
    async fn handle_pack_objects(
        &self,
        commits: Vec<crate::internal::object::commit::Commit>,
        trees: Vec<crate::internal::object::tree::Tree>,
        blobs: Vec<crate::internal::object::blob::Blob>,
    ) -> Result<(), ProtocolError> {
        // Store blobs
        for blob in blobs {
            let data = blob.to_data().map_err(|e| {
                ProtocolError::repository_error(format!("Failed to serialize blob: {e}"))
            })?;
            self.store_pack_data(&data).await.map_err(|e| {
                ProtocolError::repository_error(format!("Failed to store blob {}: {}", blob.id, e))
            })?;
        }

        // Store trees
        for tree in trees {
            let data = tree.to_data().map_err(|e| {
                ProtocolError::repository_error(format!("Failed to serialize tree: {e}"))
            })?;
            self.store_pack_data(&data).await.map_err(|e| {
                ProtocolError::repository_error(format!("Failed to store tree {}: {}", tree.id, e))
            })?;
        }

        // Store commits
        for commit in commits {
            let data = commit.to_data().map_err(|e| {
                ProtocolError::repository_error(format!("Failed to serialize commit: {e}"))
            })?;
            self.store_pack_data(&data).await.map_err(|e| {
                ProtocolError::repository_error(format!(
                    "Failed to store commit {}: {}",
                    commit.id, e
                ))
            })?;
        }

        Ok(())
    }
}

/// Authentication service trait
#[async_trait]
pub trait AuthenticationService: Send + Sync {
    /// Authenticate HTTP request
    async fn authenticate_http(
        &self,
        headers: &std::collections::HashMap<String, String>,
    ) -> Result<(), ProtocolError>;

    /// Authenticate SSH public key
    async fn authenticate_ssh(
        &self,
        username: &str,
        public_key: &[u8],
    ) -> Result<(), ProtocolError>;
}

/// Transport-agnostic Git smart protocol handler
/// Main Git protocol handler
///
/// This struct provides the core Git protocol implementation that works
/// across HTTP, SSH, and other transports. It uses SmartProtocol internally
/// to handle all Git protocol details.
pub struct GitProtocol<R: RepositoryAccess, A: AuthenticationService> {
    smart_protocol: SmartProtocol<R, A>,
}

impl<R: RepositoryAccess, A: AuthenticationService> GitProtocol<R, A> {
    /// Create a new GitProtocol instance
    pub fn new(repo_access: R, auth_service: A) -> Self {
        Self {
            smart_protocol: SmartProtocol::new(
                super::types::TransportProtocol::Http,
                repo_access,
                auth_service,
            ),
        }
    }

    /// Authenticate HTTP request before serving Git operations
    pub async fn authenticate_http(
        &self,
        headers: &HashMap<String, String>,
    ) -> Result<(), ProtocolError> {
        self.smart_protocol.authenticate_http(headers).await
    }

    /// Authenticate SSH session before serving Git operations
    pub async fn authenticate_ssh(
        &self,
        username: &str,
        public_key: &[u8],
    ) -> Result<(), ProtocolError> {
        self.smart_protocol
            .authenticate_ssh(username, public_key)
            .await
    }

    /// Set transport protocol (Http, Ssh, etc.)
    pub fn set_transport(&mut self, protocol: super::types::TransportProtocol) {
        self.smart_protocol.set_transport_protocol(protocol);
    }

    /// Handle git info-refs request
    pub async fn info_refs(&self, service: &str) -> Result<Vec<u8>, ProtocolError> {
        let service_type = match service {
            "git-upload-pack" => ServiceType::UploadPack,
            "git-receive-pack" => ServiceType::ReceivePack,
            _ => return Err(ProtocolError::invalid_service(service)),
        };

        let bytes = self.smart_protocol.git_info_refs(service_type).await?;
        Ok(bytes.to_vec())
    }

    /// Handle git-upload-pack request (for clone/fetch)
    pub async fn upload_pack(
        &mut self,
        request_data: &[u8],
    ) -> Result<ProtocolStream, ProtocolError> {
        const SIDE_BAND_PACKET_LEN: usize = 1000;
        const SIDE_BAND_64K_PACKET_LEN: usize = 65520;
        const SIDE_BAND_HEADER_LEN: usize = 5; // 4-byte length + 1-byte band

        let request_bytes = bytes::Bytes::from(request_data.to_vec());
        let (pack_stream, protocol_buf) =
            self.smart_protocol.git_upload_pack(request_bytes).await?;
        let ack_bytes = protocol_buf.freeze();

        let ack_stream: ProtocolStream = if ack_bytes.is_empty() {
            Box::pin(futures::stream::empty::<Result<Bytes, ProtocolError>>())
        } else {
            Box::pin(futures::stream::once(async move { Ok(ack_bytes) }))
        };

        let sideband_max = if self
            .smart_protocol
            .capabilities
            .contains(&Capability::SideBand64k)
        {
            Some(SIDE_BAND_64K_PACKET_LEN - SIDE_BAND_HEADER_LEN)
        } else if self
            .smart_protocol
            .capabilities
            .contains(&Capability::SideBand)
        {
            Some(SIDE_BAND_PACKET_LEN - SIDE_BAND_HEADER_LEN)
        } else {
            None
        };

        let data_stream: ProtocolStream = if let Some(max_payload) = sideband_max {
            let stream = pack_stream.flat_map(move |chunk| {
                let packets = build_side_band_packets(&chunk, max_payload);
                futures::stream::iter(packets.into_iter().map(Ok))
            });
            let stream = stream.chain(futures::stream::once(async {
                Ok(Bytes::from_static(b"0000"))
            }));
            Box::pin(stream)
        } else {
            Box::pin(pack_stream.map(|data| Ok(Bytes::from(data))))
        };

        Ok(Box::pin(ack_stream.chain(data_stream)))
    }

    /// Handle git-receive-pack request (for push)
    pub async fn receive_pack(
        &mut self,
        request_stream: ProtocolStream,
    ) -> Result<ProtocolStream, ProtocolError> {
        const SIDE_BAND_PACKET_LEN: usize = 1000;
        const SIDE_BAND_64K_PACKET_LEN: usize = 65520;
        const SIDE_BAND_HEADER_LEN: usize = 5; // 4-byte length + 1-byte band

        let result_bytes = self
            .smart_protocol
            .git_receive_pack_stream(request_stream)
            .await?;

        let sideband_max = if self
            .smart_protocol
            .capabilities
            .contains(&Capability::SideBand64k)
        {
            Some(SIDE_BAND_64K_PACKET_LEN - SIDE_BAND_HEADER_LEN)
        } else if self
            .smart_protocol
            .capabilities
            .contains(&Capability::SideBand)
        {
            Some(SIDE_BAND_PACKET_LEN - SIDE_BAND_HEADER_LEN)
        } else {
            None
        };

        // Wrap report-status in side-band if negotiated by the client.
        if let Some(max_payload) = sideband_max {
            let packets = build_side_band_packets(result_bytes.as_ref(), max_payload);
            let stream = futures::stream::iter(packets.into_iter().map(Ok)).chain(
                futures::stream::once(async { Ok(Bytes::from_static(b"0000")) }),
            );
            Ok(Box::pin(stream))
        } else {
            // Return the report status as a single-chunk stream
            Ok(Box::pin(futures::stream::once(async { Ok(result_bytes) })))
        }
    }
}

fn build_side_band_packets(chunk: &[u8], max_payload: usize) -> Vec<Bytes> {
    if chunk.is_empty() {
        return Vec::new();
    }

    let mut out = Vec::new();
    let mut offset = 0;

    while offset < chunk.len() {
        let end = (offset + max_payload).min(chunk.len());
        let payload = &chunk[offset..end];
        let length = payload.len() + 5; // 4-byte length + 1-byte band
        let mut pkt = BytesMut::with_capacity(length);
        pkt.put(Bytes::from(format!("{length:04x}")));
        pkt.put_u8(SideBand::PackfileData.value());
        pkt.put(payload);
        out.push(pkt.freeze());
        offset = end;
    }

    out
}

#[cfg(test)]
mod tests {
    use async_trait::async_trait;
    use bytes::{Bytes, BytesMut};
    use futures::StreamExt;

    use super::*;
    use crate::{
        hash::{HashKind, set_hash_kind_for_test},
        internal::object::{
            blob::Blob,
            commit::Commit,
            signature::{Signature, SignatureType},
            tree::{Tree, TreeItem, TreeItemMode},
        },
        protocol::{types::TransportProtocol, utils},
    };

    /// Simple mock repository that serves fixed refs and echoes wants.
    #[derive(Clone)]
    struct MockRepo {
        refs: Vec<(String, String)>,
    }

    #[async_trait]
    impl RepositoryAccess for MockRepo {
        async fn get_repository_refs(&self) -> Result<Vec<(String, String)>, ProtocolError> {
            Ok(self.refs.clone())
        }
        async fn has_object(&self, _object_hash: &str) -> Result<bool, ProtocolError> {
            Ok(false)
        }
        async fn get_object(&self, _object_hash: &str) -> Result<Vec<u8>, ProtocolError> {
            Ok(Vec::new())
        }
        async fn store_pack_data(&self, _pack_data: &[u8]) -> Result<(), ProtocolError> {
            Ok(())
        }
        async fn update_reference(
            &self,
            _ref_name: &str,
            _old_hash: Option<&str>,
            _new_hash: &str,
        ) -> Result<(), ProtocolError> {
            Ok(())
        }
        async fn get_objects_for_pack(
            &self,
            wants: &[String],
            _haves: &[String],
        ) -> Result<Vec<String>, ProtocolError> {
            Ok(wants.to_vec())
        }
        async fn has_default_branch(&self) -> Result<bool, ProtocolError> {
            Ok(false)
        }
        async fn post_receive_hook(&self) -> Result<(), ProtocolError> {
            Ok(())
        }
    }

    /// No-op auth service for tests.
    struct MockAuth;
    #[async_trait]
    impl AuthenticationService for MockAuth {
        async fn authenticate_http(
            &self,
            _headers: &std::collections::HashMap<String, String>,
        ) -> Result<(), ProtocolError> {
            Ok(())
        }
        async fn authenticate_ssh(
            &self,
            _username: &str,
            _public_key: &[u8],
        ) -> Result<(), ProtocolError> {
            Ok(())
        }
    }

    /// Convenience builder for GitProtocol with mock repo/auth.
    fn make_protocol() -> GitProtocol<MockRepo, MockAuth> {
        GitProtocol::new(
            MockRepo {
                refs: vec![
                    (
                        "refs/heads/main".to_string(),
                        ObjectHash::default().to_string(),
                    ),
                    ("HEAD".to_string(), ObjectHash::default().to_string()),
                ],
            },
            MockAuth,
        )
    }

    /// Mock repo that serves a single commit, tree, and blobs.
    #[derive(Clone)]
    struct SideBandRepo {
        commit: Commit,
        tree: Tree,
        blobs: Vec<Blob>,
    }
    #[async_trait]
    impl RepositoryAccess for SideBandRepo {
        async fn get_repository_refs(&self) -> Result<Vec<(String, String)>, ProtocolError> {
            Ok(vec![(
                "refs/heads/main".to_string(),
                self.commit.id.to_string(),
            )])
        }

        async fn has_object(&self, object_hash: &str) -> Result<bool, ProtocolError> {
            let known = object_hash == self.commit.id.to_string()
                || object_hash == self.tree.id.to_string()
                || self.blobs.iter().any(|b| b.id.to_string() == object_hash);
            Ok(known)
        }

        async fn get_object(&self, _object_hash: &str) -> Result<Vec<u8>, ProtocolError> {
            Ok(Vec::new())
        }

        async fn store_pack_data(&self, _pack_data: &[u8]) -> Result<(), ProtocolError> {
            Ok(())
        }

        async fn update_reference(
            &self,
            _ref_name: &str,
            _old_hash: Option<&str>,
            _new_hash: &str,
        ) -> Result<(), ProtocolError> {
            Ok(())
        }

        async fn get_objects_for_pack(
            &self,
            _wants: &[String],
            _haves: &[String],
        ) -> Result<Vec<String>, ProtocolError> {
            Ok(Vec::new())
        }

        async fn has_default_branch(&self) -> Result<bool, ProtocolError> {
            Ok(true)
        }

        async fn post_receive_hook(&self) -> Result<(), ProtocolError> {
            Ok(())
        }

        async fn get_commit(&self, commit_hash: &str) -> Result<Commit, ProtocolError> {
            if commit_hash == self.commit.id.to_string() {
                Ok(self.commit.clone())
            } else {
                Err(ProtocolError::ObjectNotFound(commit_hash.to_string()))
            }
        }

        async fn get_tree(&self, tree_hash: &str) -> Result<Tree, ProtocolError> {
            if tree_hash == self.tree.id.to_string() {
                Ok(self.tree.clone())
            } else {
                Err(ProtocolError::ObjectNotFound(tree_hash.to_string()))
            }
        }

        async fn get_blob(&self, blob_hash: &str) -> Result<Blob, ProtocolError> {
            self.blobs
                .iter()
                .find(|b| b.id.to_string() == blob_hash)
                .cloned()
                .ok_or_else(|| ProtocolError::ObjectNotFound(blob_hash.to_string()))
        }
    }

    fn build_repo_with_objects() -> (SideBandRepo, Commit) {
        let blob = Blob::from_content("hello");
        let item = TreeItem::new(TreeItemMode::Blob, blob.id, "hello.txt".to_string());
        let tree = Tree::from_tree_items(vec![item]).unwrap();
        let author = Signature::new(
            SignatureType::Author,
            "tester".to_string(),
            "tester@example.com".to_string(),
        );
        let committer = Signature::new(
            SignatureType::Committer,
            "tester".to_string(),
            "tester@example.com".to_string(),
        );
        let commit = Commit::new(author, committer, tree.id, vec![], "init commit");

        let repo = SideBandRepo {
            commit: commit.clone(),
            tree,
            blobs: vec![blob],
        };

        (repo, commit)
    }

    /// upload-pack should emit NAK before sending pack data.
    #[tokio::test]
    async fn upload_pack_emits_ack_before_pack() {
        let _guard = set_hash_kind_for_test(HashKind::Sha1);
        let (repo, commit) = build_repo_with_objects();
        let mut proto = GitProtocol::new(repo, MockAuth);
        let mut request = BytesMut::new();
        utils::add_pkt_line_string(&mut request, format!("want {}\n", commit.id));
        utils::add_pkt_line_string(&mut request, "done\n".to_string());

        let mut stream = proto.upload_pack(&request).await.expect("upload-pack");
        let mut out = BytesMut::new();
        while let Some(chunk) = stream.next().await {
            out.extend_from_slice(&chunk.expect("stream chunk"));
        }

        let mut out_bytes = out.freeze();
        let (_len, line) = utils::read_pkt_line(&mut out_bytes);
        assert_eq!(line, Bytes::from_static(b"NAK\n"));
        assert!(
            out_bytes.as_ref().starts_with(b"PACK"),
            "pack should follow ack"
        );
    }

    /// upload-pack with side-band should wrap pack data in side-band packets.
    #[tokio::test]
    async fn upload_pack_sideband_frames_pack() {
        let _guard = set_hash_kind_for_test(HashKind::Sha1);
        let (repo, commit) = build_repo_with_objects();

        let mut proto = GitProtocol::new(repo, MockAuth);
        let mut request = BytesMut::new();
        utils::add_pkt_line_string(&mut request, format!("want {} side-band-64k\n", commit.id));
        utils::add_pkt_line_string(&mut request, "done\n".to_string());

        let mut stream = proto.upload_pack(&request).await.expect("upload-pack");
        let mut out = BytesMut::new();
        while let Some(chunk) = stream.next().await {
            out.extend_from_slice(&chunk.expect("stream chunk"));
        }

        let mut out_bytes = out.freeze();
        let (_len, line) = utils::read_pkt_line(&mut out_bytes);
        assert_eq!(line, Bytes::from_static(b"NAK\n"));

        let raw = out_bytes.as_ref();
        assert!(raw.len() > 9, "side-band packet should include PACK header");
        let len_hex = std::str::from_utf8(&raw[..4]).expect("hex length");
        let pkt_len = usize::from_str_radix(len_hex, 16).expect("parse length");
        assert!(pkt_len > 5, "side-band packet should contain data");
        assert_eq!(raw[4], SideBand::PackfileData.value());
        assert_eq!(&raw[5..9], b"PACK");
        assert!(raw.ends_with(b"0000"), "side-band stream should flush");
    }

    /// info_refs should include refs, capabilities, and object-format.
    #[tokio::test]
    async fn info_refs_includes_refs_and_caps() {
        let proto = make_protocol();
        let bytes = proto.info_refs("git-upload-pack").await.expect("info_refs");
        let text = String::from_utf8(bytes).expect("utf8");
        assert!(text.contains("refs/heads/main"));
        assert!(text.contains("capabilities"));
        assert!(text.contains("object-format"));
    }

    /// Invalid service name should return InvalidService.
    #[tokio::test]
    async fn info_refs_invalid_service_errors() {
        let proto = make_protocol();
        let err = proto.info_refs("git-invalid").await.unwrap_err();
        assert!(matches!(err, ProtocolError::InvalidService(_)));
    }

    /// Ensure set_transport can switch protocols without panic.
    #[tokio::test]
    async fn can_switch_transport() {
        let mut proto = make_protocol();
        proto.set_transport(TransportProtocol::Ssh);
        // if set_transport did not panic, we consider this path covered
    }

    /// Wire hash kind expects SHA1 length; providing SHA256 refs should error.
    #[tokio::test]
    async fn info_refs_hash_length_mismatch_errors() {
        let proto = GitProtocol::new(
            MockRepo {
                refs: vec![(
                    "refs/heads/main".to_string(),
                    "f".repeat(HashKind::Sha256.hex_len()),
                )],
            },
            MockAuth,
        );
        let err = proto.info_refs("git-upload-pack").await.unwrap_err();
        assert!(matches!(err, ProtocolError::InvalidRequest(_)));
    }
}