alkgit 0.1.0

Git smart protocol for the alk family: pkt-line substrates, protocol V2 serving (upload-pack/receive-pack), producer/consumer halves on alkcall channels, and the backend seam traits — the shipped alkstore+alkblobs composition is the alkgit-substrate crate (ADR-010/025)
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
//! The V0 push wire surfaces (ADR-013 §1–2): the receive-pack ref
//! advertisement both substrates emit, capture-exact against
//! push-captures.md §Advertisement.
//!
//! Push is V0-framed on every door by upstream design — `git push`
//! never speaks protocol V2 (`protocol.version=2` does not apply, ADR-013
//! §1), so this module is the push counterpart of [`crate::v2`]: the
//! same substrate-agnostic [`PktLineWriter`] surface (the duplex
//! session and the stateless response both implement it, so no
//! duplex- or stateless-specific type appears in the machine's
//! signature), the same pure-protocol posture.
//!
//! - **The ref advertisement** ([`advertise_v0`]): a V0-shaped ref
//!   list — capabilities ride **NUL-attached on the FIRST ref line**
//!   (`<oid> <ref>\0<caps>`), remaining ref lines are bare
//!   (`<oid> <ref>`), the response is flush-terminated. The
//!   `capabilities^{}` zero-id sentinel line
//!   (`<zero-oid> capabilities^{}\0<caps>`) replaces the ref lines
//!   **only** when the repo has no refs: git rejects a bare capability
//!   dump and rejects a trailing sentinel when refs exist
//!   (push-captures.md §Advertisement) — exactly one of {ref lines,
//!   sentinel}, never both, never neither. The caps ride the first
//!   emitted line whatever it is (the sentinel is the empty repo's
//!   first ref line — the bare shape is the dump git rejects).
//! - **The served set** (honest per ADR-003 — exactly what we serve):
//!   [`PUSH_SERVED_CAPABILITIES`] — `report-status report-status-v2
//!   delete-refs side-band-64k atomic ofs-delta object-format=sha1` +
//!   `agent=alkgit/<crate version>`. **`quiet` is not advertised** (a
//!   client-side preference whose only server duty is suppressing
//!   progress chatter we never send — ADR-013 §2). **`push-options` is
//!   advertised only under the gate flag** (ADR-013 §11: the assembler
//!   enables it; default off in v1 — the gate is additive to open later
//!   as a value change). Everything else (`push-cert`, shallow-style
//!   caps) is declined by omission. Under the `sha256` feature the
//!   additional `object-format=sha256` token is emitted after the
//!   pinned default (OQ-05's passthrough policy, mirroring the V2
//!   advertisement).
//! - **The ref cap, fail-closed** (ADR-009 + review 001 N-1): the
//!   listed set exceeding [`Limits::max_advertisement_refs`] is a
//!   session error, never a silent truncation — a partial ref list is
//!   the worst failure mode an advertisement can have (the CAS input).
//!   The check precedes the first written line: no partial list can be
//!   emitted.
//! - **The ref data**: the caller's
//!   [`list_refs`](crate::GitRefs::list_refs) rows projected to
//!   oid+name (peeled tags and symref targets are ls-refs-arg data —
//!   the seam's projection rule). **No-oid ref rows are filtered** (the
//!   unborn-HEAD symref row has no oid to print — a V0 advertisement
//!   line has no symref shape; the POC's `filtered_head` posture; the
//!   OQ-19 rider (a) covers the ls-refs side, this covers the push
//!   side). If the filter empties the set the sentinel is the emission,
//!   never a bare capability dump.
//! - **The substrates' shapes**: the emission is pure wire over the
//!   listed refs (no backend call lives here at all — the listing is
//!   the caller's). The **duplex** shape is this emission with no
//!   service prefix — the server speaks first (no version negotiation
//!   exists on the push path, ADR-013 §1); the **stateless GET** shape
//!   wraps it with the smart prefix ([`crate::serve_stateless_advertisement`]
//!   — the service prefix is the stateless wrapper's, not the
//!   machine's, exactly as the V2 wrapper does).
//! - **The status report** ([`write_status_report`], ADR-013 §8):
//!   the response the push machine emits after the CAS — `unpack
//!   ok|ng <reason>`, then per-ref `ok <ref>` / `ng <ref> <reason>` in
//!   request order, an inner flush terminating the report section,
//!   then the terminating flush. The client's `side-band-64k`
//!   selection selects the framing: with it, the report rides band-1
//!   chunks whose payload is *itself* pkt-line-framed (the inner
//!   lines and the inner flush ride inside the band — a report sent
//!   unwrapped when sideband was selected aborts real clients,
//!   observed live); without it, bare pkt-lines to the single flush.
//!   Crate-internal (no public re-export): the substrate owns the
//!   framing (ADR-005), so the machine cannot get it wrong.

use gix_hash::{Kind, ObjectId};
use gix_packetline::async_io::encode;

use crate::limits::Limits;
use crate::seam::{RefLine, RefOutcome};
use crate::substrate::SubstrateError;
use crate::v2::PktLineWriter;

/// The honest V0 push served set (ADR-013 §2): exactly what the wire
/// layer serves — nothing unimplemented advertised. `quiet` is absent
/// by decision (a client-side preference; ADR-013 §2), `push-options`
/// rides the gate (ADR-013 §11, appended when the assembler enables
/// it), and `agent=alkgit/<crate version>` appends per the upstream
/// agent convention.
pub const PUSH_SERVED_CAPABILITIES: &[&str] = &[
    "report-status",
    "report-status-v2",
    "delete-refs",
    "side-band-64k",
    "atomic",
    "ofs-delta",
    "object-format=sha1",
];

/// The agent token — `agent=alkgit/<crate version>` (ADR-013 §2).
const AGENT_CAPABILITY: &str = concat!(
    "agent=",
    env!("CARGO_PKG_NAME"),
    "/",
    env!("CARGO_PKG_VERSION")
);

/// The NUL-attached capability string the advertisement carries on its
/// first emitted line (the set joined with spaces, gate and feature
/// riders applied, agent last — ADR-013 §2, ADR-013 §11, OQ-05).
pub(crate) fn capabilities_text(push_options_negotiated: bool) -> String {
    let mut tokens: Vec<&str> = PUSH_SERVED_CAPABILITIES.to_vec();
    if push_options_negotiated {
        tokens.push("push-options");
    }
    #[cfg(feature = "sha256")]
    tokens.push("object-format=sha256");
    tokens.push(AGENT_CAPABILITY);
    tokens.join(" ")
}

/// The zero-oid of the advertisement's object format (the
/// `capabilities^{}` sentinel's oid). sha1 is the pinned default
/// (OQ-05).
fn zero_oid_hex() -> String {
    ObjectId::null(Kind::Sha1).to_string()
}

/// Writes the V0 push ref advertisement (ADR-013 §2), capture-exact
/// against push-captures.md §Advertisement: capabilities
/// NUL-attached on the first emitted ref line, remaining ref lines
/// bare, flush-terminated; the `capabilities^{}` sentinel with the caps
/// NUL-attached replaces the ref lines exactly when the listed set
/// (after the no-oid filter) is empty.
///
/// `refs` is the backend's [`list_refs`](crate::GitRefs::list_refs)
/// result — the full set; the machine projects each row to oid+name and
/// filters the no-oid rows (the unborn-HEAD symref row has no oid to
/// print). The ref cap ([`Limits::max_advertisement_refs`]) precedes
/// the first written line: a breach errors the session with nothing
/// emitted — the fail-closed rule, never a silent truncation (ADR-009 +
/// review 001 N-1).
///
/// The duplex door calls this directly (the server speaks first, no
/// service prefix); the stateless GET door wraps it with the smart
/// prefix ([`crate::serve_stateless_advertisement`]).
///
/// Contract stamp: ADR-013 §1–2 (the V0 framing, the served set, the
/// sentinel rule); push-captures.md §Advertisement (the normative
/// shapes); ADR-003 (the honest set); ADR-007 (the ACL-first marker —
/// the caller's gate precedes any byte); ADR-009 + review 001 N-1 (the
/// fail-closed ref cap); core/w3-v0-advertisement.
pub async fn advertise_v0(
    writer: &mut impl PktLineWriter,
    refs: Vec<RefLine>,
    push_options_negotiated: bool,
    limits: &Limits,
) -> Result<(), SubstrateError> {
    if refs.len() > limits.max_advertisement_refs {
        return Err(SubstrateError::Protocol(format!(
            "push advertisement: ref cap of {} exceeded by {} refs — fail closed, no partial list (ADR-009, review 001 N-1)",
            limits.max_advertisement_refs,
            refs.len()
        )));
    }
    let caps = capabilities_text(push_options_negotiated);
    let zero = zero_oid_hex();

    let mut listed = Vec::with_capacity(refs.len());
    for line in &refs {
        if let Some(oid) = line.oid {
            listed.push((oid.to_string(), line.name.as_str()));
        }
    }

    if listed.is_empty() {
        writer
            .write_text_line(format!("{zero} capabilities^{{}}\0{caps}").as_bytes())
            .await?;
        return writer.write_flush().await;
    }

    let Some((first, rest)) = listed.split_first() else {
        return writer.write_flush().await;
    };
    writer
        .write_text_line(format!("{} {}\0{caps}", first.0, first.1).as_bytes())
        .await?;
    for (hex, name) in rest {
        writer
            .write_text_line(format!("{hex} {name}").as_bytes())
            .await?;
    }
    writer.write_flush().await
}

/// The unpack leg's report line: `unpack ok`, or `unpack ng <reason>`
/// with the pack-level failure text (ADR-013 §8). Consumed by
/// [`write_status_report`].
fn unpack_leg_line(unpack: &Result<(), String>) -> String {
    match unpack {
        Ok(()) => "unpack ok".to_owned(),
        Err(reason) => format!("unpack ng {reason}"),
    }
}

/// One per-ref outcome's report line: `ok <ref>` or `ng <ref>
/// <reason>` — the outcome data as the machine built it, the reason
/// verbatim (the client displays it; the writer never rewrites).
/// Consumed by [`write_status_report`].
fn ref_report_line(outcome: &RefOutcome) -> String {
    match &outcome.result {
        Ok(()) => format!("ok {}", outcome.name),
        Err(reason) => format!("ng {} {reason}", outcome.name),
    }
}

/// Writes the push status report (ADR-013 §8, substrate-owned
/// framing): `unpack ok|ng <reason>`, then the per-ref `ok <ref>` /
/// `ng <ref> <reason>` lines in request order, an inner flush
/// terminating the report section, then the terminating flush.
///
/// `sideband` is the client's `side-band-64k` selection — the framing
/// is selected by the client's capability, never by the handler:
///
/// - With sideband: the report's inner lines and the inner flush are
///   pkt-line framed into a payload that rides band-1 through
///   [`PktLineWriter::write_data_band`] (chunked at
///   [`SIDEBAND_CHUNK_SIZE`](crate::limits::SIDEBAND_CHUNK_SIZE) like
///   any band-1 relay), and the response ends with the outer flush.
///   A report sent unwrapped when sideband was selected aborts real
///   clients (`fatal: protocol error: bad line length character`,
///   observed live — push-captures.md §Status report).
/// - Without sideband: bare pkt-lines to the single flush.
///
/// `unpack` is the pack leg (`Ok` = `unpack ok`; `Err` = the ng
/// reason — a pack-level failure reports `unpack ng <reason>` with
/// all-refs `unpacker error` as the machine's outcome mapping); `refs`
/// are the per-ref CAS outcomes in request order. The report frames
/// whatever outcomes it is handed (including the atomic-abort mapping,
/// ADR-013 §10) and passes reason strings through verbatim. Band-2
/// diagnostics are always permitted (quiet suppresses progress, not
/// errors) — v1 emits none; the shape permits them additively.
///
/// Crate-internal by ADR-005/ADR-013 §8 (the substrate owns the
/// framing): no public re-export — the push machine is the only
/// consumer, handlers cannot reach it.
///
/// Contract stamp: ADR-013 §8 (the report framing, the sideband rule),
/// §2 (report-status-v2 shape-identity — the v1 shape is valid v2: v2
/// adds option lines only when the server emits them), §10 (the atomic
/// mapping is the CAS's outcome data); push-captures.md §Status report
/// (the normative record); ADR-005 (the substrate owns the framing);
/// core/w3-push-report.
pub(crate) async fn write_status_report(
    writer: &mut impl PktLineWriter,
    unpack: &Result<(), String>,
    refs: &[RefOutcome],
    sideband: bool,
) -> Result<(), SubstrateError> {
    if sideband {
        let mut payload = Vec::new();
        encode::text_to_write(unpack_leg_line(unpack).as_bytes(), &mut payload).await?;
        for outcome in refs {
            encode::text_to_write(ref_report_line(outcome).as_bytes(), &mut payload).await?;
        }
        encode::flush_to_write(&mut payload).await?;
        writer.write_data_band(&payload).await?;
        return writer.write_flush().await;
    }
    writer
        .write_text_line(unpack_leg_line(unpack).as_bytes())
        .await?;
    for outcome in refs {
        writer
            .write_text_line(ref_report_line(outcome).as_bytes())
            .await?;
    }
    writer.write_flush().await
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::substrate::SubstrateError;
    use gix_packetline::async_io::encode;
    use gix_packetline::Channel;

    const CAPS: &str = "report-status report-status-v2 delete-refs side-band-64k atomic ofs-delta object-format=sha1";
    const AGENT: &str = AGENT_CAPABILITY;

    fn oid(b: u8) -> ObjectId {
        ObjectId::from([b; 20])
    }

    fn hex_oid(b: u8) -> String {
        oid(b).to_string()
    }

    fn ref_line(name: &str, oid: Option<ObjectId>) -> RefLine {
        RefLine {
            name: name.to_owned(),
            oid,
            peeled: None,
            symref_target: None,
        }
    }

    /// An encoding sink: writes through the real pkt-line codec into a
    /// byte buffer, so the assertions see the wire bytes (the framing
    /// included), per push-captures.md §Advertisement.
    struct ByteSink(Vec<u8>);

    #[async_trait::async_trait]
    impl PktLineWriter for ByteSink {
        async fn write_text_line(&mut self, line: &[u8]) -> Result<(), SubstrateError> {
            encode::text_to_write(line, &mut self.0).await?;
            Ok(())
        }

        async fn write_flush(&mut self) -> Result<(), SubstrateError> {
            encode::flush_to_write(&mut self.0).await?;
            Ok(())
        }

        async fn write_data_band(&mut self, data: &[u8]) -> Result<(), SubstrateError> {
            encode::band_to_write(Channel::Data, data, &mut self.0).await?;
            Ok(())
        }
    }

    /// The raw payload of every pkt-line in a framed stream (a flush as
    /// a trailing empty payload).
    fn framed_lines(buffer: &[u8]) -> Vec<Vec<u8>> {
        let mut out = Vec::new();
        let mut cursor = buffer;
        while !cursor.is_empty() {
            let (header, rest) = cursor.split_at(4);
            let len = usize::from_str_radix(std::str::from_utf8(header).expect("hex header"), 16)
                .expect("hex length");
            cursor = rest;
            if len < 4 {
                out.push(Vec::new());
                continue;
            }
            let (payload, rest) = cursor.split_at(len - 4);
            cursor = rest;
            out.push(payload.to_vec());
        }
        out
    }

    /// The framed stream as texts (the codec's newline augmentation
    /// stripped; a flush as an empty string) — the shape comparisons
    /// run against it.
    fn framed_texts(buffer: &[u8]) -> Vec<String> {
        framed_lines(buffer)
            .into_iter()
            .map(|payload| {
                String::from_utf8_lossy(payload.strip_suffix(b"\n").unwrap_or(&payload))
                    .into_owned()
            })
            .collect()
    }

    #[test]
    fn the_served_set_is_the_pinned_constant() {
        assert_eq!(
            PUSH_SERVED_CAPABILITIES,
            &[
                "report-status",
                "report-status-v2",
                "delete-refs",
                "side-band-64k",
                "atomic",
                "ofs-delta",
                "object-format=sha1",
            ]
        );
        let declined = ["quiet", "push-cert", "push-options", "shallow"];
        for capability in declined {
            assert!(
                !PUSH_SERVED_CAPABILITIES
                    .iter()
                    .any(|line| line.contains(capability)),
                "{capability} is declined by omission (ADR-013 §2) or gate-gated (§11)"
            );
        }
        assert_eq!(
            capabilities_text(false),
            format!("{CAPS}{} {AGENT}", sha256_rider()),
            "the pinned default advertisement text (the sha256 rider rides the feature)"
        );
        assert_eq!(
            capabilities_text(true),
            format!("{CAPS} push-options{} {AGENT}", sha256_rider()),
            "the gate adds the push-options token, nothing else"
        );
    }

    /// The feature-gated rider text the expectations carry (`object-format=sha256`
    /// — the OQ-05 passthrough rider mirrored from the V2 advertisement).
    fn sha256_rider() -> &'static str {
        if cfg!(feature = "sha256") {
            " object-format=sha256"
        } else {
            ""
        }
    }

    #[tokio::test]
    async fn the_first_ref_line_carries_the_caps_and_the_rest_are_bare() {
        let refs = vec![
            ref_line("HEAD", Some(oid(1))),
            ref_line("refs/heads/main", Some(oid(2))),
            ref_line("refs/tags/v1", Some(oid(3))),
        ];
        let mut sink = ByteSink(Vec::new());
        advertise_v0(&mut sink, refs, false, &Limits::default())
            .await
            .unwrap();

        let caps = capabilities_text(false);
        let lines = framed_texts(&sink.0);
        assert_eq!(
            lines,
            vec![
                format!("{} HEAD\0{caps}", hex_oid(1)),
                format!("{} refs/heads/main", hex_oid(2)),
                format!("{} refs/tags/v1", hex_oid(3)),
                String::new(),
            ],
            "caps NUL-attached on the FIRST ref line only; bare rest; flush-terminated"
        );
        assert_eq!(
            lines[0].matches('\0').count(),
            1,
            "exactly one NUL, on the first line"
        );
    }

    #[tokio::test]
    async fn an_empty_repo_advertises_exactly_the_sentinel_line() {
        let mut sink = ByteSink(Vec::new());
        advertise_v0(&mut sink, Vec::new(), false, &Limits::default())
            .await
            .unwrap();

        let caps = capabilities_text(false);
        let lines = framed_texts(&sink.0);
        assert_eq!(
            lines,
            vec![
                format!("{} capabilities^{{}}\0{caps}", "0".repeat(40)),
                String::new(),
            ],
            "the zero-oid sentinel replaces the ref lines — one line carrying the caps"
        );
    }

    #[tokio::test]
    async fn a_repo_with_refs_never_emits_the_sentinel() {
        let refs = vec![
            ref_line("HEAD", Some(oid(1))),
            ref_line("refs/heads/main", Some(oid(2))),
        ];
        let mut sink = ByteSink(Vec::new());
        advertise_v0(&mut sink, refs, false, &Limits::default())
            .await
            .unwrap();
        let body = String::from_utf8_lossy(&sink.0).into_owned();
        assert!(
            !body.contains("capabilities^{}"),
            "a repo with refs never emits the sentinel: {body}"
        );
        let caps = capabilities_text(false);
        let lines = framed_texts(&sink.0);
        assert_eq!(
            lines,
            vec![
                format!("{} HEAD\0{caps}", hex_oid(1)),
                format!("{} refs/heads/main", hex_oid(2)),
                String::new(),
            ],
            "the caps NUL rides the first ref line only"
        );
    }

    #[tokio::test]
    async fn no_oid_rows_are_filtered() {
        // The unborn-HEAD symref row (oid: None) has no oid to print —
        // a V0 advertisement line has no symref shape.
        let refs = vec![
            ref_line("HEAD", None),
            ref_line("refs/heads/main", Some(oid(2))),
        ];
        let mut sink = ByteSink(Vec::new());
        advertise_v0(&mut sink, refs, false, &Limits::default())
            .await
            .unwrap();
        let body = String::from_utf8_lossy(&sink.0).into_owned();
        assert!(
            !body.contains("HEAD"),
            "the no-oid row is filtered out: {body}"
        );
    }

    #[tokio::test]
    async fn a_fully_filtered_repo_takes_the_sentinel_never_a_bare_dump() {
        // The unborn-only repo: every listed row lacks an oid — the
        // sentinel is the emission (git rejects a bare capability dump).
        let refs = vec![ref_line("HEAD", None)];
        let mut sink = ByteSink(Vec::new());
        advertise_v0(&mut sink, refs, false, &Limits::default())
            .await
            .unwrap();
        let caps = capabilities_text(false);
        let lines = framed_texts(&sink.0);
        assert_eq!(
            lines,
            vec![
                format!("{} capabilities^{{}}\0{caps}", "0".repeat(40)),
                String::new(),
            ],
        );
    }

    #[tokio::test]
    async fn the_sideband_report_is_band1_framed_packetlines_to_the_outer_flush() {
        // push-captures.md §Status report: the band payload is ITSELF
        // pkt-line-framed — the unpack line, the per-ref lines and the
        // inner flush ride inside band-1; the response ends with the
        // outer flush.
        let refs = vec![
            RefOutcome {
                name: "refs/heads/main".to_owned(),
                result: Ok(()),
            },
            RefOutcome {
                name: "refs/heads/dev".to_owned(),
                result: Err("funny refname".to_owned()),
            },
        ];
        let mut sink = ByteSink(Vec::new());
        write_status_report(&mut sink, &Ok(()), &refs, true)
            .await
            .unwrap();

        // The literal byte shape: a band-1 chunk whose payload opens
        // with the framed "unpack ok" line — the whole inner report
        // (14 + 23 + 36 + 4 = 77 bytes) rides one chunk here, so the
        // band header is 4 + 1 + 77 = 82 = 0x0052.
        assert!(
            sink.0.starts_with(b"0052\x01000eunpack ok\n"),
            "band-1 payload is itself pkt-line-framed: {}",
            String::from_utf8_lossy(&sink.0)
        );

        // The outer stream is band lines + exactly one outer flush; the
        // reassembled band payload carries the inner flush last.
        let outer = framed_lines(&sink.0);
        assert_eq!(
            outer.last().map(|v| v.is_empty()),
            Some(true),
            "one outer flush, terminal"
        );
        let bands = &outer[..outer.len() - 1];
        assert!(
            bands.iter().all(|payload| payload.first() == Some(&0x01)),
            "every report byte rides band-1 (Channel::Data)"
        );
        let mut reassembled = Vec::new();
        for payload in bands {
            reassembled.extend_from_slice(&payload[1..]);
        }
        assert_eq!(
            framed_texts(&reassembled),
            vec![
                "unpack ok",
                "ok refs/heads/main",
                "ng refs/heads/dev funny refname",
                "",
            ],
            "unpack line, per-ref lines in request order, the inner flush inside the band"
        );
    }

    #[tokio::test]
    async fn the_bare_report_is_pktlines_to_a_single_flush() {
        let refs = vec![
            RefOutcome {
                name: "refs/heads/main".to_owned(),
                result: Ok(()),
            },
            RefOutcome {
                name: "refs/heads/dev".to_owned(),
                result: Err("funny refname".to_owned()),
            },
            RefOutcome {
                name: "refs/heads/third".to_owned(),
                result: Ok(()),
            },
        ];
        let mut sink = ByteSink(Vec::new());
        write_status_report(&mut sink, &Ok(()), &refs, false)
            .await
            .unwrap();

        let lines = framed_lines(&sink.0);
        assert_eq!(
            lines.iter().filter(|p| p.is_empty()).count(),
            1,
            "exactly one flush — the report section's terminator"
        );
        assert_eq!(
            framed_texts(&sink.0),
            vec![
                "unpack ok",
                "ok refs/heads/main",
                "ng refs/heads/dev funny refname",
                "ok refs/heads/third",
                "",
            ],
            "bare pkt-lines in request order, single-flush terminated"
        );
        assert!(
            framed_lines(&sink.0)
                .iter()
                .all(|payload| payload.first() != Some(&0x01)),
            "no band framing without the sideband selection"
        );
    }

    #[tokio::test]
    async fn pack_level_failure_frames_unpack_ng_with_the_all_refs_unpacker_error_map() {
        // The observed raw-stdio shape: `unpack ng <index-pack error
        // text>` + every ref `ng <ref> unpacker error` (the detailed
        // reason is the unpack leg's; the per-ref lines carry the
        // generic text — the machine builds the mapping, the writer
        // frames it).
        let unpack: Result<(), String> =
            Err("unpack protocol error (pack signature mismatch detected)".to_owned());
        let refs = vec![
            RefOutcome {
                name: "refs/heads/main".to_owned(),
                result: Err("unpacker error".to_owned()),
            },
            RefOutcome {
                name: "refs/heads/dev".to_owned(),
                result: Err("unpacker error".to_owned()),
            },
        ];
        let mut sink = ByteSink(Vec::new());
        write_status_report(&mut sink, &unpack, &refs, false)
            .await
            .unwrap();
        assert_eq!(
            framed_texts(&sink.0),
            vec![
                "unpack ng unpack protocol error (pack signature mismatch detected)",
                "ng refs/heads/main unpacker error",
                "ng refs/heads/dev unpacker error",
                "",
            ],
            "the ng leg frames from the unpack line; per-ref lines carry the mapped text"
        );
    }

    #[tokio::test]
    async fn reason_strings_pass_through_verbatim() {
        let unpack: Result<(), String> = Err("eof before pack header was fully read".to_owned());
        let refs = vec![
            RefOutcome {
                name: "refs/heads/main".to_owned(),
                result: Err("atomic push failure".to_owned()),
            },
            RefOutcome {
                name: "refs/heads/other".to_owned(),
                result: Err("stale info  ".to_owned()),
            },
            RefOutcome {
                name: "refs/heads/good".to_owned(),
                result: Ok(()),
            },
        ];
        let mut sink = ByteSink(Vec::new());
        write_status_report(&mut sink, &unpack, &refs, false)
            .await
            .unwrap();
        assert_eq!(
            framed_texts(&sink.0),
            vec![
                "unpack ng eof before pack header was fully read",
                "ng refs/heads/main atomic push failure",
                "ng refs/heads/other stale info  ",
                "ok refs/heads/good",
                "",
            ],
            "reasons are client-displayed verbatim text — trailing spaces survive (no rewriting, no normalization)"
        );
    }

    #[tokio::test]
    async fn the_sideband_report_of_a_failed_pack_follows_the_same_rule() {
        let unpack: Result<(), String> = Err("index-pack failed".to_owned());
        let refs = vec![RefOutcome {
            name: "refs/heads/main".to_owned(),
            result: Err("unpacker error".to_owned()),
        }];
        let mut sink = ByteSink(Vec::new());
        write_status_report(&mut sink, &unpack, &refs, true)
            .await
            .unwrap();
        let outer = framed_lines(&sink.0);
        let mut reassembled = Vec::new();
        for payload in &outer[..outer.len() - 1] {
            assert_eq!(payload.first(), Some(&0x01));
            reassembled.extend_from_slice(&payload[1..]);
        }
        assert_eq!(
            framed_texts(&reassembled),
            vec![
                "unpack ng index-pack failed",
                "ng refs/heads/main unpacker error",
                "",
            ],
        );
        assert_eq!(outer.last().map(|v| v.is_empty()), Some(true));
    }

    #[tokio::test]
    async fn the_ref_cap_fails_closed_with_nothing_emitted() {
        let refs = vec![
            ref_line("refs/heads/a", Some(oid(1))),
            ref_line("refs/heads/b", Some(oid(2))),
            ref_line("refs/heads/c", Some(oid(3))),
        ];
        let limits = Limits {
            max_advertisement_refs: 2,
            ..Limits::default()
        };
        let mut sink = ByteSink(Vec::new());
        let error = advertise_v0(&mut sink, refs, false, &limits)
            .await
            .unwrap_err();
        assert!(error.is_terminal(), "a cap breach fails closed: {error:?}");
        match &error {
            SubstrateError::Protocol(message) => {
                assert!(message.contains("ref cap"), "{message}");
            }
            other => panic!("a cap breach is protocol-shaped: {other:?}"),
        }
        assert!(
            sink.0.is_empty(),
            "no partial list can be emitted — the check precedes the first written line"
        );
    }

    #[tokio::test]
    async fn the_emission_carries_no_service_prefix() {
        let refs = vec![ref_line("refs/heads/main", Some(oid(2)))];
        let mut sink = ByteSink(Vec::new());
        advertise_v0(&mut sink, refs, false, &Limits::default())
            .await
            .unwrap();
        let lines = framed_texts(&sink.0);
        assert!(
            lines.iter().all(|line| !line.contains("# service=")),
            "the duplex shape has no service prefix — the emission speaks refs first"
        );
        assert!(
            lines.iter().all(|line| !line.contains("version")),
            "no version negotiation exists on the push path (ADR-013 §1)"
        );
    }

    #[cfg(feature = "sha256")]
    #[test]
    fn the_sha256_rider_rides_the_feature() {
        let text = capabilities_text(false);
        assert!(
            text.contains("object-format=sha1 object-format=sha256"),
            "the passthrough rider follows the pinned default: {text}"
        );
    }
}