git-remote-object-store 0.2.2

Git remote helper backed by cloud object stores (S3, Azure Blob Storage)
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
//! Smoke test: drive [`protocol::run`] in-process via
//! `tokio::io::duplex`, with a [`MockStore`] standing in for the cloud
//! backend. Every claim from the `cmd_list` / `cmd_capabilities`
//! handlers has a matching assertion here.
//!
//! Real binary-spawn integration tests (with `git-remote-s3-https`
//! against RustFS) live alongside the fetch and push integration
//! suites; this file's role is the deterministic in-process check.

#![cfg(feature = "test-util")]

mod common;

use std::sync::Arc;

use bytes::Bytes;
use git_remote_object_store::object_store::mock::MockStore;
use git_remote_object_store::object_store::{ObjectStore, PutOpts};
use git_remote_object_store::protocol::ProtocolError;
use git_remote_object_store::url::RemoteUrl;
use time::Duration;
use time::OffsetDateTime;

use common::{drive_in, s3_url};

const SHA_A: &str = "0000000000000000000000000000000000000001";
const SHA_B: &str = "0000000000000000000000000000000000000002";
const SHA_C: &str = "0000000000000000000000000000000000000003";

async fn drive(
    remote: RemoteUrl,
    store: Arc<dyn ObjectStore>,
    script: &str,
) -> (Vec<u8>, Result<(), ProtocolError>) {
    drive_in(remote, store, script, std::env::temp_dir()).await
}

#[tokio::test]
async fn packchain_capabilities_succeeds() {
    // Phase 2 (issue #63) lights up packchain push. Engine-agnostic
    // commands like `capabilities` must succeed for the packchain
    // engine just as they do for the bundle engine — pinning this
    // catches a regression that re-introduces a blanket
    // engine-not-implemented gate at REPL entry.
    let raw = "s3+https://my-bucket.s3.us-west-2.amazonaws.com/repo?engine=packchain";
    let remote = git_remote_object_store::url::parse(raw).expect("URL parses");

    let store: Arc<dyn ObjectStore> = Arc::new(MockStore::new());
    let (out, result) = drive(remote, store, "capabilities\n").await;

    result.expect("capabilities must succeed for packchain");
    assert_eq!(&out, b"*push\n*fetch\noption\n\n");
}

#[tokio::test]
async fn packchain_capabilities_advertises_bundle_uri_when_opted_in() {
    // Issue #71: `?bundle_uri=1` on a packchain remote opts the
    // helper into advertising the `bundle-uri` capability. Without
    // the flag the line is absent (verified by
    // `packchain_capabilities_succeeds`).
    let raw = "s3+https://my-bucket.s3.us-west-2.amazonaws.com/repo?engine=packchain&bundle_uri=1";
    let remote = git_remote_object_store::url::parse(raw).expect("URL parses");
    let store: Arc<dyn ObjectStore> = Arc::new(MockStore::new());
    let (out, result) = drive(remote, store, "capabilities\n").await;
    result.expect("capabilities must succeed");
    assert_eq!(
        &out, b"*push\n*fetch\noption\nbundle-uri\n\n",
        "bundle-uri line must precede the trailing terminator",
    );
}

#[tokio::test]
async fn bundle_engine_with_bundle_uri_flag_does_not_advertise() {
    // The bundle engine ignores `?bundle_uri=1`: bundle filenames
    // rotate per push so a stable URL would race the next push.
    // Pin that the capability line is absent regardless of the URL
    // flag.
    let raw = "s3+https://my-bucket.s3.us-west-2.amazonaws.com/repo?bundle_uri=1";
    let remote = git_remote_object_store::url::parse(raw).expect("URL parses");
    let store: Arc<dyn ObjectStore> = Arc::new(MockStore::new());
    let (out, result) = drive(remote, store, "capabilities\n").await;
    result.expect("capabilities must succeed");
    assert_eq!(
        &out, b"*push\n*fetch\noption\n\n",
        "bundle-engine remote must not advertise bundle-uri",
    );
}

#[tokio::test]
async fn bundle_uri_command_emits_per_ref_entries_with_creation_token() {
    // End-to-end: push + bundle-uri command. We seed a packchain
    // chain.json so the handler has something to emit, then drive
    // the REPL through a `capabilities` + `bundle-uri` exchange.
    let store = MockStore::new();
    store.insert("repo/FORMAT", Bytes::from_static(b"packchain"));
    store.insert(
        "repo/refs/heads/main/chain.json",
        Bytes::from(
            format!(
                r#"{{"v":1,"tip":"{SHA_A}","full_at":"{SHA_B}","segments":[{{"sha":"{SHA_A}","parent_sha":null,"pack":"packs/{SHA_C}.pack","bytes":1024}}]}}"#,
            )
            .into_bytes(),
        ),
    );
    let store: Arc<dyn ObjectStore> = Arc::new(store);

    let raw = "s3+https://my-bucket.s3.us-west-2.amazonaws.com/repo?engine=packchain&bundle_uri=1";
    let remote = git_remote_object_store::url::parse(raw).expect("URL parses");
    let (out, result) = drive(remote, store, "capabilities\nbundle-uri\n").await;
    result.expect("capabilities + bundle-uri must succeed");
    let text = std::str::from_utf8(&out).unwrap();
    // capabilities response, then bundle-uri response.
    assert!(
        text.starts_with("*push\n*fetch\noption\nbundle-uri\n\n"),
        "{text}"
    );
    assert!(
        text.contains(&format!(
            "bundle.refs/heads/main.uri=https://my-bucket.s3.us-west-2.amazonaws.com/repo/refs/heads/main/{SHA_B}.bundle\n"
        )),
        "{text}",
    );
    assert!(
        text.contains(&format!("bundle.refs/heads/main.creationToken={SHA_B}\n")),
        "{text}",
    );
    // creationToken is `full_at` (SHA_B), not `tip` (SHA_A).
    assert!(!text.contains(&format!("creationToken={SHA_A}")), "{text}");
}

#[tokio::test]
async fn bundle_uri_command_when_capability_not_advertised_emits_terminator_only() {
    // If a misconfigured client sends `bundle-uri\n` without us
    // having advertised the capability, the helper still must
    // respond gracefully — emit just the trailing blank line.
    let raw = "s3+https://my-bucket.s3.us-west-2.amazonaws.com/repo?engine=packchain";
    let remote = git_remote_object_store::url::parse(raw).expect("URL parses");
    let store: Arc<dyn ObjectStore> = Arc::new(MockStore::new());
    let (out, result) = drive(remote, store, "bundle-uri\n").await;
    result.expect("bundle-uri command must succeed");
    assert_eq!(&out, b"\n");
}

#[tokio::test]
async fn packchain_fetch_against_empty_bucket_surfaces_chain_absent() {
    // Phase 3 (issue #64) lights up packchain fetch. Fetching a ref
    // from a packchain bucket that has no chain.json for that ref
    // must produce a typed `ChainAbsent` error (wrapped in
    // `FetchError::Packchain`) rather than the opaque `Store(NotFound)`
    // a literal GET would surface.
    use git_remote_object_store::PackchainError;
    use git_remote_object_store::protocol::fetch::FetchError;

    let raw = "s3+https://my-bucket.s3.us-west-2.amazonaws.com/repo?engine=packchain";
    let remote = git_remote_object_store::url::parse(raw).expect("URL parses");

    let store: Arc<dyn ObjectStore> = Arc::new(MockStore::new());
    let (_out, result) = drive(
        remote,
        store,
        "fetch 0123456789abcdef0123456789abcdef01234567 refs/heads/main\n\n",
    )
    .await;
    let err = result.expect_err("packchain fetch on empty bucket must error");
    assert!(
        matches!(
            err,
            ProtocolError::Fetch(FetchError::Packchain(PackchainError::ChainAbsent { .. }))
        ),
        "expected Fetch(Packchain(ChainAbsent)), got {err:?}",
    );
}

#[tokio::test]
async fn packchain_format_resolves_engine_even_without_url_flag() {
    // FORMAT is authoritative for the resolved engine. A bucket
    // already locked to `packchain` must dispatch through the
    // packchain code paths even when the URL omits `?engine=` —
    // otherwise a bundle-helper would walk a packchain bucket's keys
    // and either return empty results or overwrite chain.json.
    //
    // Pin the routing by inserting a packchain FORMAT marker without
    // a chain.json: the fetch must produce the packchain-specific
    // `ChainAbsent` error variant. A regression that routed through
    // the bundle path would surface as `Store(NotFound)` for the
    // missing `<sha>.bundle` instead.
    use git_remote_object_store::PackchainError;
    use git_remote_object_store::protocol::fetch::FetchError;

    let store = MockStore::new();
    store.insert("repo/FORMAT", Bytes::from_static(b"packchain"));
    let store: Arc<dyn ObjectStore> = Arc::new(store);

    let (_out, result) = drive(
        s3_url(Some("repo")),
        store,
        "fetch 0123456789abcdef0123456789abcdef01234567 refs/heads/main\n\n",
    )
    .await;
    let err = result.expect_err("packchain fetch on empty bucket must error");
    assert!(
        matches!(
            err,
            ProtocolError::Fetch(FetchError::Packchain(PackchainError::ChainAbsent { .. }))
        ),
        "FORMAT must drive engine resolution to packchain fetch; got {err:?}",
    );
}

#[tokio::test]
async fn packchain_list_returns_chain_tip_not_full_at() {
    // Regression test for issue #72: `list` against a packchain
    // remote returned the baseline `<full_at>` SHA from the bundle
    // filename, not the current `chain.tip` from chain.json. After
    // any incremental push, `chain.tip != full_at` and the bundle
    // path produces stale tips, breaking `git ls-remote` /
    // `git fetch` / `git pull`.
    //
    // The fix routes `Command::List` through engine-aware dispatch:
    // packchain reads chain.json directly. Pin both the right SHA
    // (chain.tip) AND the absence of the wrong SHA (full_at).
    //
    // Construct the chain.json via raw bytes (the schema types are
    // `pub(crate)`); the integration boundary is the on-bucket JSON
    // shape, which this string pins directly.
    let store = MockStore::new();
    let chain_json = format!(
        r#"{{"v":1,"tip":"{SHA_B}","full_at":"{SHA_A}","segments":[{{"sha":"{SHA_B}","parent_sha":"{SHA_A}","pack":"packs/{SHA_C}.pack","bytes":1024}}]}}"#
    );
    store.insert(
        "repo/refs/heads/main/chain.json",
        Bytes::from(chain_json.into_bytes()),
    );
    // Also drop a stale baseline bundle on disk to make the bug
    // observable: a regression that fell back to the bundle path
    // would pick up SHA_A from the filename.
    store.insert(
        format!("repo/refs/heads/main/{SHA_A}.bundle"),
        Bytes::from_static(b"baseline"),
    );
    store.insert("repo/FORMAT", Bytes::from_static(b"packchain"));
    store.insert("repo/HEAD", Bytes::from_static(b"refs/heads/main"));

    let url_str = "s3+https://my-bucket.s3.us-west-2.amazonaws.com/repo?engine=packchain";
    let remote = git_remote_object_store::url::parse(url_str).expect("URL parses");
    let (out, result) = drive(remote, Arc::new(store), "list\n").await;
    result.expect("packchain list should succeed");
    let text = std::str::from_utf8(&out).unwrap();
    assert_eq!(
        text,
        format!("@refs/heads/main HEAD\n{SHA_B} refs/heads/main\n\n"),
        "packchain list must report chain.tip ({SHA_B}), not full_at ({SHA_A})",
    );
    // Belt-and-suspenders: explicitly assert the wrong SHA never
    // appears, so a future regression that emits BOTH lines (an
    // engine-mux bug) would still fail the test.
    assert!(
        !text.contains(SHA_A),
        "list output must not include the baseline `full_at` sha; got {text:?}",
    );
}

#[tokio::test]
async fn capabilities_emits_exact_block() {
    let (out, result) = drive(
        s3_url(Some("repo")),
        Arc::new(MockStore::new()),
        "capabilities\n",
    )
    .await;
    result.expect("capabilities should succeed");
    assert_eq!(&out, b"*push\n*fetch\noption\n\n");
}

#[tokio::test]
async fn list_empty_bucket_emits_terminator() {
    let (out, result) = drive(s3_url(Some("repo")), Arc::new(MockStore::new()), "list\n").await;
    result.expect("list should succeed");
    assert_eq!(&out, b"\n");
}

#[tokio::test]
async fn list_for_push_skips_head_lookup() {
    let store = MockStore::new();
    store.insert(
        format!("repo/refs/heads/main/{SHA_A}.bundle"),
        Bytes::from_static(b"bundle a"),
    );
    store.insert("repo/HEAD", Bytes::from_static(b"refs/heads/main"));

    let (out, result) = drive(s3_url(Some("repo")), Arc::new(store), "list for-push\n").await;
    result.expect("list for-push should succeed");
    let text = std::str::from_utf8(&out).unwrap();
    // Exact-eq subsumes presence of the bundle line, absence of `@<ref> HEAD`,
    // and the trailing-blank-line terminator in a single assertion.
    assert_eq!(text, format!("{SHA_A} refs/heads/main\n\n"));
}

#[tokio::test]
async fn list_emits_head_pointer_when_ref_present() {
    let store = MockStore::new();
    store.insert(
        format!("repo/refs/heads/main/{SHA_A}.bundle"),
        Bytes::from_static(b"bundle"),
    );
    store.insert("repo/HEAD", Bytes::from_static(b"refs/heads/main\n"));

    let (out, result) = drive(s3_url(Some("repo")), Arc::new(store), "list\n").await;
    result.expect("list should succeed");
    let text = std::str::from_utf8(&out).unwrap();
    assert_eq!(
        text,
        format!("@refs/heads/main HEAD\n{SHA_A} refs/heads/main\n\n")
    );
}

#[tokio::test]
async fn list_omits_head_when_pointed_ref_has_no_bundle() {
    let store = MockStore::new();
    store.insert(
        format!("repo/refs/heads/feature/{SHA_A}.bundle"),
        Bytes::from_static(b"bundle"),
    );
    store.insert("repo/HEAD", Bytes::from_static(b"refs/heads/main"));

    let (out, result) = drive(s3_url(Some("repo")), Arc::new(store), "list\n").await;
    result.expect("list should succeed");
    let text = std::str::from_utf8(&out).unwrap();
    // Exact-eq: no `@refs/heads/main HEAD` line (the listed ref does not
    // match the head body) and the bundle line is the only output.
    assert_eq!(text, format!("{SHA_A} refs/heads/feature\n\n"));
}

#[tokio::test]
async fn list_swallows_missing_head_silently() {
    let store = MockStore::new();
    store.insert(
        format!("repo/refs/heads/main/{SHA_A}.bundle"),
        Bytes::from_static(b"bundle"),
    );
    // No HEAD object — must not error.

    let (out, result) = drive(s3_url(Some("repo")), Arc::new(store), "list\n").await;
    result.expect("list should succeed even without HEAD");
    let text = std::str::from_utf8(&out).unwrap();
    assert_eq!(text, format!("{SHA_A} refs/heads/main\n\n"));
}

#[tokio::test]
async fn list_sorts_bundles_by_last_modified_desc() {
    let store = MockStore::new();
    let now = OffsetDateTime::now_utc();
    store.insert_with(
        format!("repo/refs/heads/main/{SHA_A}.bundle"),
        Bytes::from_static(b"old"),
        now - Duration::seconds(60),
        PutOpts::default(),
    );
    store.insert_with(
        format!("repo/refs/heads/main/{SHA_B}.bundle"),
        Bytes::from_static(b"new"),
        now,
        PutOpts::default(),
    );
    store.insert_with(
        format!("repo/refs/heads/main/{SHA_C}.bundle"),
        Bytes::from_static(b"middle"),
        now - Duration::seconds(30),
        PutOpts::default(),
    );

    let (out, result) = drive(s3_url(Some("repo")), Arc::new(store), "list\n").await;
    result.expect("list should succeed");
    let text = std::str::from_utf8(&out).unwrap();
    let expected =
        format!("{SHA_B} refs/heads/main\n{SHA_C} refs/heads/main\n{SHA_A} refs/heads/main\n\n");
    assert_eq!(text, expected);
}

#[tokio::test]
async fn list_filters_non_bundle_keys() {
    let store = MockStore::new();
    // Real bundle.
    store.insert(
        format!("repo/refs/heads/main/{SHA_A}.bundle"),
        Bytes::from_static(b"bundle"),
    );
    // Uppercase SHA — must be filtered out.
    let upper_sha = SHA_A.to_uppercase();
    store.insert(
        format!("repo/refs/heads/main/{upper_sha}.bundle"),
        Bytes::from_static(b"bundle"),
    );
    // Non-refs/ keys.
    store.insert(format!("repo/lfs/{SHA_A}"), Bytes::from_static(b"lfs"));
    // Lock file under refs.
    store.insert(
        "repo/refs/heads/main/LOCK#.lock",
        Bytes::from_static(b"lock"),
    );

    let (out, result) = drive(s3_url(Some("repo")), Arc::new(store), "list for-push\n").await;
    result.expect("list should succeed");
    let text = std::str::from_utf8(&out).unwrap();
    assert_eq!(text, format!("{SHA_A} refs/heads/main\n\n"));
}

#[tokio::test]
async fn list_rejects_sibling_prefix_collision() {
    let store = MockStore::new();
    // Real repo.
    store.insert(
        format!("repo/refs/heads/main/{SHA_A}.bundle"),
        Bytes::from_static(b"bundle"),
    );
    // Sibling-prefix repo that would byte-match `prefix=repo`.
    store.insert(
        format!("repo-other/refs/heads/main/{SHA_B}.bundle"),
        Bytes::from_static(b"bundle"),
    );

    let (out, result) = drive(s3_url(Some("repo")), Arc::new(store), "list for-push\n").await;
    result.expect("list should succeed");
    let text = std::str::from_utf8(&out).unwrap();
    assert_eq!(text, format!("{SHA_A} refs/heads/main\n\n"));
    assert!(!text.contains(SHA_B));
}

#[tokio::test]
async fn list_works_with_no_prefix() {
    let store = MockStore::new();
    store.insert(
        format!("refs/heads/main/{SHA_A}.bundle"),
        Bytes::from_static(b"bundle"),
    );

    let (out, result) = drive(s3_url(None), Arc::new(store), "list for-push\n").await;
    result.expect("list should succeed");
    let text = std::str::from_utf8(&out).unwrap();
    assert_eq!(text, format!("{SHA_A} refs/heads/main\n\n"));
}

#[tokio::test]
async fn option_verbosity_two_responds_ok() {
    let (out, result) = drive(
        s3_url(Some("repo")),
        Arc::new(MockStore::new()),
        "option verbosity 2\n",
    )
    .await;
    result.expect("option should succeed");
    assert_eq!(&out, b"ok\n");
}

#[tokio::test]
async fn option_verbosity_zero_responds_unsupported() {
    // Explicit "off" — git probes with `option verbosity 0` to silence
    // helpers; we have nothing to say so we must respond `unsupported`.
    let (out, result) = drive(
        s3_url(Some("repo")),
        Arc::new(MockStore::new()),
        "option verbosity 0\n",
    )
    .await;
    result.expect("option should succeed");
    assert_eq!(&out, b"unsupported\n");
}

#[tokio::test]
async fn option_verbosity_one_responds_unsupported() {
    let (out, result) = drive(
        s3_url(Some("repo")),
        Arc::new(MockStore::new()),
        "option verbosity 1\n",
    )
    .await;
    result.expect("option should succeed");
    assert_eq!(&out, b"unsupported\n");
}

#[tokio::test]
async fn option_verbosity_three_responds_ok() {
    // Git may send any non-negative integer for `option verbosity`; the
    // handler treats `n >= 2` as the "info" threshold, so 3, 4, … must
    // all behave identically to 2 (`ok\n`). Pinning this prevents a
    // future refactor from accidentally tightening the predicate to
    // `== 2`, which would silently break high-verbosity invocations.
    let (out, result) = drive(
        s3_url(Some("repo")),
        Arc::new(MockStore::new()),
        "option verbosity 3\n",
    )
    .await;
    result.expect("option should succeed");
    assert_eq!(&out, b"ok\n");
}

#[tokio::test]
async fn option_verbosity_four_responds_ok() {
    // Same threshold as `verbosity 3` — covers a second value above the
    // boundary so the test isn't married to the exact number 3.
    let (out, result) = drive(
        s3_url(Some("repo")),
        Arc::new(MockStore::new()),
        "option verbosity 4\n",
    )
    .await;
    result.expect("option should succeed");
    assert_eq!(&out, b"ok\n");
}

#[tokio::test]
async fn option_unknown_key_responds_unsupported() {
    let (out, result) = drive(
        s3_url(Some("repo")),
        Arc::new(MockStore::new()),
        "option progress true\n",
    )
    .await;
    result.expect("option should succeed");
    assert_eq!(&out, b"unsupported\n");
}

#[tokio::test]
async fn empty_line_emits_terminator_in_idle_mode() {
    let (out, result) = drive(s3_url(Some("repo")), Arc::new(MockStore::new()), "\n").await;
    result.expect("blank line should succeed");
    assert_eq!(&out, b"\n");
}

#[tokio::test]
async fn invalid_command_returns_error() {
    let (_out, result) = drive(
        s3_url(Some("repo")),
        Arc::new(MockStore::new()),
        "nonsense\n",
    )
    .await;
    match result {
        Err(ProtocolError::InvalidCommand(line)) => assert_eq!(line, "nonsense"),
        other => panic!("expected InvalidCommand error, got {other:?}"),
    }
}

#[tokio::test]
async fn push_with_malformed_args_returns_parse_error() {
    use git_remote_object_store::protocol::push::PushError;

    // Drain on the trailing blank line so push_batch is invoked. A
    // malformed refspec aborts the batch with `PushError::Parse` before
    // any stdout traffic — a regression that emitted partial protocol
    // output before erroring would corrupt git's parser.
    let (out, result) = drive(
        s3_url(Some("repo")),
        Arc::new(MockStore::new()),
        "push not-a-refspec\n\n",
    )
    .await;
    match result {
        Err(ProtocolError::Push(PushError::Parse { .. })) => {}
        other => panic!("expected Push(Parse) error, got {other:?}"),
    }
    assert!(
        out.is_empty(),
        "push must not write on parse error: {out:?}"
    );
}

#[tokio::test]
async fn stdin_eof_exits_cleanly() {
    let (out, result) = drive(s3_url(Some("repo")), Arc::new(MockStore::new()), "").await;
    result.expect("EOF should be a clean exit");
    assert!(out.is_empty());
}

#[tokio::test]
async fn batched_command_then_blank_line_emits_terminator() {
    // capabilities and list each emit their own terminators, but a bare
    // blank line should still produce just `\n`.
    let (out, result) = drive(
        s3_url(Some("repo")),
        Arc::new(MockStore::new()),
        "capabilities\n\n",
    )
    .await;
    result.expect("script should succeed");
    assert_eq!(&out, b"*push\n*fetch\noption\n\n\n");
}

#[tokio::test]
async fn head_with_trailing_whitespace_is_trimmed() {
    let store = MockStore::new();
    store.insert(
        format!("repo/refs/heads/main/{SHA_A}.bundle"),
        Bytes::from_static(b"bundle"),
    );
    store.insert("repo/HEAD", Bytes::from_static(b"  refs/heads/main\n  \n"));

    let (out, result) = drive(s3_url(Some("repo")), Arc::new(store), "list\n").await;
    result.expect("list should succeed");
    let text = std::str::from_utf8(&out).unwrap();
    // Exact-eq: confirms the leading whitespace was stripped (otherwise the
    // ref-match would fail and `@<ref> HEAD` would be omitted) AND that no
    // extra padding leaked through to the protocol output.
    assert_eq!(
        text,
        format!("@refs/heads/main HEAD\n{SHA_A} refs/heads/main\n\n")
    );
}

#[tokio::test]
async fn head_with_empty_body_is_ignored() {
    let store = MockStore::new();
    store.insert(
        format!("repo/refs/heads/main/{SHA_A}.bundle"),
        Bytes::from_static(b"bundle"),
    );
    store.insert("repo/HEAD", Bytes::from_static(b"   \n"));

    let (out, result) = drive(s3_url(Some("repo")), Arc::new(store), "list\n").await;
    result.expect("list should succeed");
    let text = std::str::from_utf8(&out).unwrap();
    assert!(!text.contains("HEAD\n"));
    assert_eq!(text, format!("{SHA_A} refs/heads/main\n\n"));
}

/// Mid-batch fetch → push mode flip discards the buffered fetch.
///
/// Spec-allowed but uncommon: the REPL's `BatchState::accumulate`
/// resets the OTHER mode's accumulator on a switch. A regression that
/// kept the buffered fetch would either:
///   - run the fetch and crash on a missing bundle (since the script
///     never seeds it), turning the script's `Ok(())` into `Err`, or
///   - emit fetch-side stdout bytes before the push outcome.
///
/// This test seeds nothing for the fetch and asserts the script
/// produces ONLY the push outcome line (with no fetch traffic), so the
/// fetch must have been dropped.
#[tokio::test]
async fn fetch_then_push_mode_flip_drops_buffered_fetch() {
    // The push is `:refs/heads/main` (delete a ref). With nothing
    // seeded in the store, this returns the
    // `error <ref> "not found"?` outcome — a deterministic byte-exact
    // line we can pin. The fetch line targets a SHA that is NOT in the
    // store; if the fetch ran, the helper would error with
    // ProtocolError::Fetch (NotFound) instead of producing this output.
    let script = format!("fetch {SHA_A} refs/heads/main\npush :refs/heads/main\n\n");
    let (out, result) = drive(s3_url(Some("repo")), Arc::new(MockStore::new()), &script).await;
    result.expect("mode flip script should succeed");
    let text = std::str::from_utf8(&out).expect("stdout utf-8");
    // Byte-exact: the push outcome line, then the trailing blank-line
    // batch terminator. No fetch-side bytes leaked through.
    assert_eq!(
        text, "error refs/heads/main \"not found\"?\n\n",
        "expected only the push outcome line, got {text:?}",
    );
}