[Home](/content/site-root.html)

Log in

# Rewrite git-sync into focused packages

`0520b7c`→[main](/content/gh/entireio/git-sync/commits/main/index.html)·

Soph·3mo ago·39 files·+7,196 added/-3,981 removed

Break the monolithic syncer.go (3143 lines) into 7 focused packages:

\- internal/gitproto: pkt-line, smart HTTP, capability negotiation, v1/v2 fetch/push
\- internal/planner: mapping validation, planning, relay eligibility, checkpoints
\- internal/auth: credential resolution, Entire DB tokens, git credential helper
\- internal/strategy/bootstrap: one-shot + batched bootstrap, GitHub preflight
\- internal/strategy/incremental: incremental relay execution
\- internal/strategy/materialized: materialized fallback push with size guard
\- internal/syncer: slim orchestrator (734 lines), stats, measurement

Addresses all 22 issues from docs/rewrite-issue-list.md:

Correctness: tag ref creation independent of pack (#1), duplicate target
mapping rejection (#2), cross-kind mapping rejection (#3), sideband-64k
preference (#4), pack reader close discipline (#5), include-tag capability
gating (#6), OAuth refresh error propagation (#7).

Concurrency: mutex-protected stats (#8), bounded response reads (#9),
flock-based file token store locking (#10).

Architecture: package decomposition (#11), shared session setup (#12),
explicit Params structs (#13).

Performance: commit-count batch sizing heuristic (#14), materialized
object count guard (#15), bounded ancestry checks with ErrAncestryDepthExceeded
(#16), reusable pkt-line buffer (#17).

Testing: 73 test functions, 7 benchmarks, coverage 41-58% on core packages.
Protocol malformed-input tests (#18-20), behavioral edge cases (#21),
benchmarks for planning/protocol hot paths (#22).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

## Sessions

27633b8ca595View transcript

[?\\
Can you take a look at the go code (wasm) in /Users/soph/Work/entire/devenv/entire-io-worktree1 based a bit on that I wonder if something like this can be build:Codex·GPT-5.4·1 step](/content/gh/entireio/git-sync/session/019d6d29-8cf7-7fe3-adc9-8c3e4d9d5603#timeline-27633b8ca595/index.html)

## Changes

39

- internal

- auth

- Aauth.go+119

- Aauth\_test.go+550

- Aentiredb.go+229

- Atokenstore.go+142

- gitproto

- Abenchmark\_test.go+88

- Acapability.go+129

- Acapability\_test.go+186

- Aconvert.go+64

- Aconvert\_test.go+211

- Afetch.go+427

- Afetch\_helpers\_test.go+163

- Afetch\_test.go+217

- Apktline.go+155

- Apktline\_test.go+379

- Apush.go+192

- Arefs.go+188

- Arefs\_test.go+130

- Asmarthttp.go+149

- Asmarthttp\_test.go+78

- planner

- Abenchmark\_test.go+137

- Acheckpoint.go+161

- Amapping.go+85

- Aplanner.go+395

- Aplanner\_test.go+756

- Arelay.go+101

- Atypes.go+236

- strategy

- bootstrap

- Abootstrap.go+528

- Abootstrap\_test.go+112

- incremental

- Aincremental.go+92

- materialized

- Amaterialized.go+107

- syncer

- Mauth\_test.go+48/-47

- Mgit\_http\_backend\_test.go+18/-8

- Mintegration\_test.go+11/-8

- Ameasurement.go+83

- Dprotocol\_v2.go-782

- Dprotocol\_v2\_test.go-117

- Astats.go+148

- Msyncer.go+373/-2803

- Msyncer\_test.go+9/-216

```
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

package auth

import (
	"context"
	"fmt"
	"os/exec"
	"strings"

"github.com/go-git/go-git/v5/plumbing/transport"
	transporthttp "github.com/go-git/go-git/v5/plumbing/transport/http"
)

// Endpoint holds the authentication-related fields for a remote.
type Endpoint struct {
	Username      string
	Token         string
	BearerToken   string
	SkipTLSVerify bool
}

// Resolve resolves the auth method for the given endpoint configuration.
// Order: explicit flags → Entire DB token → git credential helper → anonymous.
func Resolve(raw Endpoint, ep *transport.Endpoint) (transport.AuthMethod, error) {
	if auth := explicitAuth(raw); auth != nil {
		return auth, nil
	}
	if ep == nil {
		return nil, nil
	}
	if ep.Protocol != "http" && ep.Protocol != "https" {
		return nil, nil
	}
	if username, password, ok, err := LookupEntireDBCredential(raw, ep); err != nil {
		return nil, err // issue #7: surface refresh failure explicitly
	} else if ok {
		return &transporthttp.BasicAuth{Username: username, Password: password}, nil
	}
	if username, password, ok := lookupGitCredential(ep); ok {
		return &transporthttp.BasicAuth{Username: username, Password: password}, nil
	}
	return nil, nil
}

func explicitAuth(raw Endpoint) transport.AuthMethod {
	if raw.BearerToken != "" {
		return &transporthttp.TokenAuth{Token: raw.BearerToken}
	}
	if raw.Token != "" {
		username := raw.Username
		if username == "" {
			username = "git"
		}
		return &transporthttp.BasicAuth{Username: username, Password: raw.Token}
	}
	return nil
}

// GitCredentialFillCommand is replaceable for testing.
var GitCredentialFillCommand = func(ctx context.Context, input string) ([]byte, error) {
	cmd := exec.CommandContext(ctx, "git", "credential", "fill")
	cmd.Stdin = strings.NewReader(input)
	return cmd.Output()
}

func lookupGitCredential(ep *transport.Endpoint) (string, string, bool) {
	input := credentialFillInput(ep)
	if input == "" {
		return "", "", false
	}
	output, err := GitCredentialFillCommand(context.Background(), input)
	if err != nil {
		return "", "", false
	}
	values := parseCredentialOutput(output)
	password := values["password"]
	if password == "" {
		return "", "", false
	}
	username := values["username"]
	if username == "" {
		if ep.User != "" {
			username = ep.User
		} else {
			username = "git"
		}
	}
	return username, password, true
}

func credentialFillInput(ep *transport.Endpoint) string {
	if ep == nil || ep.Host == "" {
		return ""
	}
	var b strings.Builder
	fmt.Fprintf(&b, "protocol=%s\nhost=%s\n", ep.Protocol, ep.Host)
	if path := strings.TrimPrefix(ep.Path, "/"); path != "" {
		fmt.Fprintf(&b, "path=%s\n", path)
	}
	if ep.User != "" {
		fmt.Fprintf(&b, "username=%s\n", ep.User)
	}
	b.WriteString("\n")
	return b.String()
}

func parseCredentialOutput(output []byte) map[string]string {
	values := map[string]string{}
	for _, line := range strings.Split(string(output), "\n") {
		line = strings.TrimSpace(line)
		if line == "" {
			continue
		}
		k, v, ok := strings.Cut(line, "=")
		if ok {
			values[k] = v
		}
	}
	return values
}
```

Ainternal/auth/auth.go+119

```
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

package auth

import (
	"context"
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"testing"
	"time"

"github.com/go-git/go-git/v5/plumbing/transport"
	transporthttp "github.com/go-git/go-git/v5/plumbing/transport/http"
	"github.com/zalando/go-keyring"
)

func TestDecodeTokenWithExpiration(t *testing.T) {
	tests := []struct {
		name      string
		encoded   string
		wantToken string
		wantZero  bool   // if true, expect time.Time zero value
		wantUnix  int64  // checked only when wantZero is false
	}{
		{
			name:      "token with pipe-separated unix timestamp",
			encoded:   "mytoken|12345",
			wantToken: "mytoken",
			wantUnix:  12345,
		},
		{
			name:      "plain token without pipe",
			encoded:   "plain-token",
			wantToken: "plain-token",
			wantZero:  true,
		},
		{
			name:      "empty string",
			encoded:   "",
			wantToken: "",
			wantZero:  true,
		},
		{
			name:      "pipe with non-numeric suffix falls back to full string",
			encoded:   "tok|notanumber",
			wantToken: "tok|notanumber",
			wantZero:  true,
		},
		{
			name:      "multiple pipes uses last one",
			encoded:   "a|b|99999",
			wantToken: "a|b",
			wantUnix:  99999,
		},
	}

for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			token, ts := decodeTokenWithExpiration(tt.encoded)
			if token != tt.wantToken {
				t.Errorf("token = %q, want %q", token, tt.wantToken)
			}
			if tt.wantZero {
				if !ts.IsZero() {
					t.Errorf("expected zero time, got %v", ts)
				}
			} else {
				if ts.Unix() != tt.wantUnix {
					t.Errorf("timestamp = %d, want %d", ts.Unix(), tt.wantUnix)
				}
			}
		})
	}
}

func TestTokenExpiredOrExpiring(t *testing.T) {
	tests := []struct {
		name      string
		expiresAt time.Time
		want      bool
	}{
		{
			name:      "zero time is treated as expired",
			expiresAt: time.Time{},
			want:      true,
		},
		{
			name:      "far future is not expired",
			expiresAt: time.Now().Add(1 * time.Hour),
			want:      false,
		},
		{
			name:      "past time is expired",
			expiresAt: time.Now().Add(-1 * time.Hour),
			want:      true,
		},
		{
			name:      "expiring within 5 minute window is treated as expired",
			expiresAt: time.Now().Add(2 * time.Minute),
			want:      true,
		},
		{
			name:      "just beyond 5 minute window is not expired",
			expiresAt: time.Now().Add(10 * time.Minute),
			want:      false,
		},
	}

for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := tokenExpiredOrExpiring(tt.expiresAt)
			if got != tt.want {
				t.Errorf("tokenExpiredOrExpiring(%v) = %v, want %v", tt.expiresAt, got, tt.want)
			}
		})
	}
}

func TestCredentialFillInput(t *testing.T) {
	ep := &transport.Endpoint{
		Protocol: "https",
		Host:     "github.com",
		Path:     "/owner/repo.git",
		User:     "myuser",
	}

got := credentialFillInput(ep)
	want := "protocol=https\nhost=github.com\npath=owner/repo.git\nusername=myuser\n\n"
	if got != want {
		t.Errorf("credentialFillInput returned:\n%q\nwant:\n%q", got, want)
	}
}

func TestCredentialFillInputNilEndpoint(t *testing.T) {
	got := credentialFillInput(nil)
	if got != "" {
		t.Errorf("expected empty string for nil endpoint, got %q", got)
	}
}

func TestCredentialFillInputEmptyHost(t *testing.T) {
	ep := &transport.Endpoint{Protocol: "https"}
	got := credentialFillInput(ep)
	if got != "" {
		t.Errorf("expected empty string for empty host, got %q", got)
	}
}

func TestCredentialFillInputNoUser(t *testing.T) {
	ep := &transport.Endpoint{
		Protocol: "https",
		Host:     "example.com",
		Path:     "/repo.git",
	}
	got := credentialFillInput(ep)
	want := "protocol=https\nhost=example.com\npath=repo.git\n\n"
	if got != want {
		t.Errorf("credentialFillInput returned:\n%q\nwant:\n%q", got, want)
	}
}

func TestParseCredentialOutput(t *testing.T) {
	tests := []struct {
		name       string
		output     string
		wantUser   string
		wantPass   string
		wantLen    int
	}{
		{
			name:     "standard username and password",
			output:   "username=foo\npassword=bar\n",
			wantUser: "foo",
			wantPass: "bar",
			wantLen:  2,
		},
		{
			name:     "with extra fields",
			output:   "protocol=https\nhost=example.com\nusername=alice\npassword=secret\n",
			wantUser: "alice",
			wantPass: "secret",
			wantLen:  4,
		},
		{
			name:    "empty input",
			output:  "",
			wantLen: 0,
		},
		{
			name:    "blank lines only",
			output:  "\n\n\n",
			wantLen: 0,
		},
		{
			name:     "value with equals sign",
			output:   "password=tok=en\n",
			wantPass: "tok=en",
			wantLen:  1,
		},
	}

for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := parseCredentialOutput([]byte(tt.output))
			if len(got) != tt.wantLen {
				t.Errorf("len(result) = %d, want %d; result = %v", len(got), tt.wantLen, got)
			}
			if tt.wantUser != "" {
				if got["username"] != tt.wantUser {
					t.Errorf("username = %q, want %q", got["username"], tt.wantUser)
				}
			}
			if tt.wantPass != "" {
				if got["password"] != tt.wantPass {
					t.Errorf("password = %q, want %q", got["password"], tt.wantPass)
				}
			}
		})
	}
}

func TestResolve(t *testing.T) {
	ep, err := transport.NewEndpoint("https://example.com/repo.git")
	if err != nil {
		t.Fatal(err)
	}

sshEP := &transport.Endpoint{Protocol: "ssh", Host: "example.com", Path: "/repo.git"}

tests := []struct {
		name      string
		raw       Endpoint
		ep        *transport.Endpoint
		mockCred  func(ctx context.Context, input string) ([]byte, error)
		wantType  string // "token", "basic", "nil"
		wantUser  string
		wantPass  string
		wantErr   bool
	}{
		{
			name:     "bearer token set returns TokenAuth",
			raw:      Endpoint{BearerToken: "my-bearer"},
			ep:       ep,
			wantType: "token",
			wantPass: "my-bearer",
		},
		{
			name:     "token with username returns BasicAuth",
			raw:      Endpoint{Token: "my-token", Username: "alice"},
			ep:       ep,
			wantType: "basic",
			wantUser: "alice",
			wantPass: "my-token",
		},
		{
			name:     "token without username returns BasicAuth with git",
			raw:      Endpoint{Token: "my-token"},
			ep:       ep,
			wantType: "basic",
			wantUser: "git",
			wantPass: "my-token",
		},
		{
			name:     "nothing set non-HTTP endpoint returns nil",
			raw:      Endpoint{},
			ep:       sshEP,
			wantType: "nil",
		},
		{
			name: "nothing set HTTP endpoint no credential helper returns nil",
			raw:  Endpoint{},
			ep:   ep,
			mockCred: func(ctx context.Context, input string) ([]byte, error) {
				return nil, fmt.Errorf("no helper")
			},
			wantType: "nil",
		},
	}

for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			// Save and restore GitCredentialFillCommand.
			origCmd := GitCredentialFillCommand
			defer func() { GitCredentialFillCommand = origCmd }()

if tt.mockCred != nil {
				GitCredentialFillCommand = tt.mockCred
			} else {
				// Default mock: no credential helper.
				GitCredentialFillCommand = func(ctx context.Context, input string) ([]byte, error) {
					return nil, fmt.Errorf("no helper")
				}
			}

// Also ensure ENTIRE_CONFIG_DIR points nowhere so EntireDB lookup
			// doesn't find anything.
			t.Setenv("ENTIRE_CONFIG_DIR", t.TempDir())

got, err := Resolve(tt.raw, tt.ep)
			if tt.wantErr {
				if err == nil {
					t.Fatal("expected error, got nil")
				}
				return
			}
			if err != nil {
				t.Fatalf("unexpected error: %v", err)
			}

switch tt.wantType {
			case "nil":
				if got != nil {
					t.Errorf("expected nil auth, got %T", got)
				}
			case "token":
				ta, ok := got.(*transporthttp.TokenAuth)
				if !ok {
					t.Fatalf("expected *TokenAuth, got %T", got)
				}
				if ta.Token != tt.wantPass {
					t.Errorf("token = %q, want %q", ta.Token, tt.wantPass)
				}
			case "basic":
				ba, ok := got.(*transporthttp.BasicAuth)
				if !ok {
					t.Fatalf("expected *BasicAuth, got %T", got)
				}
				if ba.Username != tt.wantUser {
					t.Errorf("username = %q, want %q", ba.Username, tt.wantUser)
				}
				if ba.Password != tt.wantPass {
					t.Errorf("password = %q, want %q", ba.Password, tt.wantPass)
				}
			}
		})
	}
}

func TestExplicitAuth(t *testing.T) {
	tests := []struct {
		name     string
		raw      Endpoint
		wantType string // "token", "basic", "nil"
		wantUser string
		wantPass string
	}{
		{
			name:     "bearer token returns TokenAuth",
			raw:      Endpoint{BearerToken: "bearer-abc"},
			wantType: "token",
			wantPass: "bearer-abc",
		},
		{
			name:     "token with username returns BasicAuth",
			raw:      Endpoint{Token: "tok", Username: "bob"},
			wantType: "basic",
			wantUser: "bob",
			wantPass: "tok",
		},
		{
			name:     "token without username returns BasicAuth with git",
			raw:      Endpoint{Token: "tok"},
			wantType: "basic",
			wantUser: "git",
			wantPass: "tok",
		},
		{
			name:     "nothing set returns nil",
			raw:      Endpoint{},
			wantType: "nil",
		},
	}

for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := explicitAuth(tt.raw)

switch tt.wantType {
			case "nil":
				if got != nil {
					t.Errorf("expected nil, got %T", got)
				}
			case "token":
				ta, ok := got.(*transporthttp.TokenAuth)
				if !ok {
					t.Fatalf("expected *TokenAuth, got %T", got)
				}
				if ta.Token != tt.wantPass {
					t.Errorf("token = %q, want %q", ta.Token, tt.wantPass)
				}
			case "basic":
				ba, ok := got.(*transporthttp.BasicAuth)
				if !ok {
					t.Fatalf("expected *BasicAuth, got %T", got)
				}
				if ba.Username != tt.wantUser {
					t.Errorf("username = %q, want %q", ba.Username, tt.wantUser)
				}
				if ba.Password != tt.wantPass {
					t.Errorf("password = %q, want %q", ba.Password, tt.wantPass)
				}
			}
		})
	}
}

func TestEndpointBaseURL(t *testing.T) {
	tests := []struct {
		name string
		ep   *transport.Endpoint
		want string
	}{
		{
			name: "https host",
			ep:   &transport.Endpoint{Protocol: "https", Host: "example.com"},
			want: "https://example.com",
		},
		{
			name: "http host with port",
			ep:   &transport.Endpoint{Protocol: "http", Host: "example.com", Port: 8080},
			want: "http://example.com:8080",
		},
		{
			name: "nil endpoint",
			ep:   nil,
			want: "",
		},
	}

for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := endpointBaseURL(tt.ep)
			if got != tt.want {
				t.Errorf("endpointBaseURL() = %q, want %q", got, tt.want)
			}
		})
	}
}

func TestEndpointCredentialHost(t *testing.T) {
	tests := []struct {
		name string
		ep   *transport.Endpoint
		want string
	}{
		{
			name: "host without port",
			ep:   &transport.Endpoint{Host: "example.com"},
			want: "example.com",
		},
		{
			name: "host with port",
			ep:   &transport.Endpoint{Host: "example.com", Port: 8080},
			want: "example.com:8080",
		},
		{
			name: "nil endpoint",
			ep:   nil,
			want: "",
		},
	}

for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := endpointCredentialHost(tt.ep)
			if got != tt.want {
				t.Errorf("endpointCredentialHost() = %q, want %q", got, tt.want)
			}
		})
	}
}

func TestReadWriteFileToken(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "tokens.json")

// Write a token and read it back.
	if err := writeFileToken(path, "svc1", "user1", "pass1"); err != nil {
		t.Fatalf("writeFileToken: %v", err)
	}
	got, err := readFileToken(path, "svc1", "user1")
	if err != nil {
		t.Fatalf("readFileToken: %v", err)
	}
	if got != "pass1" {
		t.Errorf("readFileToken = %q, want %q", got, "pass1")
	}

// Read missing service returns ErrNotFound.
	_, err = readFileToken(path, "missing-svc", "user1")
	if !errors.Is(err, keyring.ErrNotFound) {
		t.Errorf("expected ErrNotFound for missing service, got %v", err)
	}

// Write a second service and read each back.
	if err := writeFileToken(path, "svc2", "user2", "pass2"); err != nil {
		t.Fatalf("writeFileToken svc2: %v", err)
	}
	got1, err := readFileToken(path, "svc1", "user1")
	if err != nil {
		t.Fatalf("readFileToken svc1 after second write: %v", err)
	}
	if got1 != "pass1" {
		t.Errorf("svc1 token = %q, want %q", got1, "pass1")
	}
	got2, err := readFileToken(path, "svc2", "user2")
	if err != nil {
		t.Fatalf("readFileToken svc2: %v", err)
	}
	if got2 != "pass2" {
		t.Errorf("svc2 token = %q, want %q", got2, "pass2")
	}

// Read file that doesn't exist returns ErrNotFound.
	_, err = readFileToken(filepath.Join(dir, "nonexistent.json"), "svc1", "user1")
	if !errors.Is(err, keyring.ErrNotFound) {
		t.Errorf("expected ErrNotFound for missing file, got %v", err)
	}
}

func TestIsNotFound(t *testing.T) {
	if !isNotFound(keyring.ErrNotFound) {
		t.Error("expected isNotFound(keyring.ErrNotFound) = true")
	}
	if isNotFound(fmt.Errorf("some other error")) {
		t.Error("expected isNotFound(other error) = false")
	}
	// Wrapped ErrNotFound should also be detected.
	wrapped := fmt.Errorf("wrapped: %w", keyring.ErrNotFound)
	if !isNotFound(wrapped) {
		t.Error("expected isNotFound(wrapped ErrNotFound) = true")
	}
}

func TestReadFileTokenEmptyPath(t *testing.T) {
	_, err := readFileToken("", "svc", "user")
	if !errors.Is(err, keyring.ErrNotFound) {
		t.Errorf("expected ErrNotFound for empty path, got %v", err)
	}
}

func TestWriteFileTokenEmptyPath(t *testing.T) {
	err := writeFileToken("", "svc", "user", "pass")
	if err == nil {
		t.Error("expected error for empty path, got nil")
	}
	if !errors.Is(err, os.ErrInvalid) {
		t.Errorf("expected os.ErrInvalid, got %v", err)
	}
}
```

Ainternal/auth/auth\_test.go+550

package auth

import (
	"context"
	"crypto/tls"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"

"github.com/go-git/go-git/v5/plumbing/transport"
	"github.com/zalando/go-keyring"
)

func isNotFound(err error) bool {
	return errors.Is(err, keyring.ErrNotFound)
}

const entireCLIClientID = "entire-cli"

type entireAuthHostInfo struct {
	ActiveUser string   `json:"activeUser"`
	Users      []string `json:"users"`
}

type oauthTokenResponse struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	ExpiresIn    int64  `json:"expires_in"`
}

// LookupEntireDBCredential looks up credentials from the Entire token store.
// Returns (username, password, true, nil) on success, ("", "", false, nil) when
// no credential is configured, or ("", "", false, err) when a credential exists
// but refresh failed (issue #7).
func LookupEntireDBCredential(raw Endpoint, ep *transport.Endpoint) (string, string, bool, error) {
	if ep == nil || ep.Host == "" {
		return "", "", false, nil
	}
	credHost := endpointCredentialHost(ep)
	token, err := lookupEntireDBToken(credHost, endpointBaseURL(ep), raw.SkipTLSVerify)
	if err != nil {
		return "", "", false, err
	}
	if token == "" {
		return "", "", false, nil
	}
	username := raw.Username
	if username == "" {
		username = "git"
	}
	return username, token, true, nil
}

func endpointBaseURL(ep *transport.Endpoint) string {
	if ep == nil || ep.Host == "" {
		return ""
	}
	scheme := ep.Protocol
	if scheme == "" {
		scheme = "https"
	}
	host := ep.Host
	if ep.Port > 0 {
		host = fmt.Sprintf("%s:%d", host, ep.Port)
	}
	return scheme + "://" + host
}

func endpointCredentialHost(ep *transport.Endpoint) string {
	if ep == nil {
		return ""
	}
	if ep.Port > 0 {
		return fmt.Sprintf("%s:%d", ep.Host, ep.Port)
	}
	return ep.Host
}

func lookupEntireDBToken(host, baseURL string, skipTLS bool) (string, error) {
	configDir := os.Getenv("ENTIRE_CONFIG_DIR")
	if configDir == "" {
		home, err := os.UserHomeDir()
		if err != nil {
			return "", nil // no config dir, not an error
		}
		configDir = filepath.Join(home, ".config", "entire")
	}

username, ok := loadEntireDBActiveUser(host, configDir)
	if !ok || username == "" {
		return "", nil
	}
	return getTokenWithRefresh(context.Background(), host, username, baseURL, skipTLS)
}

func loadEntireDBActiveUser(host, configDir string) (string, bool) {
	data, err := os.ReadFile(filepath.Join(configDir, "hosts.json"))
	if err != nil {
		return "", false
	}
	var hosts map[string]*entireAuthHostInfo
	if err := json.Unmarshal(data, &hosts); err != nil {
		return "", false
	}
	info := hosts[host]
	if info == nil || info.ActiveUser == "" {
		return "", false
	}
	return info.ActiveUser, true
}

// getTokenWithRefresh retrieves a token, refreshing it if expired.
// On refresh failure, returns the stale token with a nil error rather than
// propagating the refresh error silently (issue #7).
func getTokenWithRefresh(ctx context.Context, host, username, baseURL string, skipTLS bool) (string, error) {
	encoded, err := ReadStoredToken(credentialService(host), username)
	if err != nil {
		// "Not found" means no credential is configured — not an error.
		// Only propagate actual storage failures.
		if isNotFound(err) {
			return "", nil
		}
		return "", err
	}
	token, expiresAt := decodeTokenWithExpiration(encoded)
	if token == "" {
		return "", nil
	}
	if !tokenExpiredOrExpiring(expiresAt) {
		return token, nil
	}
	refreshed, err := refreshAccessToken(ctx, host, username, baseURL, skipTLS)
	if err != nil {
		// Issue #7: surface refresh failure explicitly instead of silently reusing stale token.
		return "", fmt.Errorf("token expired and refresh failed for %s@%s: %w", username, host, err)
	}
	return refreshed, nil
}

func decodeTokenWithExpiration(encoded string) (string, time.Time) {
	idx := strings.LastIndex(encoded, "|")
	if idx == -1 {
		return encoded, time.Time{}
	}
	token := encoded[:idx]
	ts, err := strconv.ParseInt(encoded[idx+1:], 10, 64)
	if err != nil {
		return encoded, time.Time{}
	}
	return token, time.Unix(ts, 0)
}

func tokenExpiredOrExpiring(expiresAt time.Time) bool {
	if expiresAt.IsZero() {
		return true
	}
	return time.Now().Add(5 * time.Minute).After(expiresAt)
}

func refreshAccessToken(ctx context.Context, host, username, baseURL string, skipTLS bool) (string, error) {
	refreshToken, err := ReadStoredToken(credentialService(host)+":refresh", username)
	if err != nil {
		return "", err
	}
	if refreshToken == "" || baseURL == "" {
		return "", errors.New("missing refresh token or base url")
	}

form := url.Values{}
	form.Set("grant_type", "refresh_token")
	form.Set("refresh_token", refreshToken)
	form.Set("client_id", entireCLIClientID)

req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(baseURL, "/")+"/oauth/token", strings.NewReader(form.Encode()))
	if err != nil {
		return "", err
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

client := &http.Client{
		Timeout: 30 * time.Second,
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: skipTLS}, //nolint:gosec
		},
	}
	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("refresh failed with status %d", resp.StatusCode)
	}

var tokenResp oauthTokenResponse
	if err := json.NewDecoder(resp.Body).Decode(&tokenResp); err != nil {
		return "", err
	}
	if tokenResp.AccessToken == "" {
		return "", errors.New("empty access token in refresh response")
	}

if err := WriteStoredToken(
		credentialService(host),
		username,
		encodeTokenWithExpiration(tokenResp.AccessToken, tokenResp.ExpiresIn),
	); err != nil {
		return "", err
	}
	if tokenResp.RefreshToken != "" {
		_ = WriteStoredToken(credentialService(host)+":refresh", username, tokenResp.RefreshToken)
	}
	return tokenResp.AccessToken, nil
}

func encodeTokenWithExpiration(token string, expiresIn int64) string {
	return fmt.Sprintf("%s|%d", token, time.Now().Unix()+expiresIn)
}

func credentialService(host string) string {
	return "entire:" + host
}
```

Ainternal/auth/entiredb.go+229

```
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

package auth

import (
	"encoding/json"
	"os"
	"path/filepath"
	"syscall"

"github.com/zalando/go-keyring"
)

// ReadStoredToken reads a token from the configured store (keyring or file).
func ReadStoredToken(service, username string) (string, error) {
	if os.Getenv("ENTIRE_TOKEN_STORE") == "file" {
		return readFileToken(fileTokenPath(), service, username)
	}
	return keyring.Get(service, username)
}

// WriteStoredToken writes a token to the configured store.
func WriteStoredToken(service, username, password string) error {
	if os.Getenv("ENTIRE_TOKEN_STORE") == "file" {
		return writeFileToken(fileTokenPath(), service, username, password)
	}
	return keyring.Set(service, username, password)
}

func fileTokenPath() string {
	path := os.Getenv("ENTIRE_TOKEN_STORE_PATH")
	if path != "" {
		return path
	}
	home, err := os.UserHomeDir()
	if err != nil {
		return ""
	}
	return filepath.Join(home, ".config", "entiredb", "tokens.json")
}

func readFileToken(path, service, username string) (string, error) {
	if path == "" {
		return "", keyring.ErrNotFound
	}
	// Acquire shared lock for concurrent read safety (issue #10).
	unlock, err := flockShared(path)
	if err != nil {
		// If we can't lock (e.g., file doesn't exist yet), fall through to direct read.
		return readFileTokenDirect(path, service, username)
	}
	defer unlock()
	return readFileTokenDirect(path, service, username)
}

func readFileTokenDirect(path, service, username string) (string, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		if os.IsNotExist(err) {
			return "", keyring.ErrNotFound
		}
		return "", err
	}
	var store map[string]map[string]string
	if err := json.Unmarshal(data, &store); err != nil {
		return "", err
	}
	users := store[service]
	if users == nil {
		return "", keyring.ErrNotFound
	}
	password, ok := users[username]
	if !ok {
		return "", keyring.ErrNotFound
	}
	return password, nil
}

// writeFileToken writes a token to the file store with exclusive file locking
// to prevent corruption from concurrent processes (issue #10).
func writeFileToken(path, service, username, password string) error {
	if path == "" {
		return os.ErrInvalid
	}
	if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
		return err
	}

// Acquire exclusive lock for the write.
	unlock, err := flockExclusive(path)
	if err != nil {
		return err
	}
	defer unlock()

// Re-read under lock to avoid lost updates.
	store := map[string]map[string]string{}
	if data, err := os.ReadFile(path); err == nil {
		if err := json.Unmarshal(data, &store); err != nil {
			return err
		}
	} else if !os.IsNotExist(err) {
		return err
	}
	if store[service] == nil {
		store[service] = map[string]string{}
	}
	store[service][username] = password
	data, err := json.Marshal(store)
	if err != nil {
		return err
	}
	// Atomic write: write to temp file then rename to prevent corruption on crash.
	tmp := path + ".tmp"
	if err := os.WriteFile(tmp, data, 0o600); err != nil {
		return err
	}
	return os.Rename(tmp, path)
}

// flockShared acquires a shared (read) lock on path+".lock".
func flockShared(path string) (func(), error) {
	return flockOpen(path+".lock", syscall.LOCK_SH)
}

// flockExclusive acquires an exclusive (write) lock on path+".lock".
func flockExclusive(path string) (func(), error) {
	return flockOpen(path+".lock", syscall.LOCK_EX)
}

func flockOpen(lockPath string, how int) (func(), error) {
	f, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0o600)
	if err != nil {
		return nil, err
	}
	if err := syscall.Flock(int(f.Fd()), how); err != nil {
		f.Close()
		return nil, err
	}
	return func() {
		_ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
		f.Close()
	}, nil
}
```

Ainternal/auth/tokenstore.go+142

```
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

package gitproto

import (
	"bytes"
	"fmt"
	"strings"
	"testing"
)

func BenchmarkPacketReaderData(b *testing.B) {
	// Build a wire-format buffer containing 1000 data packets.
	// Each packet is "0009data\n" (4-byte length + "data\n" = 9 bytes total).
	var wire strings.Builder
	const packetCount = 1000
	payload := "data\n"
	pkt := FormatPktLine(payload)
	for i := 0; i < packetCount; i++ {
		wire.WriteString(pkt)
	}
	wire.WriteString("0000") // flush to terminate
	data := wire.String()

b.ResetTimer()
	for i := 0; i < b.N; i++ {
		reader := NewPacketReader(bytes.NewBufferString(data))
		for j := 0; j < packetCount; j++ {
			kind, p, err := reader.ReadPacket()
			if err != nil {
				b.Fatal(err)
			}
			if kind != PacketData || len(p) == 0 {
				b.Fatalf("unexpected packet: kind=%v len=%d", kind, len(p))
			}
		}
		// Read the trailing flush.
		kind, _, err := reader.ReadPacket()
		if err != nil {
			b.Fatal(err)
		}
		if kind != PacketFlush {
			b.Fatalf("expected flush, got %v", kind)
		}
	}
}

func BenchmarkDecodeV2Capabilities(b *testing.B) {
	// Build a capability advertisement with 10 capabilities.
	var wire strings.Builder
	wire.WriteString(FormatPktLine("version 2\n"))
	for i := 0; i < 10; i++ {
		line := fmt.Sprintf("capability-%d=value-%d\n", i, i)
		wire.WriteString(FormatPktLine(line))
	}
	wire.WriteString("0000") // flush
	data := wire.String()

b.ResetTimer()
	for i := 0; i < b.N; i++ {
		caps, err := DecodeV2Capabilities(bytes.NewBufferString(data))
		if err != nil {
			b.Fatal(err)
		}
		if len(caps.Caps) != 10 {
			b.Fatalf("expected 10 capabilities, got %d", len(caps.Caps))
		}
	}
}

func BenchmarkEncodeCommand(b *testing.B) {
	// Build a fetch command with 50 wants.
	capArgs := []string{"agent=git-sync/bench"}
	cmdArgs := make([]string, 0, 52)
	cmdArgs = append(cmdArgs, "ofs-delta", "no-progress")
	for i := 0; i < 50; i++ {
		cmdArgs = append(cmdArgs, fmt.Sprintf("want %040x", i+1))
	}

b.ResetTimer()
	for i := 0; i < b.N; i++ {
		data, err := EncodeCommand("fetch", capArgs, cmdArgs)
		if err != nil {
			b.Fatal(err)
		}
		if len(data) == 0 {
			b.Fatal("empty encoded command")
		}
	}
}
```

Ainternal/gitproto/benchmark\_test.go+88

```
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

package gitproto

import (
	"fmt"
	"io"
	"sort"
	"strings"

"github.com/go-git/go-git/v5/plumbing/protocol/packp/capability"
)

// V2Capabilities represents a parsed protocol v2 capability advertisement.
type V2Capabilities struct {
	Caps map[string]string
}

// Supports reports whether the server advertises the named capability.
func (c *V2Capabilities) Supports(name string) bool {
	if c == nil {
		return false
	}
	_, ok := c.Caps[name]
	return ok
}

// Value returns the value string for the named capability.
func (c *V2Capabilities) Value(name string) string {
	if c == nil {
		return ""
	}
	return c.Caps[name]
}

// FetchSupports checks whether a specific feature is listed in the
// "fetch" capability value (space-separated feature list).
func (c *V2Capabilities) FetchSupports(feature string) bool {
	if c == nil {
		return false
	}
	for _, f := range strings.Fields(c.Value("fetch")) {
		if f == feature {
			return true
		}
	}
	return false
}

// SortedKeys returns the capabilities as sorted "key" or "key=value" strings.
func (c *V2Capabilities) SortedKeys() []string {
	if c == nil {
		return nil
	}
	keys := make([]string, 0, len(c.Caps))
	for k, v := range c.Caps {
		if v == "" {
			keys = append(keys, k)
		} else {
			keys = append(keys, k+"="+v)
		}
	}
	sort.Strings(keys)
	return keys
}

// RequestCapabilities builds the capability arguments for a v2 command request.
func (c *V2Capabilities) RequestCapabilities() []string {
	var caps []string
	if agent := c.Value("agent"); agent != "" {
		caps = append(caps, "agent="+capability.DefaultAgent())
	}
	return caps
}

// DecodeV2Capabilities parses a protocol v2 capability advertisement from an
// info/refs response body.
func DecodeV2Capabilities(r io.Reader) (*V2Capabilities, error) {
	reader := NewPacketReader(r)

// Skip service line and find "version 2\n"
	for {
		kind, payload, err := reader.ReadPacket()
		if err != nil {
			return nil, err
		}
		if kind == PacketFlush {
			continue
		}
		if kind != PacketData {
			return nil, fmt.Errorf("unexpected packet type %v before protocol advertisement", kind)
		}
		if strings.HasPrefix(string(payload), "# service=") {
			continue
		}
		if string(payload) != "version 2\n" {
			return nil, fmt.Errorf("unexpected protocol advertisement %q", payload)
		}
		break
	}

caps := &V2Capabilities{Caps: make(map[string]string)}
	for {
		kind, payload, err := reader.ReadPacket()
		if err != nil {
			return nil, err
		}
		if kind == PacketFlush {
			return caps, nil
		}
		if kind != PacketData {
			return nil, fmt.Errorf("unexpected packet type %v in capability advertisement", kind)
		}
		line := strings.TrimSuffix(string(payload), "\n")
		name, value, _ := strings.Cut(line, "=")
		caps.Caps[name] = value
	}
}

// PreferredSideband returns the best sideband capability supported by the
// server. Prefers sideband-64k over sideband (issue #4: sideband preference
// was backwards in original code).
func PreferredSideband(caps *capability.List) capability.Capability {
	if caps.Supports(capability.Sideband64k) {
		return capability.Sideband64k
	}
	if caps.Supports(capability.Sideband) {
		return capability.Sideband
	}
	return ""
}
```

Ainternal/gitproto/capability.go+129

package gitproto

import (
	"testing"

"github.com/go-git/go-git/v5/plumbing/protocol/packp/capability"
)

func TestV2CapabilitiesFetchSupports(t *testing.T) {
	caps := &V2Capabilities{
		Caps: map[string]string{
			"fetch": "thin-pack filter",
			"agent": "git/test",
		},
	}

tests := []struct {
		feature string
		want    bool
	}{
		{"filter", true},
		{"thin-pack", true},
		{"missing", false},
		{"thin", false},
		{"", false},
	}

for _, tt := range tests {
		t.Run(tt.feature, func(t *testing.T) {
			got := caps.FetchSupports(tt.feature)
			if got != tt.want {
				t.Errorf("FetchSupports(%q) = %v, want %v", tt.feature, got, tt.want)
			}
		})
	}

// nil receiver should always return false.
	var nilCaps *V2Capabilities
	if nilCaps.FetchSupports("filter") {
		t.Error("nil V2Capabilities.FetchSupports should return false")
	}
}

func TestV2CapabilitiesSortedKeys(t *testing.T) {
	caps := &V2Capabilities{
		Caps: map[string]string{
			"fetch":   "shallow",
			"ls-refs": "",
			"agent":   "git/test",
		},
	}

got := caps.SortedKeys()
	want := []string{
		"agent=git/test",
		"fetch=shallow",
		"ls-refs",
	}
	if len(got) != len(want) {
		t.Fatalf("SortedKeys() returned %d items, want %d", len(got), len(want))
	}
	for i := range got {
		if got[i] != want[i] {
			t.Errorf("SortedKeys()[%d] = %q, want %q", i, got[i], want[i])
		}
	}

// nil receiver should return nil.
	var nilCaps *V2Capabilities
	if keys := nilCaps.SortedKeys(); keys != nil {
		t.Errorf("nil V2Capabilities.SortedKeys() = %v, want nil", keys)
	}
}

func TestV2CapabilitiesSupportsAndValue(t *testing.T) {
	caps := &V2Capabilities{
		Caps: map[string]string{
			"fetch":   "shallow",
			"ls-refs": "",
		},
	}

if !caps.Supports("fetch") {
		t.Error("expected Supports(fetch) = true")
	}
	if !caps.Supports("ls-refs") {
		t.Error("expected Supports(ls-refs) = true")
	}
	if caps.Supports("push") {
		t.Error("expected Supports(push) = false")
	}
	if got := caps.Value("fetch"); got != "shallow" {
		t.Errorf("Value(fetch) = %q, want %q", got, "shallow")
	}
	if got := caps.Value("ls-refs"); got != "" {
		t.Errorf("Value(ls-refs) = %q, want empty", got)
	}
	if got := caps.Value("push"); got != "" {
		t.Errorf("Value(push) = %q, want empty", got)
	}

// nil receiver tests.
	var nilCaps *V2Capabilities
	if nilCaps.Supports("fetch") {
		t.Error("nil V2Capabilities.Supports should return false")
	}
	if got := nilCaps.Value("fetch"); got != "" {
		t.Errorf("nil V2Capabilities.Value should return empty, got %q", got)
	}
}

func TestPreferredSideband(t *testing.T) {
	tests := []struct {
		name string
		caps []capability.Capability
		want capability.Capability
	}{
		{
			name: "both supported prefers 64k",
			caps: []capability.Capability{capability.Sideband, capability.Sideband64k},
			want: capability.Sideband64k,
		},
		{
			name: "only sideband",
			caps: []capability.Capability{capability.Sideband},
			want: capability.Sideband,
		},
		{
			name: "only sideband64k",
			caps: []capability.Capability{capability.Sideband64k},
			want: capability.Sideband64k,
		},
		{
			name: "neither supported",
			caps: []capability.Capability{capability.NoProgress},
			want: "",
		},
		{
			name: "empty capabilities",
			caps: nil,
			want: "",
		},
	}

for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			list := capability.NewList()
			for _, c := range tt.caps {
				_ = list.Set(c)
			}
			got := PreferredSideband(list)
			if got != tt.want {
				t.Errorf("PreferredSideband() = %q, want %q", got, tt.want)
			}
		})
	}
}

func TestRequestCapabilities(t *testing.T) {
	// With agent set, RequestCapabilities should return an agent line.
	caps := &V2Capabilities{
		Caps: map[string]string{
			"agent":   "git/test",
			"ls-refs": "",
		},
	}
	got := caps.RequestCapabilities()
	if len(got) != 1 {
		t.Fatalf("RequestCapabilities() returned %d items, want 1", len(got))
	}
	if got[0] != "agent="+capability.DefaultAgent() {
		t.Errorf("RequestCapabilities()[0] = %q, want %q", got[0], "agent="+capability.DefaultAgent())
	}

// Without agent, RequestCapabilities should return empty.
	capsNoAgent := &V2Capabilities{
		Caps: map[string]string{
			"ls-refs": "",
			"fetch":   "shallow",
		},
	}
	got = capsNoAgent.RequestCapabilities()
	if len(got) != 0 {
		t.Errorf("RequestCapabilities() without agent returned %d items, want 0", len(got))
	}
}
```

Ainternal/gitproto/capability\_test.go+186

```
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

package gitproto

import (
	"fmt"
	"io"

"github.com/go-git/go-git/v5/plumbing"
)

// PlannerDesired is the subset of planner.DesiredRef fields needed by gitproto.
// This avoids a circular import between gitproto and planner.
type PlannerDesired struct {
	SourceRef  plumbing.ReferenceName
	TargetRef  plumbing.ReferenceName
	SourceHash plumbing.Hash
	IsTag      bool
}

// ToPushCommands converts a slice of plan-like structs to PushCommands.
// Used by all strategy packages to avoid copy-pasting the conversion.
func ToPushCommands(plans []PushPlan) []PushCommand {
	cmds := make([]PushCommand, 0, len(plans))
	for _, p := range plans {
		cmd := PushCommand{Name: p.TargetRef, Old: p.TargetHash}
		if p.Delete {
			cmd.Delete = true
		} else {
			cmd.New = p.SourceHash
		}
		cmds = append(cmds, cmd)
	}
	return cmds
}

// PushPlan is a minimal interface for plan-to-command conversion.
type PushPlan struct {
	TargetRef  plumbing.ReferenceName
	TargetHash plumbing.Hash
	SourceHash plumbing.Hash
	Delete     bool
}

// LimitPackReader wraps a ReadCloser with a byte limit. Shared across strategies.
func LimitPackReader(r io.ReadCloser, maxBytes int64) io.ReadCloser {
	if maxBytes <= 0 {
		return r
	}
	return &packLimitRC{ReadCloser: r, max: maxBytes}
}

type packLimitRC struct {
	io.ReadCloser
	max  int64
	read int64
}

func (r *packLimitRC) Read(p []byte) (int, error) {
	n, err := r.ReadCloser.Read(p)
	r.read += int64(n)
	if r.read > r.max {
		return n, fmt.Errorf("source pack exceeded max-pack-bytes limit (%d)", r.max)
	}
	return n, err
}
```

Ainternal/gitproto/convert.go+64

package gitproto

import (
	"io"
	"strings"
	"testing"

"github.com/go-git/go-git/v5/plumbing"
)

func TestToPushCommands(t *testing.T) {
	hashA := plumbing.NewHash("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
	hashB := plumbing.NewHash("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")

tests := []struct {
		name       string
		plan       PushPlan
		wantNew    plumbing.Hash
		wantOld    plumbing.Hash
		wantDelete bool
	}{
		{
			name: "create command",
			plan: PushPlan{
				TargetRef:  "refs/heads/main",
				TargetHash: plumbing.ZeroHash,
				SourceHash: hashA,
			},
			wantNew: hashA,
			wantOld: plumbing.ZeroHash,
		},
		{
			name: "update command",
			plan: PushPlan{
				TargetRef:  "refs/heads/main",
				TargetHash: hashA,
				SourceHash: hashB,
			},
			wantNew: hashB,
			wantOld: hashA,
		},
		{
			name: "delete command",
			plan: PushPlan{
				TargetRef:  "refs/heads/old-branch",
				TargetHash: hashA,
				Delete:     true,
			},
			wantOld:    hashA,
			wantDelete: true,
		},
	}

for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			cmds := ToPushCommands([]PushPlan{tt.plan})
			if len(cmds) != 1 {
				t.Fatalf("expected 1 command, got %d", len(cmds))
			}
			cmd := cmds[0]
			if cmd.Name != tt.plan.TargetRef {
				t.Errorf("Name = %s, want %s", cmd.Name, tt.plan.TargetRef)
			}
			if cmd.Old != tt.wantOld {
				t.Errorf("Old = %s, want %s", cmd.Old, tt.wantOld)
			}
			if cmd.Delete != tt.wantDelete {
				t.Errorf("Delete = %v, want %v", cmd.Delete, tt.wantDelete)
			}
			if !tt.wantDelete && cmd.New != tt.wantNew {
				t.Errorf("New = %s, want %s", cmd.New, tt.wantNew)
			}
		})
	}
}

func TestToPushCommandsMultiple(t *testing.T) {
	plans := []PushPlan{
		{TargetRef: "refs/heads/a", SourceHash: plumbing.NewHash("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")},
		{TargetRef: "refs/heads/b", SourceHash: plumbing.NewHash("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")},
		{TargetRef: "refs/heads/c", TargetHash: plumbing.NewHash("cccccccccccccccccccccccccccccccccccccccc"), Delete: true},
	}
	cmds := ToPushCommands(plans)
	if len(cmds) != 3 {
		t.Fatalf("expected 3 commands, got %d", len(cmds))
	}
}

func TestToPushCommandsEmpty(t *testing.T) {
	cmds := ToPushCommands(nil)
	if len(cmds) != 0 {
		t.Fatalf("expected 0 commands for nil input, got %d", len(cmds))
	}
}

func TestLimitPackReaderWithinLimit(t *testing.T) {
	data := "hello world"
	rc := io.NopCloser(strings.NewReader(data))
	limited := LimitPackReader(rc, 1024)
	defer limited.Close()

got, err := io.ReadAll(limited)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if string(got) != data {
		t.Errorf("got %q, want %q", got, data)
	}
}

func TestLimitPackReaderExceedsLimit(t *testing.T) {
	data := "this is more than ten bytes of data"
	rc := io.NopCloser(strings.NewReader(data))
	limited := LimitPackReader(rc, 10)
	defer limited.Close()

_, err := io.ReadAll(limited)
	if err == nil {
		t.Fatal("expected error when exceeding limit, got nil")
	}
	if !strings.Contains(err.Error(), "source pack exceeded max-pack-bytes limit") {
		t.Errorf("unexpected error message: %v", err)
	}
}

func TestLimitPackReaderZeroLimitPassesThrough(t *testing.T) {
	data := "unlimited data"
	rc := io.NopCloser(strings.NewReader(data))
	limited := LimitPackReader(rc, 0)
	defer limited.Close()

got, err := io.ReadAll(limited)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if string(got) != data {
		t.Errorf("got %q, want %q", got, data)
	}
}

func TestLimitPackReaderNegativeLimitPassesThrough(t *testing.T) {
	data := "unlimited data"
	rc := io.NopCloser(strings.NewReader(data))
	limited := LimitPackReader(rc, -1)
	defer limited.Close()

got, err := io.ReadAll(limited)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if string(got) != data {
		t.Errorf("got %q, want %q", got, data)
	}
}

func TestSortedUniqueHashes(t *testing.T) {
	hashA := plumbing.NewHash("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
	hashB := plumbing.NewHash("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")
	hashC := plumbing.NewHash("cccccccccccccccccccccccccccccccccccccccc")

tests := []struct {
		name  string
		input []plumbing.Hash
		want  []plumbing.Hash
	}{
		{
			name:  "deduplicates repeated hashes",
			input: []plumbing.Hash{hashA, hashB, hashA, hashC, hashB},
			want:  []plumbing.Hash{hashA, hashB, hashC},
		},
		{
			name:  "already sorted and unique is unchanged",
			input: []plumbing.Hash{hashA, hashB, hashC},
			want:  []plumbing.Hash{hashA, hashB, hashC},
		},
		{
			name:  "reverse order gets sorted",
			input: []plumbing.Hash{hashC, hashB, hashA},
			want:  []plumbing.Hash{hashA, hashB, hashC},
		},
		{
			name:  "single element",
			input: []plumbing.Hash{hashB},
			want:  []plumbing.Hash{hashB},
		},
		{
			name:  "empty input",
			input: []plumbing.Hash{},
			want:  []plumbing.Hash{},
		},
		{
			name:  "nil input",
			input: nil,
			want:  []plumbing.Hash{},
		},
	}

for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := SortedUniqueHashes(tt.input)
			if len(got) != len(tt.want) {
				t.Fatalf("len = %d, want %d", len(got), len(tt.want))
			}
			for i := range got {
				if got[i] != tt.want[i] {
					t.Errorf("index %d: got %s, want %s", i, got[i], tt.want[i])
				}
			}
		})
	}
}
```

Ainternal/gitproto/convert\_test.go+211

package gitproto

import (
	"context"
	"errors"
	"fmt"
	"io"
	"strings"

git "github.com/go-git/go-git/v5"
	"github.com/go-git/go-git/v5/plumbing"
	"github.com/go-git/go-git/v5/plumbing/format/packfile"
	"github.com/go-git/go-git/v5/plumbing/protocol/packp"
	"github.com/go-git/go-git/v5/plumbing/protocol/packp/capability"
	"github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband"
	"github.com/go-git/go-git/v5/plumbing/storer"
	"github.com/go-git/go-git/v5/plumbing/transport"
	"github.com/go-git/go-git/v5/utils/ioutil"
)

// DesiredRef describes a single ref we want to fetch from source.
type DesiredRef struct {
	SourceRef  plumbing.ReferenceName
	TargetRef  plumbing.ReferenceName
	SourceHash plumbing.Hash
	IsTag      bool
}

// FetchToStore fetches objects from source into the given store, using the
// appropriate protocol version.
func (s *RefService) FetchToStore(
	ctx context.Context,
	store storer.Storer,
	conn *Conn,
	desired map[plumbing.ReferenceName]DesiredRef,
	targetRefs map[plumbing.ReferenceName]plumbing.Hash,
) error {
	switch s.Protocol {
	case "v2":
		return fetchToStoreV2(ctx, store, conn, s.V2Caps, desired, targetRefs)
	case "v1":
		return fetchToStoreV1(ctx, store, conn, s.V1Adv, desired, targetRefs)
	default:
		return fmt.Errorf("unsupported source protocol %q", s.Protocol)
	}
}

// FetchPack fetches a packfile from source and returns the pack stream as a reader.
// Caller must close the returned ReadCloser.
func (s *RefService) FetchPack(
	ctx context.Context,
	conn *Conn,
	desired map[plumbing.ReferenceName]DesiredRef,
	targetRefs map[plumbing.ReferenceName]plumbing.Hash,
) (io.ReadCloser, error) {
	switch s.Protocol {
	case "v2":
		return fetchPackV2(ctx, conn, s.V2Caps, desired, targetRefs)
	case "v1":
		return fetchPackV1(ctx, conn, s.V1Adv, desired, targetRefs)
	default:
		return nil, fmt.Errorf("unsupported source protocol %q", s.Protocol)
	}
}

// FetchCommitGraph fetches only the commit graph (tree:0 filter) for a ref.
// Requires v2 with filter support.
func (s *RefService) FetchCommitGraph(
	ctx context.Context,
	store storer.Storer,
	conn *Conn,
	ref DesiredRef,
) error {
	if s.Protocol != "v2" {
		return fmt.Errorf("commit graph fetch requires protocol v2")
	}
	if !s.V2Caps.FetchSupports("filter") {
		return fmt.Errorf("source does not advertise fetch filter support")
	}

cmdArgs := []string{
		"ofs-delta",
		"no-progress",
		"filter tree:0",
		"want " + ref.SourceHash.String(),
		"done",
	}
	body, err := EncodeCommand("fetch", s.V2Caps.RequestCapabilities(), cmdArgs)
	if err != nil {
		return err
	}
	reader, err := PostRPCStream(ctx, conn, transport.UploadPackServiceName, body, true, "upload-pack fetch")
	if err != nil {
		return err
	}
	defer ioutil.CheckClose(reader, &err)
	return storeV2FetchPack(store, reader)
}

// Capabilities returns the sorted capability list for display.
func (s *RefService) Capabilities() []string {
	switch s.Protocol {
	case "v2":
		return s.V2Caps.SortedKeys()
	case "v1":
		return AdvRefsCaps(s.V1Adv)
	default:
		return nil
	}
}

// --- V2 fetch implementation ---

func fetchToStoreV2(
	ctx context.Context,
	store storer.Storer,
	conn *Conn,
	caps *V2Capabilities,
	desired map[plumbing.ReferenceName]DesiredRef,
	targetRefs map[plumbing.ReferenceName]plumbing.Hash,
) error {
	wants := collectWants(desired)
	haves := SortedUniqueHashes(refValues(targetRefs))
	if len(wants) == 0 {
		return git.NoErrAlreadyUpToDate
	}

cmdArgs := make([]string, 0, len(wants)+len(haves)+4)
	cmdArgs = append(cmdArgs, "ofs-delta", "no-progress")
	for _, h := range wants {
		cmdArgs = append(cmdArgs, "want "+h.String())
	}
	for _, h := range haves {
		cmdArgs = append(cmdArgs, "have "+h.String())
	}
	cmdArgs = append(cmdArgs, "done")

body, err := EncodeCommand("fetch", caps.RequestCapabilities(), cmdArgs)
	if err != nil {
		return err
	}
	reader, err := PostRPCStream(ctx, conn, transport.UploadPackServiceName, body, true, "upload-pack fetch")
	if err != nil {
		return err
	}
	defer ioutil.CheckClose(reader, &err)
	return storeV2FetchPack(store, reader)
}

func fetchPackV2(
	ctx context.Context,
	conn *Conn,
	caps *V2Capabilities,
	desired map[plumbing.ReferenceName]DesiredRef,
	targetRefs map[plumbing.ReferenceName]plumbing.Hash,
) (io.ReadCloser, error) {
	wants := collectWants(desired)
	haves := SortedUniqueHashes(refValues(targetRefs))
	if len(wants) == 0 {
		return nil, git.NoErrAlreadyUpToDate
	}

cmdArgs := make([]string, 0, len(wants)+len(haves)+4)
	cmdArgs = append(cmdArgs, "ofs-delta", "no-progress")
	// Only request include-tag if the server supports it (issue #6).
	if hasTag(desired) && caps.FetchSupports("include-tag") {
		cmdArgs = append(cmdArgs, "include-tag")
	}
	for _, h := range wants {
		cmdArgs = append(cmdArgs, "want "+h.String())
	}
	for _, h := range haves {
		cmdArgs = append(cmdArgs, "have "+h.String())
	}
	cmdArgs = append(cmdArgs, "done")

body, err := EncodeCommand("fetch", caps.RequestCapabilities(), cmdArgs)
	if err != nil {
		return nil, err
	}
	reader, err := PostRPCStream(ctx, conn, transport.UploadPackServiceName, body, true, "upload-pack fetch")
	if err != nil {
		return nil, err
	}
	packStream, err := openV2PackStream(reader)
	if err != nil {
		_ = reader.Close()
		return nil, err
	}
	return packStream, nil
}

func storeV2FetchPack(store storer.Storer, r io.Reader) error {
	reader := NewPacketReader(r)
	for {
		kind, payload, err := reader.ReadPacket()
		if err != nil {
			if errors.Is(err, io.EOF) {
				return nil
			}
			return fmt.Errorf("decode protocol v2 fetch response: %w", err)
		}
		switch kind {
		case PacketFlush:
			return nil
		case PacketDelim, PacketResponseEnd:
			continue
		case PacketData:
			line := string(payload)
			switch line {
			case "packfile\n":
				demux := sideband.NewDemuxer(sideband.Sideband64k, reader.BufReader())
				return packfile.UpdateObjectStorage(store, demux)
			case "acknowledgments\n", "shallow-info\n":
				if err := SkipSection(reader); err != nil {
					return err
				}
			default:
				return fmt.Errorf("unexpected protocol v2 fetch section %q", strings.TrimSpace(line))
			}
		}
	}
}

func openV2PackStream(body io.ReadCloser) (io.ReadCloser, error) {
	reader := NewPacketReader(body)
	for {
		kind, payload, err := reader.ReadPacket()
		if err != nil {
			if errors.Is(err, io.EOF) {
				return nil, io.ErrUnexpectedEOF
			}
			return nil, fmt.Errorf("decode protocol v2 fetch response: %w", err)
		}
		switch kind {
		case PacketFlush:
			return nil, io.ErrUnexpectedEOF
		case PacketDelim, PacketResponseEnd:
			continue
		case PacketData:
			line := string(payload)
			switch line {
			case "packfile\n":
				return &wrappedRC{
					Reader: sideband.NewDemuxer(sideband.Sideband64k, reader.BufReader()),
					Closer: body,
				}, nil
			case "acknowledgments\n", "shallow-info\n":
				if err := SkipSection(reader); err != nil {
					return nil, err
				}
			default:
				return nil, fmt.Errorf("unexpected protocol v2 fetch section %q", strings.TrimSpace(line))
			}
		}
	}
}

// --- V1 fetch implementation ---

func fetchToStoreV1(
	ctx context.Context,
	store storer.Storer,
	conn *Conn,
	adv *packp.AdvRefs,
	desired map[plumbing.ReferenceName]DesiredRef,
	targetRefs map[plumbing.ReferenceName]plumbing.Hash,
) error {
	session, err := conn.Transport.NewUploadPackSession(conn.Endpoint, conn.Auth)
	if err != nil {
		return fmt.Errorf("open source upload-pack session: %w", err)
	}
	defer session.Close()

req := packp.NewUploadPackRequestFromCapabilities(adv.Capabilities)
	for _, ref := range desired {
		req.Wants = append(req.Wants, ref.SourceHash)
	}
	req.Wants = SortedUniqueHashes(req.Wants)
	req.Haves = SortedUniqueHashes(refValues(targetRefs))
	if len(req.Wants) == 0 {
		return git.NoErrAlreadyUpToDate
	}
	if adv.Capabilities.Supports(capability.NoProgress) {
		_ = req.Capabilities.Set(capability.NoProgress)
	}
	if hasTag(desired) && adv.Capabilities.Supports(capability.IncludeTag) {
		_ = req.Capabilities.Set(capability.IncludeTag)
	}

reader, err := session.UploadPack(ctx, req)
	if err != nil {
		if errors.Is(err, transport.ErrEmptyUploadPackRequest) {
			return git.NoErrAlreadyUpToDate
		}
		return fmt.Errorf("source upload-pack: %w", err)
	}
	defer ioutil.CheckClose(reader, &err)

sbReader := buildSidebandReader(req.Capabilities, reader, nil)
	return packfile.UpdateObjectStorage(store, sbReader)
}

func fetchPackV1(
	ctx context.Context,
	conn *Conn,
	adv *packp.AdvRefs,
	desired map[plumbing.ReferenceName]DesiredRef,
	targetRefs map[plumbing.ReferenceName]plumbing.Hash,
) (io.ReadCloser, error) {
	session, err := conn.Transport.NewUploadPackSession(conn.Endpoint, conn.Auth)
	if err != nil {
		return nil, fmt.Errorf("open source upload-pack session: %w", err)
	}

req := packp.NewUploadPackRequestFromCapabilities(adv.Capabilities)
	for _, ref := range desired {
		req.Wants = append(req.Wants, ref.SourceHash)
	}
	req.Wants = SortedUniqueHashes(req.Wants)
	req.Haves = SortedUniqueHashes(refValues(targetRefs))
	if len(req.Wants) == 0 {
		_ = session.Close()
		return nil, git.NoErrAlreadyUpToDate
	}
	if adv.Capabilities.Supports(capability.NoProgress) {
		_ = req.Capabilities.Set(capability.NoProgress)
	}
	if hasTag(desired) && adv.Capabilities.Supports(capability.IncludeTag) {
		_ = req.Capabilities.Set(capability.IncludeTag)
	}

reader, err := session.UploadPack(ctx, req)
	if err != nil {
		_ = session.Close()
		if errors.Is(err, transport.ErrEmptyUploadPackRequest) {
			return nil, git.NoErrAlreadyUpToDate
		}
		return nil, fmt.Errorf("source upload-pack: %w", err)
	}
	return &sessionRC{
		Reader: buildSidebandReader(req.Capabilities, reader, nil),
		closeFn: func() error {
			_ = reader.Close()
			return session.Close()
		},
	}, nil
}

// buildSidebandReader wraps a reader with sideband demuxing if the negotiated
// capabilities include sideband support. Delegates to PreferredSideband (issue #4).
func buildSidebandReader(caps *capability.List, reader io.Reader, progress sideband.Progress) io.Reader {
	sb := PreferredSideband(caps)
	if sb == "" {
		return reader
	}
	var t sideband.Type
	if sb == capability.Sideband64k {
		t = sideband.Sideband64k
	} else {
		t = sideband.Sideband
	}
	d := sideband.NewDemuxer(t, reader)
	d.Progress = progress
	return d
}

// --- helpers ---

func collectWants(desired map[plumbing.ReferenceName]DesiredRef) []plumbing.Hash {
	hashes := make([]plumbing.Hash, 0, len(desired))
	for _, ref := range desired {
		hashes = append(hashes, ref.SourceHash)
	}
	return SortedUniqueHashes(hashes)
}

func hasTag(desired map[plumbing.ReferenceName]DesiredRef) bool {
	for _, ref := range desired {
		if ref.IsTag {
			return true
		}
	}
	return false
}

func refValues(m map[plumbing.ReferenceName]plumbing.Hash) []plumbing.Hash {
	out := make([]plumbing.Hash, 0, len(m))
	for _, h := range m {
		if !h.IsZero() {
			out = append(out, h)
		}
	}
	return out
}

// SortedUniqueHashes deduplicates and sorts a hash slice.
func SortedUniqueHashes(input []plumbing.Hash) []plumbing.Hash {
	seen := make(map[plumbing.Hash]bool, len(input))
	out := make([]plumbing.Hash, 0, len(input))
	for _, h := range input {
		if seen[h] {
			continue
		}
		seen[h] = true
		out = append(out, h)
	}
	plumbing.HashesSort(out)
	return out
}

type wrappedRC struct {
	io.Reader
	io.Closer
}

type sessionRC struct {
	io.Reader
	closeFn func() error
}

func (r *sessionRC) Close() error {
	if r.closeFn == nil {
		return nil
	}
	return r.closeFn()
}
```

Ainternal/gitproto/fetch.go+427

package gitproto

import (
	"testing"

"github.com/go-git/go-git/v5/plumbing"
)

func TestCollectWants(t *testing.T) {
	hashA := plumbing.NewHash("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
	hashB := plumbing.NewHash("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")

tests := []struct {
		name    string
		desired map[plumbing.ReferenceName]DesiredRef
		want    []plumbing.Hash
	}{
		{
			name:    "empty map",
			desired: map[plumbing.ReferenceName]DesiredRef{},
			want:    []plumbing.Hash{},
		},
		{
			name: "single ref",
			desired: map[plumbing.ReferenceName]DesiredRef{
				"refs/heads/main": {SourceHash: hashA},
			},
			want: []plumbing.Hash{hashA},
		},
		{
			name: "deduplicated and sorted",
			desired: map[plumbing.ReferenceName]DesiredRef{
				"refs/heads/main": {SourceHash: hashB},
				"refs/heads/dev":  {SourceHash: hashA},
				"refs/heads/dup":  {SourceHash: hashB}, // duplicate of main
			},
			want: []plumbing.Hash{hashA, hashB}, // sorted: aa < bb
		},
	}

for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := collectWants(tt.desired)
			if len(got) != len(tt.want) {
				t.Fatalf("len = %d, want %d", len(got), len(tt.want))
			}
			for i := range got {
				if got[i] != tt.want[i] {
					t.Errorf("index %d: got %s, want %s", i, got[i], tt.want[i])
				}
			}
		})
	}
}

func TestHasTag(t *testing.T) {
	hashA := plumbing.NewHash("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")

tests := []struct {
		name    string
		desired map[plumbing.ReferenceName]DesiredRef
		want    bool
	}{
		{
			name:    "empty map",
			desired: map[plumbing.ReferenceName]DesiredRef{},
			want:    false,
		},
		{
			name: "no tags",
			desired: map[plumbing.ReferenceName]DesiredRef{
				"refs/heads/main": {SourceHash: hashA, IsTag: false},
			},
			want: false,
		},
		{
			name: "has tag",
			desired: map[plumbing.ReferenceName]DesiredRef{
				"refs/heads/main":  {SourceHash: hashA, IsTag: false},
				"refs/tags/v1.0.0": {SourceHash: hashA, IsTag: true},
			},
			want: true,
		},
		{
			name: "only tags",
			desired: map[plumbing.ReferenceName]DesiredRef{
				"refs/tags/v1.0.0": {SourceHash: hashA, IsTag: true},
			},
			want: true,
		},
	}

for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := hasTag(tt.desired)
			if got != tt.want {
				t.Errorf("hasTag() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestRefValues(t *testing.T) {
	hashA := plumbing.NewHash("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
	hashB := plumbing.NewHash("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")

tests := []struct {
		name string
		m    map[plumbing.ReferenceName]plumbing.Hash
		want int // expected count of non-zero hashes
	}{
		{
			name: "empty map",
			m:    map[plumbing.ReferenceName]plumbing.Hash{},
			want: 0,
		},
		{
			name: "all non-zero",
			m: map[plumbing.ReferenceName]plumbing.Hash{
				"refs/heads/main": hashA,
				"refs/heads/dev":  hashB,
			},
			want: 2,
		},
		{
			name: "some zero",
			m: map[plumbing.ReferenceName]plumbing.Hash{
				"refs/heads/main":    hashA,
				"refs/heads/new":     plumbing.ZeroHash,
				"refs/heads/another": hashB,
			},
			want: 2,
		},
		{
			name: "all zero",
			m: map[plumbing.ReferenceName]plumbing.Hash{
				"refs/heads/a": plumbing.ZeroHash,
				"refs/heads/b": plumbing.ZeroHash,
			},
			want: 0,
		},
		{
			name: "nil map",
			m:    nil,
			want: 0,
		},
	}

for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := refValues(tt.m)
			if len(got) != tt.want {
				t.Fatalf("refValues() returned %d values, want %d", len(got), tt.want)
			}
			// Verify none of the returned hashes are zero.
			for _, h := range got {
				if h.IsZero() {
					t.Errorf("refValues() returned zero hash, should be excluded")
				}
			}
		})
	}
}
```

Ainternal/gitproto/fetch\_helpers\_test.go+163

package gitproto

import (
	"bytes"
	"io"
	"testing"

"github.com/go-git/go-git/v5/plumbing/protocol/packp"
	"github.com/go-git/go-git/v5/plumbing/protocol/packp/capability"
	"github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband"
)

func TestCapabilities(t *testing.T) {
	// v2 protocol
	v2Caps := &V2Capabilities{
		Caps: map[string]string{
			"fetch":   "shallow",
			"ls-refs": "",
			"agent":   "git/test",
		},
	}
	rs := &RefService{Protocol: "v2", V2Caps: v2Caps}
	got := rs.Capabilities()
	if len(got) != 3 {
		t.Fatalf("v2 Capabilities() returned %d items, want 3", len(got))
	}
	// Should be sorted.
	if got[0] != "agent=git/test" {
		t.Errorf("v2 Capabilities()[0] = %q, want %q", got[0], "agent=git/test")
	}

// v1 protocol
	adv := packp.NewAdvRefs()
	_ = adv.Capabilities.Set(capability.OFSDelta)
	rs = &RefService{Protocol: "v1", V1Adv: adv}
	got = rs.Capabilities()
	if len(got) == 0 {
		t.Fatal("v1 Capabilities() returned empty list")
	}

// unknown protocol
	rs = &RefService{Protocol: "v99"}
	got = rs.Capabilities()
	if got != nil {
		t.Errorf("unknown protocol Capabilities() = %v, want nil", got)
	}
}

func TestBuildSidebandReader(t *testing.T) {
	data := "hello world"
	reader := bytes.NewBufferString(data)

// No sideband support -- should return the original reader.
	caps := capability.NewList()
	got := buildSidebandReader(caps, reader, nil)
	if got != reader {
		t.Error("expected original reader when no sideband capability")
	}

// With Sideband64k -- should return a demuxer (different reader).
	caps = capability.NewList()
	_ = caps.Set(capability.Sideband64k)
	got = buildSidebandReader(caps, reader, nil)
	if got == reader {
		t.Error("expected wrapped reader when Sideband64k is set")
	}

// With Sideband (not 64k) -- should return a demuxer.
	caps = capability.NewList()
	_ = caps.Set(capability.Sideband)
	got = buildSidebandReader(caps, reader, nil)
	if got == reader {
		t.Error("expected wrapped reader when Sideband is set")
	}
}

func TestBuildSidebandReaderWithProgress(t *testing.T) {
	reader := bytes.NewBufferString("test")
	caps := capability.NewList()
	_ = caps.Set(capability.Sideband64k)
	var progress sideband.Progress = io.Discard
	got := buildSidebandReader(caps, reader, progress)
	if got == reader {
		t.Error("expected wrapped reader when sideband capability is set")
	}
}

func TestProgressWriter(t *testing.T) {
	w := progressWriter(false)
	if w != nil {
		t.Error("progressWriter(false) should return nil")
	}
	w = progressWriter(true)
	if w == nil {
		t.Error("progressWriter(true) should return non-nil writer")
	}
}

func TestSessionRCClose(t *testing.T) {
	// With closeFn
	called := false
	rc := &sessionRC{
		Reader: bytes.NewBufferString("data"),
		closeFn: func() error {
			called = true
			return nil
		},
	}
	if err := rc.Close(); err != nil {
		t.Fatalf("Close() error: %v", err)
	}
	if !called {
		t.Error("closeFn was not called")
	}

// With nil closeFn
	rc = &sessionRC{
		Reader:  bytes.NewBufferString("data"),
		closeFn: nil,
	}
	if err := rc.Close(); err != nil {
		t.Fatalf("Close() with nil closeFn error: %v", err)
	}
}

func TestDecodeV2LSRefs(t *testing.T) {
	// Build a valid ls-refs response:
	// Each line: "<hash> <refname>\n"
	wire := "" +
		FormatPktLine("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa refs/heads/main\n") +
		FormatPktLine("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb refs/heads/dev\n") +
		"0000" // flush

refs, err := decodeV2LSRefs(bytes.NewReader([]byte(wire)))
	if err != nil {
		t.Fatalf("decodeV2LSRefs: %v", err)
	}
	if len(refs) != 2 {
		t.Fatalf("expected 2 refs, got %d", len(refs))
	}
	if refs[0].Name().String() != "refs/heads/main" {
		t.Errorf("refs[0].Name() = %q, want %q", refs[0].Name(), "refs/heads/main")
	}
	if refs[0].Hash().String() != "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" {
		t.Errorf("refs[0].Hash() = %q", refs[0].Hash())
	}
	if refs[1].Name().String() != "refs/heads/dev" {
		t.Errorf("refs[1].Name() = %q, want %q", refs[1].Name(), "refs/heads/dev")
	}
}

func TestDecodeV2LSRefsMalformed(t *testing.T) {
	// Line with only one field (no refname).
	wire := FormatPktLine("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n") + "0000"
	_, err := decodeV2LSRefs(bytes.NewReader([]byte(wire)))
	if err == nil {
		t.Fatal("expected error for malformed ls-refs line, got nil")
	}
}

func TestDecodeV2LSRefsEmpty(t *testing.T) {
	// Empty response (just flush).
	wire := "0000"
	refs, err := decodeV2LSRefs(bytes.NewReader([]byte(wire)))
	if err != nil {
		t.Fatalf("decodeV2LSRefs: %v", err)
	}
	if len(refs) != 0 {
		t.Fatalf("expected 0 refs, got %d", len(refs))
	}
}

func TestBufReader(t *testing.T) {
	input := bytes.NewBufferString("test data")
	pr := NewPacketReader(input)
	br := pr.BufReader()
	if br == nil {
		t.Fatal("BufReader() returned nil")
	}
}

func TestFetchToStoreUnsupportedProtocol(t *testing.T) {
	rs := &RefService{Protocol: "v99"}
	err := rs.FetchToStore(nil, nil, nil, nil, nil)
	if err == nil {
		t.Fatal("expected error for unsupported protocol")
	}
}

func TestFetchPackUnsupportedProtocol(t *testing.T) {
	rs := &RefService{Protocol: "v99"}
	_, err := rs.FetchPack(nil, nil, nil, nil)
	if err == nil {
		t.Fatal("expected error for unsupported protocol")
	}
}

func TestFetchCommitGraphRequiresV2(t *testing.T) {
	rs := &RefService{Protocol: "v1"}
	err := rs.FetchCommitGraph(nil, nil, nil, DesiredRef{})
	if err == nil {
		t.Fatal("expected error for non-v2 protocol")
	}
}

func TestFetchCommitGraphRequiresFilter(t *testing.T) {
	caps := &V2Capabilities{
		Caps: map[string]string{
			"fetch": "shallow",
		},
	}
	rs := &RefService{Protocol: "v2", V2Caps: caps}
	err := rs.FetchCommitGraph(nil, nil, nil, DesiredRef{})
	if err == nil {
		t.Fatal("expected error when filter not supported")
	}
}
```

Ainternal/gitproto/fetch\_test.go+217

package gitproto

import (
	"bufio"
	"bytes"
	"encoding/hex"
	"fmt"
	"io"

"github.com/go-git/go-git/v5/plumbing/format/pktline"
)

// PacketType represents the type of a pkt-line packet.
type PacketType int

const (
	PacketData        PacketType = iota
	PacketFlush                  // 0000
	PacketDelim                  // 0001
	PacketResponseEnd            // 0002
)

// PacketReader reads pkt-line formatted data. It reuses a fixed header buffer
// and a growable payload buffer to reduce allocations (issue #17).
type PacketReader struct {
	r      *bufio.Reader
	header [4]byte
	buf    []byte
}

func NewPacketReader(r io.Reader) *PacketReader {
	if br, ok := r.(*bufio.Reader); ok {
		return &PacketReader{r: br, buf: make([]byte, 0, 1024)}
	}
	return &PacketReader{r: bufio.NewReaderSize(r, 65536), buf: make([]byte, 0, 1024)}
}

// BufReader returns the underlying buffered reader for direct access
// (needed by sideband demuxer after switching to pack stream).
func (pr *PacketReader) BufReader() *bufio.Reader {
	return pr.r
}

// ReadPacket reads the next pkt-line packet. The returned payload slice is
// only valid until the next call to ReadPacket.
func (pr *PacketReader) ReadPacket() (PacketType, []byte, error) {
	if _, err := io.ReadFull(pr.r, pr.header[:]); err != nil {
		return PacketData, nil, err
	}

switch string(pr.header[:]) {
	case "0000":
		return PacketFlush, nil, nil
	case "0001":
		return PacketDelim, nil, nil
	case "0002":
		return PacketResponseEnd, nil, nil
	}

n, err := parseHexLength(pr.header)
	if err != nil {
		return PacketData, nil, err
	}
	if n <= 4 {
		return PacketData, nil, pktline.ErrInvalidPktLen
	}

payloadLen := n - 4
	if payloadLen > cap(pr.buf) {
		pr.buf = make([]byte, payloadLen)
	} else {
		pr.buf = pr.buf[:payloadLen]
	}
	if _, err := io.ReadFull(pr.r, pr.buf); err != nil {
		return PacketData, nil, err
	}
	return PacketData, pr.buf, nil
}

func parseHexLength(header [4]byte) (int, error) {
	var n int
	for _, b := range header {
		v, ok := hexVal(b)
		if !ok {
			return 0, pktline.ErrInvalidPktLen
		}
		n = 16*n + int(v)
	}
	return n, nil
}

func hexVal(b byte) (byte, bool) {
	switch {
	case b >= '0' && b <= '9':
		return b - '0', true
	case b >= 'a' && b <= 'f':
		return b - 'a' + 10, true
	case b >= 'A' && b <= 'F':
		return b - 'A' + 10, true
	default:
		return 0, false
	}
}

// EncodeCommand builds a pkt-line encoded v2 command request.
func EncodeCommand(command string, capArgs, cmdArgs []string) ([]byte, error) {
	var buf bytes.Buffer
	enc := pktline.NewEncoder(&buf)
	if err := enc.EncodeString("command=" + command + "\n"); err != nil {
		return nil, err
	}
	for _, arg := range capArgs {
		if err := enc.EncodeString(arg + "\n"); err != nil {
			return nil, err
		}
	}
	if len(cmdArgs) > 0 {
		if _, err := buf.WriteString("0001"); err != nil {
			return nil, err
		}
		for _, arg := range cmdArgs {
			if err := enc.EncodeString(arg + "\n"); err != nil {
				return nil, err
			}
		}
	}
	if err := enc.Flush(); err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}

// SkipSection reads and discards packets until a delimiter or flush is reached.
func SkipSection(pr *PacketReader) error {
	for {
		kind, _, err := pr.ReadPacket()
		if err != nil {
			return err
		}
		if kind == PacketDelim || kind == PacketFlush {
			return nil
		}
	}
}

// HashHex is a helper to encode a 20-byte hash as lowercase hex.
func HashHex(h [20]byte) string {
	return hex.EncodeToString(h[:])
}

// FormatPktLine encodes a single pkt-line from a string payload.
func FormatPktLine(s string) string {
	n := len(s) + 4
	return fmt.Sprintf("%04x%s", n, s)
}
```

Ainternal/gitproto/pktline.go+155

package gitproto

import (
	"bufio"
	"bytes"
	"io"
	"testing"
)

func TestPacketReaderHandlesSpecialPackets(t *testing.T) {
	reader := NewPacketReader(bytes.NewBufferString("0000000100020006a\n"))

kind, payload, err := reader.ReadPacket()
	if err != nil {
		t.Fatalf("read flush: %v", err)
	}
	if kind != PacketFlush || payload != nil {
		t.Fatalf("unexpected flush: kind=%v payload=%q", kind, payload)
	}

kind, payload, err = reader.ReadPacket()
	if err != nil {
		t.Fatalf("read delim: %v", err)
	}
	if kind != PacketDelim {
		t.Fatalf("unexpected delim kind: %v", kind)
	}

kind, payload, err = reader.ReadPacket()
	if err != nil {
		t.Fatalf("read response-end: %v", err)
	}
	if kind != PacketResponseEnd {
		t.Fatalf("unexpected response-end kind: %v", kind)
	}

kind, payload, err = reader.ReadPacket()
	if err != nil {
		t.Fatalf("read data: %v", err)
	}
	if kind != PacketData || string(payload) != "a\n" {
		t.Fatalf("unexpected data: kind=%v payload=%q", kind, payload)
	}
}

func TestDecodeV2Capabilities(t *testing.T) {
	wire := "" +
		"000eversion 2\n" +
		"0013ls-refs=unborn\n" +
		"0012fetch=shallow\n" +
		"0013agent=git/test\n" +
		"0000"
	caps, err := DecodeV2Capabilities(bytes.NewBufferString(wire))
	if err != nil {
		t.Fatalf("decode: %v", err)
	}
	if !caps.Supports("ls-refs") {
		t.Fatalf("expected ls-refs capability")
	}
	if got := caps.Value("fetch"); got != "shallow" {
		t.Fatalf("unexpected fetch value %q", got)
	}
	if got := caps.Value("agent"); got != "git/test" {
		t.Fatalf("unexpected agent value %q", got)
	}
}

func TestPacketReaderMalformedLength(t *testing.T) {
	tests := []struct {
		name  string
		input string
	}{
		{
			name:  "non-hex characters",
			input: "xxxx",
		},
		{
			name:  "partial hex with invalid char",
			input: "00gz",
		},
		{
			name:  "uppercase non-hex",
			input: "ZZZZ",
		},
	}

for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			reader := NewPacketReader(bytes.NewBufferString(tt.input))
			_, _, err := reader.ReadPacket()
			if err == nil {
				t.Fatal("expected error for malformed hex length, got nil")
			}
		})
	}
}

func TestPacketReaderTruncatedPayload(t *testing.T) {
	tests := []struct {
		name  string
		input string
	}{
		{
			name:  "header claims 10 bytes total but payload is short",
			input: "000aab",
		},
		{
			name:  "header claims 8 bytes total but only 1 byte of payload",
			input: "0008x",
		},
	}

for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			reader := NewPacketReader(bytes.NewBufferString(tt.input))
			_, _, err := reader.ReadPacket()
			if err == nil {
				t.Fatal("expected error for truncated payload, got nil")
			}
		})
	}
}

func TestDecodeV2CapabilitiesMissingVersion(t *testing.T) {
	tests := []struct {
		name  string
		input string
	}{
		{
			name:  "wrong version string",
			input: "000eversion 1\n" + "0000",
		},
		{
			name:  "no version line at all, just capabilities",
			input: "0013ls-refs=unborn\n" + "0000",
		},
	}

for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			_, err := DecodeV2Capabilities(bytes.NewBufferString(tt.input))
			if err == nil {
				t.Fatal("expected error for missing version 2 line, got nil")
			}
		})
	}
}

func TestDecodeV2CapabilitiesEmptyFlush(t *testing.T) {
	// Flush packet (0000) before the version line should be skipped,
	// but if the stream is only flushes with no version line, it should error.
	tests := []struct {
		name    string
		input   string
		wantErr bool
	}{
		{
			name:    "flush before version line is skipped",
			input:   "0000" + "000eversion 2\n" + "0013ls-refs=unborn\n" + "0000",
			wantErr: false,
		},
		{
			name:    "only flush packets with no data causes EOF",
			input:   "0000",
			wantErr: true,
		},
	}

for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			caps, err := DecodeV2Capabilities(bytes.NewBufferString(tt.input))
			if tt.wantErr {
				if err == nil {
					t.Fatal("expected error, got nil")
				}
				return
			}
			if err != nil {
				t.Fatalf("unexpected error: %v", err)
			}
			if !caps.Supports("ls-refs") {
				t.Fatal("expected ls-refs capability after flush-then-version")
			}
		})
	}
}

func TestEncodeCommand(t *testing.T) {
	req, err := EncodeCommand(
		"ls-refs",
		[]string{"agent=git-sync/test"},
		[]string{"peel", "ref-prefix refs/heads/"},
	)
	if err != nil {
		t.Fatalf("encode: %v", err)
	}
	want := "" +
		"0014command=ls-refs\n" +
		"0018agent=git-sync/test\n" +
		"0001" +
		"0009peel\n" +
		"001bref-prefix refs/heads/\n" +
		"0000"
	if string(req) != want {
		t.Fatalf("unexpected request:\n%s\nwant:\n%s", req, want)
	}
}

func TestEncodeCommandNoArgs(t *testing.T) {
	// EncodeCommand with no command args should emit command + cap args +
	// flush, with no delimiter section.
	req, err := EncodeCommand(
		"ls-refs",
		[]string{"agent=git-sync/test"},
		nil,
	)
	if err != nil {
		t.Fatalf("encode: %v", err)
	}
	want := "" +
		"0014command=ls-refs\n" +
		"0018agent=git-sync/test\n" +
		"0000"
	if string(req) != want {
		t.Fatalf("unexpected request:\ngot:  %q\nwant: %q", string(req), want)
	}
	// Verify no delimiter is present in the output.
	if bytes.Contains(req, []byte("0001")) {
		t.Fatalf("expected no delimiter section when cmdArgs is nil, but found 0001")
	}
}

func TestPacketReaderEOF(t *testing.T) {
	// Reading from an empty reader should return io.EOF.
	reader := NewPacketReader(bytes.NewReader(nil))
	_, _, err := reader.ReadPacket()
	if err == nil {
		t.Fatal("expected error from empty reader, got nil")
	}
	if err != io.EOF && err != io.ErrUnexpectedEOF {
		t.Fatalf("expected io.EOF or io.ErrUnexpectedEOF, got %v", err)
	}
}

func TestSkipSection(t *testing.T) {
	tests := []struct {
		name      string
		input     string
		wantErr   bool
		remainder string
	}{
		{
			name: "data packets followed by delimiter",
			// Two data packets then a delimiter (0001), then a trailing data packet.
			input:     "0009hello" + "0009world" + "0001" + "0008end!",
			remainder: "0008end!",
		},
		{
			name: "data packets followed by flush",
			// Two data packets then a flush (0000).
			input: "0009hello" + "0009world" + "0000",
		},
		{
			name:    "EOF before delimiter or flush",
			input:   "0009hello",
			wantErr: true,
		},
	}

for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			buf := bytes.NewBufferString(tt.input)
			pr := NewPacketReader(buf)
			err := SkipSection(pr)
			if tt.wantErr {
				if err == nil {
					t.Fatal("expected error, got nil")
				}
				return
			}
			if err != nil {
				t.Fatalf("unexpected error: %v", err)
			}
			// Verify that the remainder after the section is intact.
			if tt.remainder != "" {
				kind, payload, err := pr.ReadPacket()
				if err != nil {
					t.Fatalf("reading remainder: %v", err)
				}
				if kind != PacketData {
					t.Fatalf("expected data packet after skip, got kind=%v", kind)
				}
				if string(payload) != "end!" {
					t.Fatalf("remainder payload = %q, want %q", payload, "end!")
				}
			}
		})
	}
}

func TestFormatPktLine(t *testing.T) {
	tests := []struct {
		input string
		want  string
	}{
		{input: "a\n", want: "0006a\n"},
		{input: "hello\n", want: "000ahello\n"},
		{input: "", want: "0004"},
		{input: "version 2\n", want: "000eversion 2\n"},
	}
	for _, tt := range tests {
		got := FormatPktLine(tt.input)
		if got != tt.want {
			t.Errorf("FormatPktLine(%q) = %q, want %q", tt.input, got, tt.want)
		}
	}
}

func TestNewPacketReaderWithBufioReader(t *testing.T) {
	// When passed a *bufio.Reader, NewPacketReader should reuse it instead
	// of wrapping it again.
	input := bytes.NewBufferString("0000")
	br := bufio.NewReader(input)
	pr := NewPacketReader(br)
	if pr.BufReader() != br {
		t.Error("expected NewPacketReader to reuse the provided *bufio.Reader")
	}
	kind, _, err := pr.ReadPacket()
	if err != nil {
		t.Fatalf("ReadPacket error: %v", err)
	}
	if kind != PacketFlush {
		t.Errorf("expected PacketFlush, got %v", kind)
	}
}

func TestParseHexLengthUppercase(t *testing.T) {
	// Uppercase hex should also parse correctly (hexVal covers A-F).
	// 0x000A = 10 total, payload = 10 - 4 = 6 bytes.
	wire := "000AABCDEF"
	pr := NewPacketReader(bytes.NewBufferString(wire))
	kind, payload, err := pr.ReadPacket()
	if err != nil {
		t.Fatalf("ReadPacket error: %v", err)
	}
	if kind != PacketData {
		t.Fatalf("expected PacketData, got %v", kind)
	}
	if string(payload) != "ABCDEF" {
		t.Errorf("payload = %q, want %q", payload, "ABCDEF")
	}
}

func TestHashHex(t *testing.T) {
	tests := []struct {
		name string
		hash [20]byte
		want string
	}{
		{
			name: "zero hash",
			hash: [20]byte{},
			want: "0000000000000000000000000000000000000000",
		},
		{
			name: "known hash",
			hash: [20]byte{0xde, 0xad, 0xbe, 0xef, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10},
			want: "deadbeef0102030405060708090a0b0c0d0e0f10",
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := HashHex(tt.hash)
			if got != tt.want {
				t.Errorf("HashHex() = %q, want %q", got, tt.want)
			}
		})
	}
}
```

Ainternal/gitproto/pktline\_test.go+379

package gitproto

import (
	"context"
	"fmt"
	"io"
	"os"

"github.com/go-git/go-git/v5/plumbing"
	"github.com/go-git/go-git/v5/plumbing/format/packfile"
	"github.com/go-git/go-git/v5/plumbing/protocol/packp"
	"github.com/go-git/go-git/v5/plumbing/protocol/packp/capability"
	"github.com/go-git/go-git/v5/plumbing/storer"
	"github.com/go-git/go-git/v5/plumbing/transport"
)

// PushCommand represents a single ref update command.
type PushCommand struct {
	Name   plumbing.ReferenceName
	Old    plumbing.Hash
	New    plumbing.Hash
	Delete bool
}

// preparePush opens a receive-pack session and builds the base request with
// sideband negotiation. Shared by PushObjects, PushPack, and PushCommands.
func preparePush(
	conn *Conn,
	adv *packp.AdvRefs,
	commands []PushCommand,
	verbose bool,
) (transport.ReceivePackSession, *packp.ReferenceUpdateRequest, bool, bool, error) {
	session, err := conn.Transport.NewReceivePackSession(conn.Endpoint, conn.Auth)
	if err != nil {
		return nil, nil, false, false, fmt.Errorf("open target receive-pack session: %w", err)
	}

req := packp.NewReferenceUpdateRequestFromCapabilities(adv.Capabilities)
	req.Progress = progressWriter(verbose)
	if sb := PreferredSideband(adv.Capabilities); sb != "" {
		_ = req.Capabilities.Set(sb)
	}

hasDelete := false
	hasUpdates := false
	for _, cmd := range commands {
		c := &packp.Command{Name: cmd.Name, Old: cmd.Old}
		if cmd.Delete {
			c.New = plumbing.ZeroHash
			hasDelete = true
		} else {
			c.New = cmd.New
			hasUpdates = true
		}
		req.Commands = append(req.Commands, c)
	}

if hasDelete {
		if !adv.Capabilities.Supports(capability.DeleteRefs) {
			_ = session.Close()
			return nil, nil, false, false, fmt.Errorf("target does not support delete-refs")
		}
		_ = req.Capabilities.Set(capability.DeleteRefs)
	}

return session, req, hasDelete, hasUpdates, nil
}

// PushObjects pushes locally-materialized objects to the target.
func PushObjects(
	ctx context.Context,
	conn *Conn,
	adv *packp.AdvRefs,
	commands []PushCommand,
	store storer.Storer,
	hashes []plumbing.Hash,
	verbose bool,
) error {
	session, req, _, hasUpdates, err := preparePush(conn, adv, commands, verbose)
	if err != nil {
		return err
	}
	defer session.Close()
	return executePush(ctx, session, store, req, hashes, hasUpdates, !adv.Capabilities.Supports(capability.OFSDelta))
}

// PushPack pushes a pack stream (relay) to the target.
func PushPack(
	ctx context.Context,
	conn *Conn,
	adv *packp.AdvRefs,
	commands []PushCommand,
	pack io.ReadCloser,
	verbose bool,
) error {
	// Validate no deletes in pack push before opening session.
	for _, cmd := range commands {
		if cmd.Delete {
			return fmt.Errorf("pack push only supports create and update actions")
		}
	}

session, req, _, _, err := preparePush(conn, adv, commands, verbose)
	if err != nil {
		return err
	}
	defer session.Close()

req.Packfile = pack
	report, err := session.ReceivePack(ctx, req)
	if err != nil {
		_ = pack.Close()
		return err
	}
	if closeErr := pack.Close(); closeErr != nil {
		return closeErr
	}
	if report != nil {
		return report.Error()
	}
	return nil
}

// PushCommands sends ref update commands without a pack (for ref-only changes).
func PushCommands(
	ctx context.Context,
	conn *Conn,
	adv *packp.AdvRefs,
	commands []PushCommand,
	verbose bool,
) error {
	session, req, _, _, err := preparePush(conn, adv, commands, verbose)
	if err != nil {
		return err
	}
	defer session.Close()
	return executePush(ctx, session, nil, req, nil, false, false)
}

func executePush(
	ctx context.Context,
	session transport.ReceivePackSession,
	store storer.Storer,
	req *packp.ReferenceUpdateRequest,
	hashes []plumbing.Hash,
	sendPack bool,
	useRefDeltas bool,
) error {
	if !sendPack {
		report, err := session.ReceivePack(ctx, req)
		if err != nil {
			return err
		}
		if report != nil {
			return report.Error()
		}
		return nil
	}

rd, wr := io.Pipe()
	req.Packfile = rd
	done := make(chan error, 1)

go func() {
		enc := packfile.NewEncoder(wr, store, useRefDeltas)
		if _, err := enc.Encode(hashes, 10); err != nil {
			done <- wr.CloseWithError(err)
			return
		}
		done <- wr.Close()
	}()

report, err := session.ReceivePack(ctx, req)
	if err != nil {
		_ = rd.Close()
		return err
	}
	if err := <-done; err != nil {
		return err
	}
	if report != nil {
		return report.Error()
	}
	return nil
}

func progressWriter(verbose bool) io.Writer {
	if !verbose {
		return nil
	}
	return os.Stderr
}
```

Ainternal/gitproto/push.go+192

package gitproto

import (
	"bytes"
	"context"
	"fmt"
	"strings"

"github.com/go-git/go-git/v5/plumbing"
	"github.com/go-git/go-git/v5/plumbing/protocol/packp"
	"github.com/go-git/go-git/v5/plumbing/transport"
)

// RefService encapsulates the result of source ref discovery and the negotiated
// protocol, providing methods for subsequent fetch and pack operations.
type RefService struct {
	Protocol string // "v1" or "v2"
	V1Adv    *packp.AdvRefs
	V2Caps   *V2Capabilities
}

// ListSourceRefs discovers refs from the source using the configured protocol mode.
// Returns the list of refs and a RefService for subsequent operations.
func ListSourceRefs(ctx context.Context, conn *Conn, protocolMode string, refPrefixes []string) ([]*plumbing.Reference, *RefService, error) {
	switch protocolMode {
	case "v1":
		adv, refs, err := listSourceRefsV1(ctx, conn)
		if err != nil {
			return nil, nil, err
		}
		return refs, &RefService{Protocol: "v1", V1Adv: adv}, nil

case "auto", "v2":
		data, err := RequestInfoRefs(ctx, conn, transport.UploadPackServiceName, "version=2")
		if err != nil {
			return nil, nil, err
		}
		if caps, err := DecodeV2Capabilities(bytes.NewReader(data)); err == nil {
			if !caps.Supports("ls-refs") || !caps.Supports("fetch") {
				return nil, nil, fmt.Errorf("source does not advertise required protocol v2 commands")
			}
			refs, err := listSourceRefsV2(ctx, conn, caps, refPrefixes)
			if err != nil {
				return nil, nil, err
			}
			return refs, &RefService{Protocol: "v2", V2Caps: caps}, nil
		}
		if protocolMode == "v2" {
			return nil, nil, fmt.Errorf("source did not negotiate protocol v2")
		}
		// Fall back to v1
		adv, err := decodeV1AdvRefs(data)
		if err != nil {
			return nil, nil, err
		}
		refs, err := AdvRefsToSlice(adv)
		if err != nil {
			return nil, nil, err
		}
		return refs, &RefService{Protocol: "v1", V1Adv: adv}, nil

default:
		return nil, nil, fmt.Errorf("unsupported protocol mode %q", protocolMode)
	}
}

// AdvertisedRefsV1 fetches and decodes v1 advertised refs for the given service.
func AdvertisedRefsV1(ctx context.Context, conn *Conn, service string) (*packp.AdvRefs, error) {
	data, err := RequestInfoRefs(ctx, conn, service, "")
	if err != nil {
		return nil, err
	}
	return decodeV1AdvRefs(data)
}

// AdvRefsToSlice converts an AdvRefs to a slice of references.
func AdvRefsToSlice(ar *packp.AdvRefs) ([]*plumbing.Reference, error) {
	refs, err := ar.AllReferences()
	if err != nil {
		return nil, err
	}
	iter, err := refs.IterReferences()
	if err != nil {
		return nil, err
	}
	defer iter.Close()

var out []*plumbing.Reference
	err = iter.ForEach(func(ref *plumbing.Reference) error {
		out = append(out, ref)
		return nil
	})
	return out, err
}

// AdvRefsCaps returns the sorted capability list from an AdvRefs.
func AdvRefsCaps(adv *packp.AdvRefs) []string {
	if adv == nil || adv.Capabilities == nil {
		return nil
	}
	all := adv.Capabilities.All()
	items := make([]string, 0, len(all))
	for _, cap := range all {
		values := adv.Capabilities.Get(cap)
		if len(values) == 0 {
			items = append(items, string(cap))
			continue
		}
		for _, value := range values {
			items = append(items, string(cap)+"="+value)
		}
	}
	return items
}

func listSourceRefsV1(ctx context.Context, conn *Conn) (*packp.AdvRefs, []*plumbing.Reference, error) {
	adv, err := AdvertisedRefsV1(ctx, conn, transport.UploadPackServiceName)
	if err != nil {
		return nil, nil, err
	}
	refs, err := AdvRefsToSlice(adv)
	if err != nil {
		return nil, nil, err
	}
	return adv, refs, nil
}

func listSourceRefsV2(ctx context.Context, conn *Conn, caps *V2Capabilities, prefixes []string) ([]*plumbing.Reference, error) {
	args := []string{"peel"}
	for _, prefix := range prefixes {
		args = append(args, "ref-prefix "+prefix)
	}
	body, err := EncodeCommand("ls-refs", caps.RequestCapabilities(), args)
	if err != nil {
		return nil, err
	}
	data, err := PostRPC(ctx, conn, transport.UploadPackServiceName, body, true, "upload-pack ls-refs")
	if err != nil {
		return nil, err
	}
	return decodeV2LSRefs(bytes.NewReader(data))
}

func decodeV2LSRefs(r *bytes.Reader) ([]*plumbing.Reference, error) {
	reader := NewPacketReader(r)
	var refs []*plumbing.Reference
	for {
		kind, payload, err := reader.ReadPacket()
		if err != nil {
			return nil, err
		}
		if kind == PacketFlush {
			return refs, nil
		}
		if kind != PacketData {
			return nil, fmt.Errorf("unexpected packet type %v in ls-refs response", kind)
		}
		fields := strings.Fields(strings.TrimSpace(string(payload)))
		if len(fields) < 2 {
			return nil, fmt.Errorf("malformed ls-refs response line %q", payload)
		}
		hash := plumbing.NewHash(fields[0])
		name := plumbing.ReferenceName(fields[1])
		refs = append(refs, plumbing.NewHashReference(name, hash))
	}
}

func decodeV1AdvRefs(data []byte) (*packp.AdvRefs, error) {
	ar := packp.NewAdvRefs()
	if err := ar.Decode(bytes.NewReader(data)); err != nil {
		if err == packp.ErrEmptyAdvRefs {
			return nil, transport.ErrEmptyRemoteRepository
		}
		return nil, err
	}
	return ar, nil
}

// RefHashMap converts a reference slice to a map of name→hash.
func RefHashMap(refs []*plumbing.Reference) map[plumbing.ReferenceName]plumbing.Hash {
	out := make(map[plumbing.ReferenceName]plumbing.Hash, len(refs))
	for _, ref := range refs {
		if ref.Type() == plumbing.HashReference {
			out[ref.Name()] = ref.Hash()
		}
	}
	return out
}
```

Ainternal/gitproto/refs.go+188

```
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

package gitproto

import (
	"context"
	"testing"

"github.com/go-git/go-git/v5/plumbing"
	"github.com/go-git/go-git/v5/plumbing/protocol/packp"
	"github.com/go-git/go-git/v5/plumbing/protocol/packp/capability"
)

func TestRefHashMap(t *testing.T) {
	hashA := plumbing.NewHash("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
	hashB := plumbing.NewHash("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")

refs := []*plumbing.Reference{
		plumbing.NewHashReference("refs/heads/main", hashA),
		plumbing.NewHashReference("refs/heads/dev", hashB),
		plumbing.NewSymbolicReference("HEAD", "refs/heads/main"), // symbolic, should be skipped
	}

m := RefHashMap(refs)

if len(m) != 2 {
		t.Fatalf("expected 2 entries, got %d", len(m))
	}
	if got := m["refs/heads/main"]; got != hashA {
		t.Errorf("refs/heads/main = %s, want %s", got, hashA)
	}
	if got := m["refs/heads/dev"]; got != hashB {
		t.Errorf("refs/heads/dev = %s, want %s", got, hashB)
	}

// Empty input.
	m = RefHashMap(nil)
	if len(m) != 0 {
		t.Errorf("RefHashMap(nil) returned %d entries, want 0", len(m))
	}
}

func TestAdvRefsCaps(t *testing.T) {
	// nil AdvRefs should return nil.
	if got := AdvRefsCaps(nil); got != nil {
		t.Errorf("AdvRefsCaps(nil) = %v, want nil", got)
	}

// AdvRefs with nil Capabilities should return nil.
	adv := &packp.AdvRefs{}
	adv.Capabilities = nil
	if got := AdvRefsCaps(adv); got != nil {
		t.Errorf("AdvRefsCaps(nil caps) = %v, want nil", got)
	}

// AdvRefs with populated capabilities.
	adv = packp.NewAdvRefs()
	_ = adv.Capabilities.Set(capability.OFSDelta)
	_ = adv.Capabilities.Add(capability.Agent, "git/test-agent")
	_ = adv.Capabilities.Set(capability.NoProgress)

items := AdvRefsCaps(adv)
	if len(items) == 0 {
		t.Fatal("expected non-empty capability list")
	}

// Verify that known capabilities appear in the output.
	found := make(map[string]bool)
	for _, item := range items {
		found[item] = true
	}
	if !found["ofs-delta"] {
		t.Error("expected ofs-delta in capability list")
	}
	if !found["agent=git/test-agent"] {
		t.Errorf("expected agent=git/test-agent in capability list, got items: %v", items)
	}
	if !found["no-progress"] {
		t.Error("expected no-progress in capability list")
	}
}

func TestAdvRefsToSlice(t *testing.T) {
	adv := packp.NewAdvRefs()
	hashA := plumbing.NewHash("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
	hashB := plumbing.NewHash("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")
	adv.References = map[string]plumbing.Hash{
		"refs/heads/main": hashA,
		"refs/heads/dev":  hashB,
	}

refs, err := AdvRefsToSlice(adv)
	if err != nil {
		t.Fatalf("AdvRefsToSlice: %v", err)
	}
	if len(refs) != 2 {
		t.Fatalf("expected 2 refs, got %d", len(refs))
	}

found := make(map[plumbing.ReferenceName]plumbing.Hash)
	for _, ref := range refs {
		found[ref.Name()] = ref.Hash()
	}
	if found["refs/heads/main"] != hashA {
		t.Errorf("refs/heads/main = %s, want %s", found["refs/heads/main"], hashA)
	}
	if found["refs/heads/dev"] != hashB {
		t.Errorf("refs/heads/dev = %s, want %s", found["refs/heads/dev"], hashB)
	}
}

func TestDecodeV1AdvRefs(t *testing.T) {
	// Empty data should return ErrEmptyRemoteRepository.
	_, err := decodeV1AdvRefs(nil)
	if err == nil {
		t.Fatal("expected error for nil data, got nil")
	}

// Empty bytes should also error.
	_, err = decodeV1AdvRefs([]byte{})
	if err == nil {
		t.Fatal("expected error for empty data, got nil")
	}
}

func TestListSourceRefsUnsupportedProtocol(t *testing.T) {
	_, _, err := ListSourceRefs(context.Background(), nil, "v99", nil)
	if err == nil {
		t.Fatal("expected error for unsupported protocol mode")
	}
}
```

Ainternal/gitproto/refs\_test.go+130

```
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

package gitproto

import (
	"bytes"
	"context"
	"crypto/tls"
	"fmt"
	"io"
	"net/http"

"github.com/go-git/go-git/v5/plumbing/protocol/packp/capability"
	"github.com/go-git/go-git/v5/plumbing/transport"
	transporthttp "github.com/go-git/go-git/v5/plumbing/transport/http"
)

// StatsPhaseHeader is the HTTP header used to annotate requests with the
// current git-sync stats phase for round-trip tracking.
const StatsPhaseHeader = "X-Git-Sync-Stats-Phase"

// Conn represents a connection to a remote Git HTTP endpoint.
type Conn struct {
	Label     string
	Endpoint  *transport.Endpoint
	Transport transport.Transport
	HTTP      *http.Client
	Auth      transport.AuthMethod
}

// NewConn creates a new connection to the given endpoint.
func NewConn(ep *transport.Endpoint, label string, auth transport.AuthMethod, rt http.RoundTripper) *Conn {
	httpClient := &http.Client{Transport: rt}
	return &Conn{
		Label:     label,
		Endpoint:  ep,
		Transport: transporthttp.NewClient(httpClient),
		HTTP:      httpClient,
		Auth:      auth,
	}
}

// NewHTTPTransport creates an http.Transport with optional TLS skip.
func NewHTTPTransport(skipTLS bool) http.RoundTripper {
	if !skipTLS {
		return http.DefaultTransport
	}
	if cloned, ok := http.DefaultTransport.(*http.Transport); ok {
		tc := cloned.Clone()
		if tc.TLSClientConfig == nil {
			tc.TLSClientConfig = &tls.Config{MinVersion: tls.VersionTLS12}
		}
		tc.TLSClientConfig.InsecureSkipVerify = true
		return tc
	}
	return http.DefaultTransport
}

// RequestInfoRefs fetches /info/refs for the given service.
func RequestInfoRefs(ctx context.Context, conn *Conn, service, gitProtocol string) ([]byte, error) {
	url := fmt.Sprintf("%s/info/refs?service=%s", conn.Endpoint.String(), service)
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Accept", "*/*")
	req.Header.Set("User-Agent", capability.DefaultAgent())
	req.Header.Set(StatsPhaseHeader, service+" info-refs")
	if gitProtocol != "" {
		req.Header.Set("Git-Protocol", gitProtocol)
	}
	ApplyAuth(req, conn.Auth)

res, err := conn.HTTP.Do(req)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()
	if err := transporthttp.NewErr(res); err != nil {
		return nil, err
	}
	// Bound the read to prevent unbounded memory allocation (issue #9).
	const maxInfoRefsSize = 64 * 1024 * 1024 // 64 MiB
	lr := io.LimitReader(res.Body, maxInfoRefsSize+1)
	data, err := io.ReadAll(lr)
	if err != nil {
		return nil, err
	}
	if int64(len(data)) > maxInfoRefsSize {
		return nil, fmt.Errorf("info/refs response exceeds %d byte limit", maxInfoRefsSize)
	}
	return data, nil
}

// PostRPC sends a buffered POST to the given service and returns the full response body.
// Responses are bounded to prevent unbounded memory allocation (issue #9).
func PostRPC(ctx context.Context, conn *Conn, service string, body []byte, v2 bool, phase string) ([]byte, error) {
	reader, err := PostRPCStream(ctx, conn, service, body, v2, phase)
	if err != nil {
		return nil, err
	}
	defer reader.Close()
	const maxRPCResponse = 128 * 1024 * 1024 // 128 MiB
	lr := io.LimitReader(reader, maxRPCResponse+1)
	data, err := io.ReadAll(lr)
	if err != nil {
		return nil, err
	}
	if int64(len(data)) > maxRPCResponse {
		return nil, fmt.Errorf("RPC response for %s exceeds %d byte limit", service, maxRPCResponse)
	}
	return data, nil
}

// PostRPCStream sends a POST to the given service and returns the response body
// as a streaming reader. Caller must close the returned ReadCloser.
func PostRPCStream(ctx context.Context, conn *Conn, service string, body []byte, v2 bool, phase string) (io.ReadCloser, error) {
	url := fmt.Sprintf("%s/%s", conn.Endpoint.String(), service)
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", fmt.Sprintf("application/x-%s-request", service))
	req.Header.Set("Accept", fmt.Sprintf("application/x-%s-result", service))
	req.Header.Set("User-Agent", capability.DefaultAgent())
	req.Header.Set(StatsPhaseHeader, phase)
	if v2 {
		req.Header.Set("Git-Protocol", "version=2")
	}
	ApplyAuth(req, conn.Auth)

res, err := conn.HTTP.Do(req)
	if err != nil {
		return nil, err
	}
	if err := transporthttp.NewErr(res); err != nil {
		_ = res.Body.Close()
		return nil, err
	}
	return res.Body, nil
}

// ApplyAuth applies the given auth method to an HTTP request.
func ApplyAuth(req *http.Request, auth transport.AuthMethod) {
	switch a := auth.(type) {
	case *transporthttp.BasicAuth:
		a.SetAuth(req)
	case *transporthttp.TokenAuth:
		a.SetAuth(req)
	}
}
```

Ainternal/gitproto/smarthttp.go+149

```
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

package gitproto

import (
	"net/http"
	"testing"

"github.com/go-git/go-git/v5/plumbing/transport"
	transporthttp "github.com/go-git/go-git/v5/plumbing/transport/http"
)

func TestNewConn(t *testing.T) {
	ep, err := transport.NewEndpoint("https://github.com/user/repo.git")
	if err != nil {
		t.Fatalf("parse endpoint: %v", err)
	}
	auth := &transporthttp.BasicAuth{Username: "user", Password: "pass"}
	conn := NewConn(ep, "test-label", auth, http.DefaultTransport)

if conn.Label != "test-label" {
		t.Errorf("Label = %q, want %q", conn.Label, "test-label")
	}
	if conn.Endpoint != ep {
		t.Error("Endpoint mismatch")
	}
	if conn.Auth != auth {
		t.Error("Auth mismatch")
	}
	if conn.HTTP == nil {
		t.Error("HTTP client should not be nil")
	}
	if conn.Transport == nil {
		t.Error("Transport should not be nil")
	}
}

func TestNewHTTPTransport(t *testing.T) {
	// Without TLS skip should return default transport.
	rt := NewHTTPTransport(false)
	if rt != http.DefaultTransport {
		t.Error("expected http.DefaultTransport when skipTLS is false")
	}

// With TLS skip should return a transport with InsecureSkipVerify.
	rt = NewHTTPTransport(true)
	if rt == http.DefaultTransport {
		t.Error("expected a different transport when skipTLS is true")
	}
	// Verify the returned transport is an *http.Transport with skip verify.
	if ht, ok := rt.(*http.Transport); ok {
		if ht.TLSClientConfig == nil || !ht.TLSClientConfig.InsecureSkipVerify {
			t.Error("expected InsecureSkipVerify = true")
		}
	}
}

func TestApplyAuth(t *testing.T) {
	// BasicAuth
	req, _ := http.NewRequest("GET", "https://example.com", nil)
	auth := &transporthttp.BasicAuth{Username: "user", Password: "pass"}
	ApplyAuth(req, auth)
	user, pass, ok := req.BasicAuth()
	if !ok || user != "user" || pass != "pass" {
		t.Errorf("BasicAuth not applied: ok=%v user=%q pass=%q", ok, user, pass)
	}

// TokenAuth
	req, _ = http.NewRequest("GET", "https://example.com", nil)
	tokenAuth := &transporthttp.TokenAuth{Token: "my-token"}
	ApplyAuth(req, tokenAuth)
	got := req.Header.Get("Authorization")
	if got == "" {
		t.Error("TokenAuth not applied: Authorization header is empty")
	}

// nil auth should not panic.
	req, _ = http.NewRequest("GET", "https://example.com", nil)
	ApplyAuth(req, nil)
}
```

Ainternal/gitproto/smarthttp\_test.go+78

```
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

package planner

import (
	"fmt"
	"testing"

git "github.com/go-git/go-git/v5"
	"github.com/go-git/go-git/v5/plumbing"
	"github.com/go-git/go-git/v5/storage/memory"
)

func BenchmarkBuildDesiredRefs(b *testing.B) {
	sourceRefs := make(map[plumbing.ReferenceName]plumbing.Hash, 100)
	for i := 0; i < 100; i++ {
		name := plumbing.NewBranchReferenceName(fmt.Sprintf("branch-%03d", i))
		sourceRefs[name] = plumbing.NewHash(fmt.Sprintf("%040x", i+1))
	}
	cfg := PlanConfig{}

b.ResetTimer()
	for i := 0; i < b.N; i++ {
		_, _, err := BuildDesiredRefs(sourceRefs, cfg)
		if err != nil {
			b.Fatal(err)
		}
	}
}

func BenchmarkBuildPlans(b *testing.B) {
	repo, err := git.Init(memory.NewStorage(), nil)
	if err != nil {
		b.Fatalf("init repo: %v", err)
	}

// Build a two-commit chain so we can test fast-forward detection.
	root := seedCommit(b, repo, nil)
	tip := seedCommit(b, repo, []plumbing.Hash{root})

desired := make(map[plumbing.ReferenceName]DesiredRef, 100)
	targetRefs := make(map[plumbing.ReferenceName]plumbing.Hash, 100)
	managed := make(map[plumbing.ReferenceName]ManagedTarget, 100)

for i := 0; i < 100; i++ {
		ref := plumbing.NewBranchReferenceName(fmt.Sprintf("branch-%03d", i))
		short := ref.Short()

switch {
		case i < 50:
			// skip: source == target
			desired[ref] = DesiredRef{
				Kind: RefKindBranch, Label: short,
				SourceRef: ref, TargetRef: ref,
				SourceHash: root,
			}
			targetRefs[ref] = root
		case i < 75:
			// create: exists in desired, absent from target
			desired[ref] = DesiredRef{
				Kind: RefKindBranch, Label: short,
				SourceRef: ref, TargetRef: ref,
				SourceHash: tip,
			}
			// no targetRefs entry -> ActionCreate
		default:
			// update (fast-forward): target at root, source at tip
			desired[ref] = DesiredRef{
				Kind: RefKindBranch, Label: short,
				SourceRef: ref, TargetRef: ref,
				SourceHash: tip,
			}
			targetRefs[ref] = root
		}
		managed[ref] = ManagedTarget{Kind: RefKindBranch, Label: short}
	}

cfg := PlanConfig{}

b.ResetTimer()
	for i := 0; i < b.N; i++ {
		// Copy managed map each iteration because BuildPlans can mutate it
		// when Prune is set (not the case here, but copy for safety).
		mgdCopy := make(map[plumbing.ReferenceName]ManagedTarget, len(managed))
		for k, v := range managed {
			mgdCopy[k] = v
		}
		_, err := BuildPlans(repo.Storer, desired, targetRefs, mgdCopy, cfg)
		if err != nil {
			b.Fatal(err)
		}
	}
}

func BenchmarkSampledCheckpointCandidates(b *testing.B) {
	// Simulate a chain of 10000 commits; prevSpan of 500.
	lo := 100
	hi := 9999
	prevSpan := 500

b.ResetTimer()
	for i := 0; i < b.N; i++ {
		candidates := SampledCheckpointCandidates(lo, hi, prevSpan)
		if len(candidates) == 0 {
			b.Fatal("expected candidates")
		}
	}
}

func BenchmarkReachesCommit(b *testing.B) {
	repo, err := git.Init(memory.NewStorage(), nil)
	if err != nil {
		b.Fatalf("init repo: %v", err)
	}

// Build a 100-commit linear chain.
	hashes := make([]plumbing.Hash, 100)
	hashes[0] = seedCommit(b, repo, nil)
	for i := 1; i < 100; i++ {
		hashes[i] = seedCommit(b, repo, []plumbing.Hash{hashes[i-1]})
	}

tip := hashes[99]
	root := hashes[0]

b.ResetTimer()
	for i := 0; i < b.N; i++ {
		ok, err := ReachesCommit(repo.Storer, tip, root)
		if err != nil {
			b.Fatal(err)
		}
		if !ok {
			b.Fatal("expected tip to reach root")
		}
	}
}

// seedCommit is defined in planner_test.go with a testing.TB parameter,
// so it is usable from both tests and benchmarks.
```

Ainternal/planner/benchmark\_test.go+137

package planner

import (
	"fmt"
	"sort"

"github.com/go-git/go-git/v5/plumbing"
	"github.com/go-git/go-git/v5/plumbing/object"
	"github.com/go-git/go-git/v5/plumbing/storer"
)

// BootstrapBatch holds the checkpoint plan for a single branch during batched bootstrap.
type BootstrapBatch struct {
	Plan        BranchPlan
	TempRef     plumbing.ReferenceName
	ResumeHash  plumbing.Hash
	Checkpoints []plumbing.Hash
}

// FirstParentChain walks the first-parent chain from tip back to root,
// returning the chain in root-to-tip order.
func FirstParentChain(store storer.EncodedObjectStorer, tip plumbing.Hash) ([]plumbing.Hash, error) {
	commit, err := object.GetCommit(store, tip)
	if err != nil {
		return nil, err
	}
	chain := make([]plumbing.Hash, 0, 128)
	for {
		chain = append(chain, commit.Hash)
		if len(commit.ParentHashes) == 0 {
			break
		}
		commit, err = object.GetCommit(store, commit.ParentHashes[0])
		if err != nil {
			return nil, err
		}
	}
	// Reverse in-place to get root-to-tip order.
	for i, j := 0, len(chain)-1; i < j; i, j = i+1, j-1 {
		chain[i], chain[j] = chain[j], chain[i]
	}
	return chain, nil
}

// SampledCheckpointCandidates generates a set of candidate indices to probe,
// sorted from largest (preferred) to smallest.
func SampledCheckpointCandidates(lo, hi int, prevSpan int) []int {
	if lo > hi {
		return nil
	}
	set := map[int]struct{}{}
	add := func(idx int) {
		if idx < lo {
			idx = lo
		}
		if idx > hi {
			idx = hi
		}
		set[idx] = struct{}{}
	}

projected := hi
	if prevSpan > 0 {
		projected = lo + prevSpan - 1
	}
	add(projected)

const sampleCount = 4
	current := projected
	for i := 0; i < sampleCount-1; i++ {
		if current <= lo {
			add(lo)
			continue
		}
		distance := current - lo
		current = lo + distance/2
		add(current)
	}
	add(lo)

candidates := make([]int, 0, len(set))
	for idx := range set {
		candidates = append(candidates, idx)
	}
	sort.Sort(sort.Reverse(sort.IntSlice(candidates)))
	return candidates
}

// SampledCheckpointUnderLimit finds the largest checkpoint index that fits within
// the batch limit, using a sampling strategy to reduce probes (issue #14).
func SampledCheckpointUnderLimit(
	chain []plumbing.Hash,
	prevIdx int,
	prevSpan int,
	probe func(idx int) (tooLarge bool, err error),
) (int, error) {
	lo := prevIdx + 1
	hi := len(chain) - 1
	if lo > hi {
		return -1, nil
	}

samples := SampledCheckpointCandidates(lo, hi, prevSpan)
	best := -1
	for _, idx := range samples {
		tooLarge, err := probe(idx)
		if err != nil {
			return -1, err
		}
		if tooLarge {
			continue
		}
		best = idx
		break
	}
	if best != -1 {
		return best, nil
	}

if prevSpan > 1 {
		shrunk := prevSpan / 2
		if shrunk < 1 {
			shrunk = 1
		}
		idx := lo + shrunk - 1
		if idx > hi {
			idx = hi
		}
		if idx >= lo {
			tooLarge, err := probe(idx)
			if err != nil {
				return -1, err
			}
			if !tooLarge {
				return idx, nil
			}
		}
	}

tooLarge, err := probe(lo)
	if err != nil {
		return -1, err
	}
	if tooLarge {
		return -1, nil
	}
	return lo, nil
}

// BootstrapResumeIndex finds the starting index in a checkpoint list given a resume hash.
func BootstrapResumeIndex(checkpoints []plumbing.Hash, resumeHash plumbing.Hash) (int, error) {
	if resumeHash.IsZero() {
		return 0, nil
	}
	for idx, checkpoint := range checkpoints {
		if checkpoint == resumeHash {
			return idx + 1, nil
		}
	}
	return 0, fmt.Errorf("temp ref hash %s does not match any planned checkpoint", resumeHash)
}
```

Ainternal/planner/checkpoint.go+161

```
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

package planner

import (
	"fmt"
	"strings"

"github.com/go-git/go-git/v5/plumbing"
)

// NormalizeMapping validates and normalizes a single ref mapping.
// It rejects branch-to-tag and tag-to-branch cross-kind mappings (issue #3).
func NormalizeMapping(m RefMapping) (plumbing.ReferenceName, plumbing.ReferenceName, RefKind, error) {
	src := strings.TrimSpace(m.Source)
	dst := strings.TrimSpace(m.Target)
	if src == "" || dst == "" {
		return "", "", "", fmt.Errorf("invalid mapping %q:%q: source and target must be non-empty", m.Source, m.Target)
	}

srcFQ := strings.HasPrefix(src, "refs/")
	dstFQ := strings.HasPrefix(dst, "refs/")

// Both fully qualified
	if srcFQ && dstFQ {
		sourceRef := plumbing.ReferenceName(src)
		targetRef := plumbing.ReferenceName(dst)
		srcKind := RefKindFromName(sourceRef)
		dstKind := RefKindFromName(targetRef)
		if srcKind == "" {
			return "", "", "", fmt.Errorf("unsupported source ref kind: %s", src)
		}
		if dstKind == "" {
			return "", "", "", fmt.Errorf("unsupported target ref kind: %s", dst)
		}
		if srcKind != dstKind {
			return "", "", "", fmt.Errorf("cross-kind mapping not allowed: %s (%s) -> %s (%s)", src, srcKind, dst, dstKind)
		}
		return sourceRef, targetRef, dstKind, nil
	}

// Both short names -> branch mapping
	if !srcFQ && !dstFQ {
		return plumbing.NewBranchReferenceName(src), plumbing.NewBranchReferenceName(dst), RefKindBranch, nil
	}

// Mixed: one FQ and one short -> reject as ambiguous (issue #3)
	return "", "", "", fmt.Errorf("ambiguous mapping: cannot mix fully-qualified and short ref names: %q -> %q", src, dst)
}

// ValidateMappings normalizes all mappings and checks for duplicate targets (issue #2).
// Validation happens before any network activity.
func ValidateMappings(mappings []RefMapping) ([]NormalizedMapping, error) {
	if len(mappings) == 0 {
		return nil, nil
	}

normalized := make([]NormalizedMapping, 0, len(mappings))
	targetSeen := make(map[plumbing.ReferenceName]string, len(mappings))

for _, m := range mappings {
		srcRef, dstRef, kind, err := NormalizeMapping(m)
		if err != nil {
			return nil, err
		}

// Check for duplicate target refs (issue #2)
		if prev, exists := targetSeen[dstRef]; exists {
			return nil, fmt.Errorf("duplicate target ref %s: mapped from both %q and %q", dstRef, prev, m.Source)
		}
		targetSeen[dstRef] = m.Source

normalized = append(normalized, NormalizedMapping{
			SourceRef: srcRef,
			TargetRef: dstRef,
			Kind:      kind,
		})
	}
	return normalized, nil
}

// NormalizedMapping is a validated and normalized ref mapping.
type NormalizedMapping struct {
	SourceRef plumbing.ReferenceName
	TargetRef plumbing.ReferenceName
	Kind      RefKind
}
```

Ainternal/planner/mapping.go+85

package planner

import (
	"errors"
	"fmt"
	"sort"

"github.com/go-git/go-git/v5/plumbing"
	"github.com/go-git/go-git/v5/plumbing/object"
	"github.com/go-git/go-git/v5/plumbing/storer"
)

// PlanConfig holds configuration for plan generation.
type PlanConfig struct {
	Branches    []string
	Mappings    []RefMapping
	IncludeTags bool
	Force       bool
	Prune       bool
}

// BuildDesiredRefs constructs the set of desired refs and managed targets from
// source refs and user configuration. All mapping validation happens here,
// before any network activity (issue #2, #3).
func BuildDesiredRefs(
	sourceRefs map[plumbing.ReferenceName]plumbing.Hash,
	cfg PlanConfig,
) (map[plumbing.ReferenceName]DesiredRef, map[plumbing.ReferenceName]ManagedTarget, error) {
	desired := make(map[plumbing.ReferenceName]DesiredRef)
	managed := make(map[plumbing.ReferenceName]ManagedTarget)

addManaged := func(sourceRef, targetRef plumbing.ReferenceName, kind RefKind, hash plumbing.Hash) error {
		if hash.IsZero() {
			return fmt.Errorf("source ref %s not found", sourceRef)
		}
		// Reject duplicate target refs from different sources (issue #2, #3).
		if existing, ok := desired[targetRef]; ok && existing.SourceRef != sourceRef {
			return fmt.Errorf("duplicate target ref %s: mapped from both %s and %s", targetRef, existing.SourceRef, sourceRef)
		}
		short := targetRef.Short()
		desired[targetRef] = DesiredRef{
			Kind:       kind,
			Label:      short,
			SourceRef:  sourceRef,
			TargetRef:  targetRef,
			SourceHash: hash,
		}
		managed[targetRef] = ManagedTarget{Kind: kind, Label: short}
		return nil
	}

if len(cfg.Mappings) > 0 {
		// Validate all mappings up front (issue #2, #3)
		normalized, err := ValidateMappings(cfg.Mappings)
		if err != nil {
			return nil, nil, err
		}
		for _, nm := range normalized {
			if err := addManaged(nm.SourceRef, nm.TargetRef, nm.Kind, sourceRefs[nm.SourceRef]); err != nil {
				return nil, nil, err
			}
		}
	} else {
		branches := BranchMapFromRefHashMap(sourceRefs)
		selected := SelectBranches(branches, cfg.Branches)
		for branch, hash := range selected {
			refName := plumbing.NewBranchReferenceName(branch)
			if err := addManaged(refName, refName, RefKindBranch, hash); err != nil {
				return nil, nil, err
			}
		}
	}

if cfg.IncludeTags {
		for refName, hash := range sourceRefs {
			if !refName.IsTag() {
				continue
			}
			if err := addManaged(refName, refName, RefKindTag, hash); err != nil {
				return nil, nil, err
			}
		}
	}

return desired, managed, nil
}

// BuildPlans generates the action plans for each managed ref.
func BuildPlans(
	store storer.EncodedObjectStorer,
	desired map[plumbing.ReferenceName]DesiredRef,
	targetRefs map[plumbing.ReferenceName]plumbing.Hash,
	managed map[plumbing.ReferenceName]ManagedTarget,
	cfg PlanConfig,
) ([]BranchPlan, error) {
	if cfg.Prune {
		for targetRef := range targetRefs {
			if _, ok := managed[targetRef]; ok {
				continue
			}
			switch {
			case targetRef.IsTag() && cfg.IncludeTags:
				managed[targetRef] = ManagedTarget{Kind: RefKindTag, Label: targetRef.Short()}
			case targetRef.IsBranch() && len(cfg.Mappings) == 0 && len(cfg.Branches) == 0:
				managed[targetRef] = ManagedTarget{Kind: RefKindBranch, Label: targetRef.Short()}
			}
		}
	}

targetNames := make([]plumbing.ReferenceName, 0, len(managed))
	for name := range managed {
		targetNames = append(targetNames, name)
	}
	sort.Slice(targetNames, func(i, j int) bool { return targetNames[i] < targetNames[j] })

plans := make([]BranchPlan, 0, len(targetNames))
	for _, targetRef := range targetNames {
		info := managed[targetRef]
		want, existsInDesired := desired[targetRef]
		targetHash, existsOnTarget := targetRefs[targetRef]

if !existsInDesired {
			if cfg.Prune && existsOnTarget {
				plans = append(plans, BranchPlan{
					Branch:     info.Label,
					TargetRef:  targetRef,
					TargetHash: targetHash,
					Kind:       info.Kind,
					Action:     ActionDelete,
					Reason:     fmt.Sprintf("%s -> <deleted>", ShortHash(targetHash)),
				})
			}
			continue
		}

if !existsOnTarget {
			plans = append(plans, BranchPlan{
				Branch:     want.Label,
				SourceRef:  want.SourceRef,
				TargetRef:  want.TargetRef,
				SourceHash: want.SourceHash,
				Kind:       want.Kind,
				Action:     ActionCreate,
				Reason:     fmt.Sprintf("%s -> <new>", ShortHash(want.SourceHash)),
			})
			continue
		}

plan, err := PlanRef(store, want, targetHash, cfg.Force)
		if err != nil {
			return nil, err
		}
		plans = append(plans, plan)
	}

sort.Slice(plans, func(i, j int) bool {
		return plans[i].TargetRef.String() < plans[j].TargetRef.String()
	})
	return plans, nil
}

// BuildBootstrapPlans creates plans for an empty-target bootstrap.
func BuildBootstrapPlans(
	desired map[plumbing.ReferenceName]DesiredRef,
	targetRefs map[plumbing.ReferenceName]plumbing.Hash,
) ([]BranchPlan, error) {
	targetNames := make([]plumbing.ReferenceName, 0, len(desired))
	for _, want := range desired {
		targetNames = append(targetNames, want.TargetRef)
	}
	sort.Slice(targetNames, func(i, j int) bool { return targetNames[i] < targetNames[j] })

plans := make([]BranchPlan, 0, len(targetNames))
	for _, targetRef := range targetNames {
		targetHash := targetRefs[targetRef]
		if !targetHash.IsZero() {
			return nil, fmt.Errorf("target ref %s already exists; use sync for non-bootstrap runs", targetRef)
		}
		want := desired[targetRef]
		plans = append(plans, BranchPlan{
			Branch:     want.Label,
			SourceRef:  want.SourceRef,
			TargetRef:  want.TargetRef,
			SourceHash: want.SourceHash,
			TargetHash: plumbing.ZeroHash,
			Kind:       want.Kind,
			Action:     ActionCreate,
			Reason:     fmt.Sprintf("create %s at %s", want.TargetRef, ShortHash(want.SourceHash)),
		})
	}
	return plans, nil
}

// PlanRef determines the action for a single ref that exists on both source and target.
func PlanRef(store storer.EncodedObjectStorer, want DesiredRef, targetHash plumbing.Hash, force bool) (BranchPlan, error) {
	plan := BranchPlan{
		Branch:     want.Label,
		SourceRef:  want.SourceRef,
		TargetRef:  want.TargetRef,
		SourceHash: want.SourceHash,
		TargetHash: targetHash,
		Kind:       want.Kind,
	}

if want.SourceHash == targetHash {
		plan.Action = ActionSkip
		plan.Reason = fmt.Sprintf("%s already current", ShortHash(want.SourceHash))
		return plan, nil
	}

if want.Kind == RefKindTag {
		if force {
			plan.Action = ActionUpdate
			plan.Reason = fmt.Sprintf("%s -> %s (force tag update)", ShortHash(targetHash), ShortHash(want.SourceHash))
			return plan, nil
		}
		plan.Action = ActionBlock
		plan.Reason = fmt.Sprintf("%s differs from %s; use --force to retarget tag", ShortHash(targetHash), ShortHash(want.SourceHash))
		return plan, nil
	}

isFF, err := ReachesCommit(store, want.SourceHash, targetHash)
	if err != nil {
		if errors.Is(err, ErrAncestryDepthExceeded) {
			// Can't prove fast-forward within depth limit — block with explanation.
			plan.Action = ActionBlock
			plan.Reason = fmt.Sprintf("ancestry check for %s exceeded depth limit; use --force if this is a valid fast-forward", want.TargetRef)
			return plan, nil
		}
		return plan, fmt.Errorf("check fast-forward for %s: %w", want.TargetRef, err)
	}
	if isFF {
		plan.Action = ActionUpdate
		plan.Reason = fmt.Sprintf("%s -> %s", ShortHash(targetHash), ShortHash(want.SourceHash))
		return plan, nil
	}

if force {
		plan.Action = ActionUpdate
		plan.Reason = fmt.Sprintf("%s -> %s (force)", ShortHash(targetHash), ShortHash(want.SourceHash))
		return plan, nil
	}

plan.Action = ActionBlock
	plan.Reason = fmt.Sprintf("%s is not an ancestor of %s", ShortHash(targetHash), ShortHash(want.SourceHash))
	return plan, nil
}

// MaxAncestryDepth is the maximum number of commits to visit during a
// fast-forward ancestry check. This prevents full graph walks on very
// large histories (issue #16). Set high enough to avoid false negatives
// on real repos — even the Linux kernel has ~1.3M commits.
const MaxAncestryDepth = 2_000_000

// ErrAncestryDepthExceeded is returned when ReachesCommit exceeds MaxAncestryDepth.
var ErrAncestryDepthExceeded = errors.New("ancestry check exceeded depth limit")

// ReachesCommit checks whether the commit at startHash has targetHash as an
// ancestor, bounded to MaxAncestryDepth commits to prevent degenerate walks.
func ReachesCommit(store storer.EncodedObjectStorer, startHash, targetHash plumbing.Hash) (bool, error) {
	if startHash == targetHash {
		return true, nil
	}

start, err := object.GetCommit(store, startHash)
	if err != nil {
		return false, fmt.Errorf("load source commit %s: %w", startHash, err)
	}

seen := map[plumbing.Hash]struct{}{}
	stack := []*object.Commit{start}

for len(stack) > 0 {
		if len(seen) >= MaxAncestryDepth {
			return false, ErrAncestryDepthExceeded
		}
		current := stack[len(stack)-1]
		stack = stack[:len(stack)-1]
		if _, ok := seen[current.Hash]; ok {
			continue
		}
		seen[current.Hash] = struct{}{}

for _, parentHash := range current.ParentHashes {
			if parentHash == targetHash {
				return true, nil
			}
			if _, ok := seen[parentHash]; ok {
				continue
			}
			parent, err := object.GetCommit(store, parentHash)
			if err != nil {
				if errors.Is(err, plumbing.ErrObjectNotFound) {
					continue
				}
				return false, err
			}
			stack = append(stack, parent)
		}
	}
	return false, nil
}

// ObjectsToPush computes the set of objects that need to be sent to the target.
func ObjectsToPush(store storer.EncodedObjectStorer, wants []plumbing.Hash, targetRefs map[plumbing.ReferenceName]plumbing.Hash) ([]plumbing.Hash, error) {
	haveSet := make(map[plumbing.Hash]struct{})
	for _, h := range targetRefs {
		if !h.IsZero() {
			haveSet[h] = struct{}{}
		}
	}

filteredWants := make([]plumbing.Hash, 0, len(wants))
	for _, h := range wants {
		if _, ok := haveSet[h]; !ok {
			filteredWants = append(filteredWants, h)
		}
	}
	if len(filteredWants) == 0 {
		return nil, nil
	}

seen := make(map[plumbing.Hash]bool, len(filteredWants)*4)
	objects := make([]plumbing.Hash, 0, len(filteredWants)*16)
	for _, h := range filteredWants {
		if err := collectObjects(store, h, haveSet, seen, &objects); err != nil {
			return nil, err
		}
	}
	return objects, nil
}

func collectObjects(
	store storer.EncodedObjectStorer,
	hash plumbing.Hash,
	haves map[plumbing.Hash]struct{},
	seen map[plumbing.Hash]bool,
	out *[]plumbing.Hash,
) error {
	if hash.IsZero() {
		return nil
	}
	if _, ok := haves[hash]; ok {
		return nil
	}
	if seen[hash] {
		return nil
	}
	seen[hash] = true

obj, err := store.EncodedObject(plumbing.AnyObject, hash)
	if err != nil {
		return fmt.Errorf("load object %s: %w", hash, err)
	}

switch obj.Type() {
	case plumbing.CommitObject:
		commit, err := object.GetCommit(store, hash)
		if err != nil {
			return fmt.Errorf("load commit %s: %w", hash, err)
		}
		if err := collectObjects(store, commit.TreeHash, haves, seen, out); err != nil {
			return err
		}
		for _, ph := range commit.ParentHashes {
			if err := collectObjects(store, ph, haves, seen, out); err != nil {
				return err
			}
		}
	case plumbing.TreeObject:
		tree, err := object.GetTree(store, hash)
		if err != nil {
			return fmt.Errorf("load tree %s: %w", hash, err)
		}
		for _, entry := range tree.Entries {
			if err := collectObjects(store, entry.Hash, haves, seen, out); err != nil {
				return err
			}
		}
	case plumbing.TagObject:
		tag, err := object.GetTag(store, hash)
		if err != nil {
			return fmt.Errorf("load tag %s: %w", hash, err)
		}
		if err := collectObjects(store, tag.Target, haves, seen, out); err != nil {
			return err
		}
	case plumbing.BlobObject:
	default:
		return fmt.Errorf("unsupported object type %s for %s", obj.Type(), hash)
	}

*out = append(*out, hash)
	return nil
}
```

Ainternal/planner/planner.go+395

package planner

import (
	"fmt"
	"slices"
	"testing"
	"time"

git "github.com/go-git/go-git/v5"
	"github.com/go-git/go-git/v5/plumbing"
	"github.com/go-git/go-git/v5/plumbing/object"
	"github.com/go-git/go-git/v5/plumbing/protocol/packp"
	"github.com/go-git/go-git/v5/plumbing/protocol/packp/capability"
	"github.com/go-git/go-git/v5/storage/memory"
)

func TestSelectBranches(t *testing.T) {
	source := map[string]plumbing.Hash{
		"main": plumbing.NewHash("1111111111111111111111111111111111111111"),
		"dev":  plumbing.NewHash("2222222222222222222222222222222222222222"),
	}
	got := SelectBranches(source, []string{"dev", "missing"})
	if len(got) != 1 || got["dev"] != source["dev"] {
		t.Fatalf("unexpected branch selection: %#v", got)
	}
}

func TestPlanRefSkip(t *testing.T) {
	hash := plumbing.NewHash("1111111111111111111111111111111111111111")
	plan, err := PlanRef(nil, DesiredRef{
		Kind: RefKindBranch, Label: "main",
		SourceRef: plumbing.NewBranchReferenceName("main"),
		TargetRef: plumbing.NewBranchReferenceName("main"),
		SourceHash: hash,
	}, hash, false)
	if err != nil {
		t.Fatalf("PlanRef error: %v", err)
	}
	if plan.Action != ActionSkip {
		t.Fatalf("expected skip, got %s", plan.Action)
	}
}

func TestPlanRefFastForwardAndBlock(t *testing.T) {
	repo, err := git.Init(memory.NewStorage(), nil)
	if err != nil {
		t.Fatalf("init repo: %v", err)
	}
	root := seedCommit(t, repo, nil)
	next := seedCommit(t, repo, []plumbing.Hash{root})
	side := seedCommit(t, repo, []plumbing.Hash{root})

ffPlan, err := PlanRef(repo.Storer, DesiredRef{
		Kind: RefKindBranch, Label: "main",
		SourceRef: plumbing.NewBranchReferenceName("main"),
		TargetRef: plumbing.NewBranchReferenceName("main"),
		SourceHash: next,
	}, root, false)
	if err != nil {
		t.Fatalf("PlanRef fast-forward: %v", err)
	}
	if ffPlan.Action != ActionUpdate {
		t.Fatalf("expected update, got %s", ffPlan.Action)
	}

blockPlan, err := PlanRef(repo.Storer, DesiredRef{
		Kind: RefKindBranch, Label: "main",
		SourceRef: plumbing.NewBranchReferenceName("main"),
		TargetRef: plumbing.NewBranchReferenceName("main"),
		SourceHash: side,
	}, next, false)
	if err != nil {
		t.Fatalf("PlanRef block: %v", err)
	}
	if blockPlan.Action != ActionBlock {
		t.Fatalf("expected block, got %s", blockPlan.Action)
	}
}

func TestValidateMappingsRejectsDuplicateTargets(t *testing.T) {
	_, err := ValidateMappings([]RefMapping{
		{Source: "main", Target: "stable"},
		{Source: "release", Target: "stable"},
	})
	if err == nil {
		t.Fatalf("expected error for duplicate target")
	}
}

func TestValidateMappingsRejectsCrossKind(t *testing.T) {
	_, err := ValidateMappings([]RefMapping{
		{Source: "refs/heads/main", Target: "refs/tags/main"},
	})
	if err == nil {
		t.Fatalf("expected error for cross-kind mapping")
	}
}

func TestValidateMappingsRejectsMixedQualification(t *testing.T) {
	_, err := ValidateMappings([]RefMapping{
		{Source: "refs/heads/main", Target: "stable"},
	})
	if err == nil {
		t.Fatalf("expected error for mixed qualification")
	}
}

func TestSampledCheckpointCandidates(t *testing.T) {
	candidates := SampledCheckpointCandidates(10, 100, 20)
	if len(candidates) == 0 {
		t.Fatalf("expected sampled candidates")
	}
	if candidates[0] != 29 {
		t.Fatalf("expected highest candidate first, got %v", candidates)
	}
	if !slices.Contains(candidates, 29) {
		t.Fatalf("expected projected candidate near previous span, got %v", candidates)
	}
	if !slices.Contains(candidates, 10) {
		t.Fatalf("expected lower bound candidate, got %v", candidates)
	}
}

func TestSampledCheckpointUnderLimit(t *testing.T) {
	chain := make([]plumbing.Hash, 40)
	for i := range chain {
		chain[i] = plumbing.NewHash(fmt.Sprintf("%040x", i+1))
	}
	var probes []int
	best, err := SampledCheckpointUnderLimit(chain, 4, 8, func(idx int) (bool, error) {
		probes = append(probes, idx)
		return idx > 19, nil
	})
	if err != nil {
		t.Fatalf("SampledCheckpointUnderLimit: %v", err)
	}
	if best < 12 || best > 19 {
		t.Fatalf("expected a reasonable sampled checkpoint, got %d", best)
	}
	if len(probes) > 6 {
		t.Fatalf("expected fixed small probe count, got %d probes: %v", len(probes), probes)
	}
}

func TestBuildDesiredRefsWithMappings(t *testing.T) {
	hash1 := plumbing.NewHash("1111111111111111111111111111111111111111")
	hash2 := plumbing.NewHash("2222222222222222222222222222222222222222")

sourceRefs := map[plumbing.ReferenceName]plumbing.Hash{
		plumbing.NewBranchReferenceName("main"):    hash1,
		plumbing.NewBranchReferenceName("develop"): hash2,
	}

tests := []struct {
		name        string
		mappings    []RefMapping
		wantTargets []plumbing.ReferenceName
		wantErr     bool
	}{
		{
			name: "simple rename mapping",
			mappings: []RefMapping{
				{Source: "main", Target: "stable"},
			},
			wantTargets: []plumbing.ReferenceName{
				plumbing.NewBranchReferenceName("stable"),
			},
		},
		{
			name: "multiple mappings",
			mappings: []RefMapping{
				{Source: "main", Target: "prod"},
				{Source: "develop", Target: "staging"},
			},
			wantTargets: []plumbing.ReferenceName{
				plumbing.NewBranchReferenceName("prod"),
				plumbing.NewBranchReferenceName("staging"),
			},
		},
		{
			name: "missing source ref errors",
			mappings: []RefMapping{
				{Source: "nonexistent", Target: "target"},
			},
			wantErr: true,
		},
		{
			name: "duplicate target errors",
			mappings: []RefMapping{
				{Source: "main", Target: "same"},
				{Source: "develop", Target: "same"},
			},
			wantErr: true,
		},
	}

for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			desired, managed, err := BuildDesiredRefs(sourceRefs, PlanConfig{
				Mappings: tt.mappings,
			})
			if tt.wantErr {
				if err == nil {
					t.Fatal("expected error, got nil")
				}
				return
			}
			if err != nil {
				t.Fatalf("unexpected error: %v", err)
			}
			if len(desired) != len(tt.wantTargets) {
				t.Fatalf("expected %d desired refs, got %d", len(tt.wantTargets), len(desired))
			}
			for _, target := range tt.wantTargets {
				if _, ok := desired[target]; !ok {
					t.Errorf("expected target ref %s in desired map", target)
				}
				if _, ok := managed[target]; !ok {
					t.Errorf("expected target ref %s in managed map", target)
				}
			}
		})
	}
}

func TestBuildDesiredRefsAllBranches(t *testing.T) {
	hash1 := plumbing.NewHash("1111111111111111111111111111111111111111")
	hash2 := plumbing.NewHash("2222222222222222222222222222222222222222")
	tagHash := plumbing.NewHash("3333333333333333333333333333333333333333")

sourceRefs := map[plumbing.ReferenceName]plumbing.Hash{
		plumbing.NewBranchReferenceName("main"):    hash1,
		plumbing.NewBranchReferenceName("develop"): hash2,
		plumbing.NewTagReferenceName("v1.0"):       tagHash,
	}

tests := []struct {
		name            string
		branches        []string
		includeTags     bool
		wantBranchCount int
		wantTagCount    int
	}{
		{
			name:            "no filter returns all branches",
			wantBranchCount: 2,
			wantTagCount:    0,
		},
		{
			name:            "filter to single branch",
			branches:        []string{"main"},
			wantBranchCount: 1,
			wantTagCount:    0,
		},
		{
			name:            "include tags adds tag refs",
			includeTags:     true,
			wantBranchCount: 2,
			wantTagCount:    1,
		},
		{
			name:            "branch filter plus tags",
			branches:        []string{"main"},
			includeTags:     true,
			wantBranchCount: 1,
			wantTagCount:    1,
		},
	}

for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			desired, _, err := BuildDesiredRefs(sourceRefs, PlanConfig{
				Branches:    tt.branches,
				IncludeTags: tt.includeTags,
			})
			if err != nil {
				t.Fatalf("unexpected error: %v", err)
			}
			branchCount, tagCount := 0, 0
			for _, d := range desired {
				switch d.Kind {
				case RefKindBranch:
					branchCount++
				case RefKindTag:
					tagCount++
				}
			}
			if branchCount != tt.wantBranchCount {
				t.Errorf("expected %d branches, got %d", tt.wantBranchCount, branchCount)
			}
			if tagCount != tt.wantTagCount {
				t.Errorf("expected %d tags, got %d", tt.wantTagCount, tagCount)
			}
		})
	}
}

func TestBuildPlansDelete(t *testing.T) {
	hash1 := plumbing.NewHash("1111111111111111111111111111111111111111")
	hash2 := plumbing.NewHash("2222222222222222222222222222222222222222")

mainRef := plumbing.NewBranchReferenceName("main")
	oldRef := plumbing.NewBranchReferenceName("old-branch")

desired := map[plumbing.ReferenceName]DesiredRef{
		mainRef: {
			Kind:       RefKindBranch,
			Label:      "main",
			SourceRef:  mainRef,
			TargetRef:  mainRef,
			SourceHash: hash1,
		},
	}
	managed := map[plumbing.ReferenceName]ManagedTarget{
		mainRef: {Kind: RefKindBranch, Label: "main"},
	}
	targetRefs := map[plumbing.ReferenceName]plumbing.Hash{
		mainRef: hash1,
		oldRef:  hash2,
	}

plans, err := BuildPlans(nil, desired, targetRefs, managed, PlanConfig{
		Prune: true,
	})
	if err != nil {
		t.Fatalf("BuildPlans error: %v", err)
	}

var deletePlan *BranchPlan
	for i, p := range plans {
		if p.Action == ActionDelete {
			deletePlan = &plans[i]
			break
		}
	}
	if deletePlan == nil {
		t.Fatal("expected a delete plan for old-branch")
	}
	if deletePlan.TargetRef != oldRef {
		t.Fatalf("expected delete for %s, got %s", oldRef, deletePlan.TargetRef)
	}
	if deletePlan.Kind != RefKindBranch {
		t.Fatalf("expected branch kind, got %s", deletePlan.Kind)
	}
}

func TestBuildPlansTagBlock(t *testing.T) {
	repo, err := git.Init(memory.NewStorage(), nil)
	if err != nil {
		t.Fatalf("init repo: %v", err)
	}
	hash1 := seedCommit(t, repo, nil)
	hash2 := seedCommit(t, repo, nil)

tagRef := plumbing.NewTagReferenceName("v1.0")

desired := map[plumbing.ReferenceName]DesiredRef{
		tagRef: {
			Kind:       RefKindTag,
			Label:      "v1.0",
			SourceRef:  tagRef,
			TargetRef:  tagRef,
			SourceHash: hash2,
		},
	}
	managed := map[plumbing.ReferenceName]ManagedTarget{
		tagRef: {Kind: RefKindTag, Label: "v1.0"},
	}
	targetRefs := map[plumbing.ReferenceName]plumbing.Hash{
		tagRef: hash1,
	}

plans, err := BuildPlans(repo.Storer, desired, targetRefs, managed, PlanConfig{
		Force: false,
	})
	if err != nil {
		t.Fatalf("BuildPlans error: %v", err)
	}
	if len(plans) != 1 {
		t.Fatalf("expected 1 plan, got %d", len(plans))
	}
	if plans[0].Action != ActionBlock {
		t.Fatalf("expected block action for tag without force, got %s", plans[0].Action)
	}
}

func TestBuildPlansTagForce(t *testing.T) {
	repo, err := git.Init(memory.NewStorage(), nil)
	if err != nil {
		t.Fatalf("init repo: %v", err)
	}
	hash1 := seedCommit(t, repo, nil)
	hash2 := seedCommit(t, repo, nil)

tagRef := plumbing.NewTagReferenceName("v1.0")

plans, err := BuildPlans(repo.Storer, desired, targetRefs, managed, PlanConfig{
		Force: true,
	})
	if err != nil {
		t.Fatalf("BuildPlans error: %v", err)
	}
	if len(plans) != 1 {
		t.Fatalf("expected 1 plan, got %d", len(plans))
	}
	if plans[0].Action != ActionUpdate {
		t.Fatalf("expected update action for tag with force, got %s", plans[0].Action)
	}
}

func TestBootstrapResumeIndex(t *testing.T) {
	checkpoints := []plumbing.Hash{
		plumbing.NewHash("1111111111111111111111111111111111111111"),
		plumbing.NewHash("2222222222222222222222222222222222222222"),
		plumbing.NewHash("3333333333333333333333333333333333333333"),
	}

tests := []struct {
		name       string
		resumeHash plumbing.Hash
		wantIdx    int
		wantErr    bool
	}{
		{
			name:       "zero hash starts at beginning",
			resumeHash: plumbing.ZeroHash,
			wantIdx:    0,
		},
		{
			name:       "match first checkpoint resumes at index 1",
			resumeHash: plumbing.NewHash("1111111111111111111111111111111111111111"),
			wantIdx:    1,
		},
		{
			name:       "match second checkpoint resumes at index 2",
			resumeHash: plumbing.NewHash("2222222222222222222222222222222222222222"),
			wantIdx:    2,
		},
		{
			name:       "match last checkpoint resumes past end",
			resumeHash: plumbing.NewHash("3333333333333333333333333333333333333333"),
			wantIdx:    3,
		},
		{
			name:       "mismatch hash returns error",
			resumeHash: plumbing.NewHash("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"),
			wantErr:    true,
		},
	}

for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			idx, err := BootstrapResumeIndex(checkpoints, tt.resumeHash)
			if tt.wantErr {
				if err == nil {
					t.Fatal("expected error, got nil")
				}
				return
			}
			if err != nil {
				t.Fatalf("unexpected error: %v", err)
			}
			if idx != tt.wantIdx {
				t.Fatalf("expected resume index %d, got %d", tt.wantIdx, idx)
			}
		})
	}
}

func TestFirstParentChain(t *testing.T) {
	repo, err := git.Init(memory.NewStorage(), nil)
	if err != nil {
		t.Fatalf("init repo: %v", err)
	}

// Build a linear chain: root -> mid -> tip
	root := seedCommit(t, repo, nil)
	mid := seedCommit(t, repo, []plumbing.Hash{root})
	tip := seedCommit(t, repo, []plumbing.Hash{mid})

chain, err := FirstParentChain(repo.Storer, tip)
	if err != nil {
		t.Fatalf("FirstParentChain error: %v", err)
	}

if len(chain) != 3 {
		t.Fatalf("expected chain of length 3, got %d: %v", len(chain), chain)
	}
	// Chain should be in root-to-tip order
	if chain[0] != root {
		t.Errorf("chain[0] = %s, want root %s", chain[0], root)
	}
	if chain[1] != mid {
		t.Errorf("chain[1] = %s, want mid %s", chain[1], mid)
	}
	if chain[2] != tip {
		t.Errorf("chain[2] = %s, want tip %s", chain[2], tip)
	}
}

func TestValidateMappingsEmpty(t *testing.T) {
	result, err := ValidateMappings(nil)
	if err != nil {
		t.Fatalf("expected nil error for empty mappings, got %v", err)
	}
	if result != nil {
		t.Fatalf("expected nil result for empty mappings, got %v", result)
	}
}

func TestValidateMappingsValidBranch(t *testing.T) {
	normalized, err := ValidateMappings([]RefMapping{
		{Source: "main", Target: "stable"},
	})
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if len(normalized) != 1 {
		t.Fatalf("expected 1 normalized mapping, got %d", len(normalized))
	}
	nm := normalized[0]
	if nm.SourceRef != plumbing.NewBranchReferenceName("main") {
		t.Fatalf("expected source ref refs/heads/main, got %s", nm.SourceRef)
	}
	if nm.TargetRef != plumbing.NewBranchReferenceName("stable") {
		t.Fatalf("expected target ref refs/heads/stable, got %s", nm.TargetRef)
	}
	if nm.Kind != RefKindBranch {
		t.Fatalf("expected kind branch, got %s", nm.Kind)
	}
}

func TestValidateMappingsValidFullRef(t *testing.T) {
	normalized, err := ValidateMappings([]RefMapping{
		{Source: "refs/heads/main", Target: "refs/heads/upstream-main"},
	})
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if len(normalized) != 1 {
		t.Fatalf("expected 1 normalized mapping, got %d", len(normalized))
	}
	nm := normalized[0]
	if nm.SourceRef != "refs/heads/main" {
		t.Fatalf("expected source ref refs/heads/main, got %s", nm.SourceRef)
	}
	if nm.TargetRef != "refs/heads/upstream-main" {
		t.Fatalf("expected target ref refs/heads/upstream-main, got %s", nm.TargetRef)
	}
	if nm.Kind != RefKindBranch {
		t.Fatalf("expected kind branch, got %s", nm.Kind)
	}
}

func TestBuildDesiredRefsEmptySource(t *testing.T) {
	// Empty source ref map with a branch filter: SelectBranches finds nothing,
	// so the desired map should be empty without error.
	desired, _, err := BuildDesiredRefs(
		map[plumbing.ReferenceName]plumbing.Hash{},
		PlanConfig{Branches: []string{"main"}},
	)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if len(desired) != 0 {
		t.Fatalf("expected empty desired refs for empty source, got %d", len(desired))
	}
}

func TestBuildDesiredRefsTagForceRetarget(t *testing.T) {
	// A tag that exists on both source and target with different hashes.
	// With force=true, PlanRef should give ActionUpdate.
	repo, err := git.Init(memory.NewStorage(), nil)
	if err != nil {
		t.Fatalf("init repo: %v", err)
	}
	sourceHash := seedCommit(t, repo, nil)
	targetHash := seedCommit(t, repo, nil)

tagRef := plumbing.NewTagReferenceName("v1.0")
	sourceRefs := map[plumbing.ReferenceName]plumbing.Hash{
		tagRef: sourceHash,
	}

desired, _, err := BuildDesiredRefs(sourceRefs, PlanConfig{IncludeTags: true})
	if err != nil {
		t.Fatalf("BuildDesiredRefs error: %v", err)
	}

targetRefs := map[plumbing.ReferenceName]plumbing.Hash{
		tagRef: targetHash,
	}

plans, err := BuildPlans(repo.Storer, desired, targetRefs, map[plumbing.ReferenceName]ManagedTarget{
		tagRef: {Kind: RefKindTag, Label: "v1.0"},
	}, PlanConfig{IncludeTags: true, Force: true})
	if err != nil {
		t.Fatalf("BuildPlans error: %v", err)
	}
	if len(plans) != 1 {
		t.Fatalf("expected 1 plan, got %d", len(plans))
	}
	if plans[0].Action != ActionUpdate {
		t.Fatalf("expected ActionUpdate for force-retarget tag, got %s", plans[0].Action)
	}
}

func TestBuildDesiredRefsDuplicateMappingTarget(t *testing.T) {
	// Two different source refs mapping to the same target via ValidateMappings
	// should be rejected before BuildDesiredRefs even resolves hashes.
	sourceRefs := map[plumbing.ReferenceName]plumbing.Hash{
		plumbing.NewBranchReferenceName("main"):    plumbing.NewHash("1111111111111111111111111111111111111111"),
		plumbing.NewBranchReferenceName("release"): plumbing.NewHash("2222222222222222222222222222222222222222"),
	}

_, _, err := BuildDesiredRefs(sourceRefs, PlanConfig{
		Mappings: []RefMapping{
			{Source: "main", Target: "stable"},
			{Source: "release", Target: "stable"},
		},
	})
	if err == nil {
		t.Fatalf("expected error for duplicate target ref from two different sources")
	}
}

func TestCanBootstrapRelayAllAbsent(t *testing.T) {
	hash := plumbing.NewHash("1111111111111111111111111111111111111111")
	desired := map[plumbing.ReferenceName]DesiredRef{
		"refs/heads/main": {
			Kind:       RefKindBranch,
			Label:      "main",
			SourceRef:  "refs/heads/main",
			TargetRef:  "refs/heads/main",
			SourceHash: hash,
		},
		"refs/heads/dev": {
			Kind:       RefKindBranch,
			Label:      "dev",
			SourceRef:  "refs/heads/dev",
			TargetRef:  "refs/heads/dev",
			SourceHash: hash,
		},
	}
	targetRefs := map[plumbing.ReferenceName]plumbing.Hash{}

ok, reason := CanBootstrapRelay(false, false, desired, targetRefs)
	if !ok {
		t.Fatalf("expected CanBootstrapRelay=true when all absent, got reason: %s", reason)
	}
}

func TestCanBootstrapRelayOneExists(t *testing.T) {
	hash := plumbing.NewHash("1111111111111111111111111111111111111111")
	desired := map[plumbing.ReferenceName]DesiredRef{
		"refs/heads/main": {
			Kind:       RefKindBranch,
			Label:      "main",
			SourceRef:  "refs/heads/main",
			TargetRef:  "refs/heads/main",
			SourceHash: hash,
		},
		"refs/heads/dev": {
			Kind:       RefKindBranch,
			Label:      "dev",
			SourceRef:  "refs/heads/dev",
			TargetRef:  "refs/heads/dev",
			SourceHash: hash,
		},
	}
	targetRefs := map[plumbing.ReferenceName]plumbing.Hash{
		"refs/heads/main": plumbing.NewHash("2222222222222222222222222222222222222222"),
	}

ok, reason := CanBootstrapRelay(false, false, desired, targetRefs)
	if ok {
		t.Fatalf("expected CanBootstrapRelay=false when one target exists")
	}
	if reason != "bootstrap-target-ref-exists" {
		t.Fatalf("unexpected reason: %s", reason)
	}
}

func TestCanIncrementalRelayMixed(t *testing.T) {
	// A mix of branch update + tag update (not create) should return false.
	// CanIncrementalRelay requires tags to have ActionCreate only.
	plans := []BranchPlan{
		{
			Branch:     "main",
			SourceRef:  "refs/heads/main",
			TargetRef:  "refs/heads/main",
			SourceHash: plumbing.NewHash("1111111111111111111111111111111111111111"),
			TargetHash: plumbing.NewHash("2222222222222222222222222222222222222222"),
			Kind:       RefKindBranch,
			Action:     ActionUpdate,
		},
		{
			Branch:     "v1.0",
			SourceRef:  "refs/tags/v1.0",
			TargetRef:  "refs/tags/v1.0",
			SourceHash: plumbing.NewHash("3333333333333333333333333333333333333333"),
			TargetHash: plumbing.NewHash("4444444444444444444444444444444444444444"),
			Kind:       RefKindTag,
			Action:     ActionUpdate, // tag update, not create
		},
	}

// Build a minimal AdvRefs with capabilities to pass the capability check.
	advRefs := &packp.AdvRefs{}
	advRefs.Capabilities = capability.NewList()

ok, reason := CanIncrementalRelay(false, false, false, plans, advRefs)
	if ok {
		t.Fatalf("expected CanIncrementalRelay=false for tag with ActionUpdate")
	}
	if reason != "incremental-tag-action-not-create" {
		t.Fatalf("unexpected reason: %s", reason)
	}
}

func seedCommit(tb testing.TB, repo *git.Repository, parents []plumbing.Hash) plumbing.Hash {
	tb.Helper()
	now := time.Now().UTC()
	obj := repo.Storer.NewEncodedObject()
	commit := &object.Commit{
		Author:       object.Signature{Name: "test", Email: "test@example.com", When: now},
		Committer:    object.Signature{Name: "test", Email: "test@example.com", When: now},
		Message:      fmt.Sprintf("test-%d-%d", len(parents), now.UnixNano()),
		TreeHash:     plumbing.ZeroHash,
		ParentHashes: parents,
	}
	if err := commit.Encode(obj); err != nil {
		tb.Fatalf("encode commit: %v", err)
	}
	hash, err := repo.Storer.SetEncodedObject(obj)
	if err != nil {
		tb.Fatalf("store commit: %v", err)
	}
	return hash
}
```

Ainternal/planner/planner\_test.go+756

```
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

package planner

import (
	"github.com/go-git/go-git/v5/plumbing"
	"github.com/go-git/go-git/v5/plumbing/protocol/packp"
	"github.com/go-git/go-git/v5/plumbing/protocol/packp/capability"
)

// CanBootstrapRelay checks whether all desired target refs are absent on the target,
// making a bootstrap relay possible.
func CanBootstrapRelay(
	force, prune bool,
	desired map[plumbing.ReferenceName]DesiredRef,
	targetRefs map[plumbing.ReferenceName]plumbing.Hash,
) (bool, string) {
	if force || prune {
		return false, "bootstrap-disabled-by-force-or-prune"
	}
	if len(desired) == 0 {
		return false, "bootstrap-no-managed-refs"
	}
	for targetRef := range desired {
		if !targetRefs[targetRef].IsZero() {
			return false, "bootstrap-target-ref-exists"
		}
	}
	return true, "empty-target-managed-refs"
}

// CanIncrementalRelay checks whether all plans are eligible for the incremental
// relay fast-path (fast-forward branch updates + new tag creates).
func CanIncrementalRelay(force, prune, dryRun bool, plans []BranchPlan, targetAdv *packp.AdvRefs) (bool, string) {
	if force || prune || dryRun {
		return false, "incremental-disabled-by-force-prune-or-dry-run"
	}
	if len(plans) == 0 {
		return false, "incremental-no-plans"
	}
	if targetAdv == nil || targetAdv.Capabilities == nil {
		return false, "incremental-missing-target-capabilities"
	}
	if targetAdv.Capabilities.Supports(capability.Capability("no-thin")) {
		return false, "incremental-target-no-thin"
	}

for _, plan := range plans {
		switch plan.Kind {
		case RefKindBranch:
			if !plan.SourceRef.IsBranch() || !plan.TargetRef.IsBranch() {
				return false, "incremental-non-branch-mapping"
			}
			if plan.Action != ActionUpdate {
				return false, "incremental-branch-action-not-update"
			}
			if plan.TargetHash.IsZero() {
				return false, "incremental-branch-target-missing"
			}
		case RefKindTag:
			if !plan.SourceRef.IsTag() || !plan.TargetRef.IsTag() {
				return false, "incremental-non-tag-mapping"
			}
			if plan.Action != ActionCreate {
				return false, "incremental-tag-action-not-create"
			}
		default:
			return false, "incremental-unsupported-ref-kind"
		}
	}
	return true, "fast-forward-branch-or-tag-create"
}

// CanFullTagCreateRelay checks whether all plans are tag creates, eligible for
// a full-pack tag relay.
func CanFullTagCreateRelay(plans []BranchPlan) (bool, string) {
	if len(plans) == 0 {
		return false, "incremental-no-plans"
	}
	for _, plan := range plans {
		if plan.Kind != RefKindTag {
			return false, "incremental-tag-relay-non-tag-plan"
		}
		if !plan.SourceRef.IsTag() || !plan.TargetRef.IsTag() {
			return false, "incremental-tag-relay-non-tag-mapping"
		}
		if plan.Action != ActionCreate {
			return false, "incremental-tag-relay-tag-action-not-create"
		}
	}
	return true, "tag-create-full-pack"
}

// RelayFallbackReason returns the reason why relay was not used.
func RelayFallbackReason(force, prune, dryRun bool, plans []BranchPlan, targetAdv *packp.AdvRefs) string {
	if ok, reason := CanIncrementalRelay(force, prune, dryRun, plans, targetAdv); ok {
		return reason
	} else if ok, reason := CanFullTagCreateRelay(plans); ok {
		return reason
	} else {
		return reason
	}
}
```

Ainternal/planner/relay.go+101

package planner

import (
	"encoding/json"
	"fmt"
	"sort"
	"strings"

"github.com/go-git/go-git/v5/plumbing"
)

// RefKind distinguishes branch refs from tag refs.
type RefKind string

const (
	RefKindBranch RefKind = "branch"
	RefKindTag    RefKind = "tag"
)

// Action represents the planned operation on a ref.
type Action string

const (
	ActionCreate Action = "create"
	ActionUpdate Action = "update"
	ActionDelete Action = "delete"
	ActionSkip   Action = "skip"
	ActionBlock  Action = "block"
)

// RefMapping is a user-specified source:target mapping.
type RefMapping struct {
	Source string
	Target string
}

// DesiredRef represents a source ref that should be mirrored to a target ref.
type DesiredRef struct {
	Kind       RefKind
	Label      string
	SourceRef  plumbing.ReferenceName
	TargetRef  plumbing.ReferenceName
	SourceHash plumbing.Hash
}

// ManagedTarget tracks which target refs are managed by git-sync.
type ManagedTarget struct {
	Kind  RefKind
	Label string
}

// BranchPlan describes the planned action for a single ref.
type BranchPlan struct {
	Branch     string                 `json:"branch"`
	SourceRef  plumbing.ReferenceName `json:"source_ref"`
	TargetRef  plumbing.ReferenceName `json:"target_ref"`
	SourceHash plumbing.Hash          `json:"source_hash"`
	TargetHash plumbing.Hash          `json:"target_hash"`
	Kind       RefKind                `json:"kind"`
	Action     Action                 `json:"action"`
	Reason     string                 `json:"reason"`
}

func (p BranchPlan) MarshalJSON() ([]byte, error) {
	type bp struct {
		Branch     string  `json:"branch"`
		SourceRef  string  `json:"source_ref"`
		TargetRef  string  `json:"target_ref"`
		SourceHash string  `json:"source_hash"`
		TargetHash string  `json:"target_hash"`
		Kind       RefKind `json:"kind"`
		Action     Action  `json:"action"`
		Reason     string  `json:"reason"`
	}
	return json.Marshal(bp{
		Branch:     p.Branch,
		SourceRef:  p.SourceRef.String(),
		TargetRef:  p.TargetRef.String(),
		SourceHash: p.SourceHash.String(),
		TargetHash: p.TargetHash.String(),
		Kind:       p.Kind,
		Action:     p.Action,
		Reason:     p.Reason,
	})
}

// ShortHash returns the first 8 characters of a hash, or "<zero>" for zero hashes.
func ShortHash(hash plumbing.Hash) string {
	if hash.IsZero() {
		return "<zero>"
	}
	s := hash.String()
	if len(s) > 8 {
		return s[:8]
	}
	return s
}

// RefKindFromName infers the ref kind from a fully qualified ref name.
func RefKindFromName(name plumbing.ReferenceName) RefKind {
	switch {
	case name.IsBranch():
		return RefKindBranch
	case name.IsTag():
		return RefKindTag
	default:
		return ""
	}
}

// ActionForTargetHash returns ActionCreate for zero hashes, ActionUpdate otherwise.
func ActionForTargetHash(hash plumbing.Hash) Action {
	if hash.IsZero() {
		return ActionCreate
	}
	return ActionUpdate
}

// BranchMapFromRefHashMap extracts short branch names from a ref hash map.
func BranchMapFromRefHashMap(refs map[plumbing.ReferenceName]plumbing.Hash) map[string]plumbing.Hash {
	branches := make(map[string]plumbing.Hash)
	for name, hash := range refs {
		if name.IsBranch() {
			branches[name.Short()] = hash
		}
	}
	return branches
}

// SelectBranches filters branches to only the requested ones.
// If requested is empty, returns all.
func SelectBranches(source map[string]plumbing.Hash, requested []string) map[string]plumbing.Hash {
	if len(requested) == 0 {
		return source
	}
	selected := make(map[string]plumbing.Hash, len(requested))
	for _, branch := range requested {
		if hash, ok := source[branch]; ok {
			selected[branch] = hash
		}
	}
	return selected
}

// RefPrefixes computes the ref-prefix arguments for v2 ls-refs based on
// the user's configuration.
func RefPrefixes(mappings []RefMapping, includeTags bool) []string {
	prefixSet := map[string]struct{}{}
	if len(mappings) > 0 {
		for _, m := range mappings {
			src := strings.TrimSpace(m.Source)
			if strings.HasPrefix(src, "refs/tags/") {
				prefixSet["refs/tags/"] = struct{}{}
			} else if strings.HasPrefix(src, "refs/heads/") {
				prefixSet["refs/heads/"] = struct{}{}
			} else if !strings.HasPrefix(src, "refs/") {
				prefixSet["refs/heads/"] = struct{}{}
			}
		}
	} else {
		prefixSet["refs/heads/"] = struct{}{}
	}
	if includeTags {
		prefixSet["refs/tags/"] = struct{}{}
	}
	prefixes := make([]string, 0, len(prefixSet))
	for p := range prefixSet {
		prefixes = append(prefixes, p)
	}
	sort.Strings(prefixes)
	return prefixes
}

// CopyRefHashMap returns a shallow copy of a ref hash map.
func CopyRefHashMap(input map[plumbing.ReferenceName]plumbing.Hash) map[plumbing.ReferenceName]plumbing.Hash {
	out := make(map[plumbing.ReferenceName]plumbing.Hash, len(input))
	for k, v := range input {
		out[k] = v
	}
	return out
}

// DesiredSubset returns the subset of desired refs that match the given plans.
func DesiredSubset(
	desired map[plumbing.ReferenceName]DesiredRef,
	plans []BranchPlan,
) map[plumbing.ReferenceName]DesiredRef {
	out := make(map[plumbing.ReferenceName]DesiredRef, len(plans))
	for _, plan := range plans {
		if ref, ok := desired[plan.TargetRef]; ok {
			out[plan.TargetRef] = ref
		}
	}
	return out
}

// SingleDesired builds a single-entry desired ref map.
func SingleDesired(sourceRef, targetRef plumbing.ReferenceName, hash plumbing.Hash) map[plumbing.ReferenceName]DesiredRef {
	return map[plumbing.ReferenceName]DesiredRef{
		targetRef: {
			Kind:       RefKindBranch,
			Label:      targetRef.Short(),
			SourceRef:  sourceRef,
			TargetRef:  targetRef,
			SourceHash: hash,
		},
	}
}

// SingleHaveMap builds a single-entry have map for fetch negotiation.
func SingleHaveMap(hash plumbing.Hash) map[plumbing.ReferenceName]plumbing.Hash {
	if hash.IsZero() {
		return nil
	}
	return map[plumbing.ReferenceName]plumbing.Hash{
		plumbing.ReferenceName("refs/gitsync/have"): hash,
	}
}

// BootstrapTempRef returns the temporary ref name used during batched bootstrap.
func BootstrapTempRef(targetRef plumbing.ReferenceName) plumbing.ReferenceName {
	return plumbing.ReferenceName("refs/gitsync/bootstrap/heads/" + targetRef.Short())
}

// FormatPlanLine formats a single plan entry for human-readable output.
func FormatPlanLine(plan BranchPlan) string {
	label := plan.Branch
	if plan.TargetRef != "" {
		label = plan.TargetRef.String()
	}
	line := fmt.Sprintf("%s %s", strings.ToUpper(string(plan.Action)), label)
	if plan.Reason != "" {
		line += " - " + plan.Reason
	}
	return line
}
```

Ainternal/planner/types.go+236

// Package bootstrap implements the bootstrap relay strategy for git-sync.
// This handles initial seeding of an empty target, both one-shot and batched.
package bootstrap

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"os"
	"regexp"
	"strconv"
	"strings"

git "github.com/go-git/go-git/v5"
	"github.com/go-git/go-git/v5/plumbing"
	"github.com/go-git/go-git/v5/plumbing/protocol/packp"
	"github.com/go-git/go-git/v5/plumbing/protocol/packp/capability"
	"github.com/go-git/go-git/v5/storage/memory"

"github.com/soph/git-sync/internal/gitproto"
	"github.com/soph/git-sync/internal/planner"
)

const (
	defaultAutoBatchMaxPackBytes = 512 * 1024 * 1024
	githubLargeRepoThresholdKB   = 1536 * 1024
)

var bodyLimitPattern = regexp.MustCompile(`body exceeded size limit ([0-9]+)`)

// GitHubRepoAPIBaseURL is the base for GitHub API calls (replaceable in tests).
var GitHubRepoAPIBaseURL = "https://api.github.com"

// Params holds the inputs for a bootstrap execution.
type Params struct {
	SourceConn    *gitproto.Conn
	TargetConn    *gitproto.Conn
	SourceService *gitproto.RefService
	TargetAdv     *packp.AdvRefs
	DesiredRefs   map[plumbing.ReferenceName]planner.DesiredRef
	TargetRefs    map[plumbing.ReferenceName]plumbing.Hash
	MaxPackBytes int64
	BatchMaxPack int64
	Verbose      bool
}

// Result holds the outcome of the bootstrap strategy.
type Result struct {
	Plans             []planner.BranchPlan
	Pushed            int
	Relay             bool
	RelayMode         string
	RelayReason       string
	Batching          bool
	BatchCount        int
	PlannedBatchCount int
	TempRefs          []string
}

// Execute runs the bootstrap strategy (one-shot or batched).
func Execute(ctx context.Context, p Params, relayReason string) (Result, error) {
	plans, err := planner.BuildBootstrapPlans(p.DesiredRefs, p.TargetRefs)
	if err != nil {
		return Result{}, err
	}

result := Result{
		Plans: plans, Relay: true, RelayMode: "bootstrap", RelayReason: relayReason,
	}

// GitHub large-repo preflight
	if batchLimit, ok := githubBatchLimit(ctx, p); ok {
		p.BatchMaxPack = batchLimit
		progressf(p.Verbose, "bootstrap: github repo-size preflight selected batched mode with batch-max-pack-bytes=%d", p.BatchMaxPack)
	}

if p.BatchMaxPack > 0 {
		return executeBatched(ctx, p, plans, result)
	}

// One-shot bootstrap
	progressf(p.Verbose, "bootstrap: fetching %d ref(s) from source", len(plans))
	gpDesired := toGP(p.DesiredRefs)
	packReader, err := p.SourceService.FetchPack(ctx, p.SourceConn, gpDesired, nil)
	if err != nil {
		if errors.Is(err, git.NoErrAlreadyUpToDate) {
			return result, nil
		}
		return result, fmt.Errorf("fetch source pack: %w", err)
	}
	packReader = gitproto.LimitPackReader(packReader, p.MaxPackBytes)

progressf(p.Verbose, "bootstrap: pushing %d ref(s) to target", len(plans))
	cmds := gitproto.ToPushCommands(plansToPushPlans(plans))
	pushErr := gitproto.PushPack(ctx, p.TargetConn, p.TargetAdv, cmds, packReader, p.Verbose)
	if pushErr != nil {
		autoBatch, ok := autoBatchMaxPackBytes(p, pushErr)
		if !ok {
			return result, fmt.Errorf("push target refs: %w", pushErr)
		}
		progressf(p.Verbose, "bootstrap: target rejected; retrying with batch-max-pack-bytes=%d", autoBatch)
		p.BatchMaxPack = autoBatch
		return executeBatched(ctx, p, plans, result)
	}

result.Pushed = len(plans)
	return result, nil
}

// --- Batched bootstrap ---

func executeBatched(
	ctx context.Context,
	p Params,
	plans []planner.BranchPlan,
	result Result,
) (Result, error) {
	if p.SourceService.Protocol != "v2" {
		return result, fmt.Errorf("bootstrap batching currently requires protocol v2")
	}
	if p.SourceService.V2Caps == nil || !p.SourceService.V2Caps.FetchSupports("filter") {
		return result, fmt.Errorf("bootstrap batching requires source fetch filter support")
	}

planRefs := make([]planner.DesiredRef, 0, len(plans))
	tagPlans := make([]planner.BranchPlan, 0, len(plans))
	tagDesired := make(map[plumbing.ReferenceName]gitproto.DesiredRef)
	for _, plan := range plans {
		if plan.Kind == planner.RefKindTag {
			tagPlans = append(tagPlans, plan)
			if d, ok := p.DesiredRefs[plan.TargetRef]; ok {
				tagDesired[plan.TargetRef] = gitproto.DesiredRef{
					SourceRef: d.SourceRef, TargetRef: d.TargetRef,
					SourceHash: d.SourceHash, IsTag: true,
				}
			}
			continue
		}
		if !plan.SourceRef.IsBranch() || !plan.TargetRef.IsBranch() {
			return result, fmt.Errorf("bootstrap batching currently supports branch refs and create-only tags")
		}
		planRefs = append(planRefs, p.DesiredRefs[plan.TargetRef])
	}

var batches []planner.BootstrapBatch
	if len(planRefs) > 0 {
		progressf(p.Verbose, "bootstrap-batch: planning checkpoints for %d branch ref(s)", len(planRefs))
		var err error
		batches, err = planBatches(ctx, p, planRefs)
		if err != nil {
			return result, err
		}
	}

batchLimit := p.BatchMaxPack
	if p.MaxPackBytes > 0 && (batchLimit == 0 || p.MaxPackBytes < batchLimit) {
		batchLimit = p.MaxPackBytes
	}

for _, batch := range batches {
		result.PlannedBatchCount += len(batch.Checkpoints)
		result.TempRefs = append(result.TempRefs, batch.TempRef.String())
		progressf(p.Verbose, "bootstrap-batch: branch=%s temp-ref=%s planned-batches=%d resume=%s",
			batch.Plan.TargetRef, batch.TempRef, len(batch.Checkpoints), planner.ShortHash(batch.ResumeHash))

current := batch.ResumeHash
		startIdx, err := planner.BootstrapResumeIndex(batch.Checkpoints, batch.ResumeHash)
		if err != nil {
			return result, fmt.Errorf("resume bootstrap batch for %s: %w", batch.Plan.TargetRef, err)
		}

for idx := startIdx; idx < len(batch.Checkpoints); idx++ {
			checkpoint := batch.Checkpoints[idx]
			progressf(p.Verbose, "bootstrap-batch: branch=%s batch=%d/%d from=%s to=%s",
				batch.Plan.TargetRef, idx+1, len(batch.Checkpoints),
				planner.ShortHash(current), planner.ShortHash(checkpoint))

stagePlans := []planner.BranchPlan{{
				Branch: batch.Plan.Branch, SourceRef: batch.Plan.SourceRef,
				TargetRef: batch.TempRef, SourceHash: checkpoint, TargetHash: current,
				Kind: batch.Plan.Kind, Action: planner.ActionForTargetHash(current),
				Reason: fmt.Sprintf("%s -> %s via %s", planner.ShortHash(current), planner.ShortHash(checkpoint), batch.TempRef),
			}}
			if idx == len(batch.Checkpoints)-1 {
				stagePlans = append(stagePlans, planner.BranchPlan{
					Branch: batch.Plan.Branch, SourceRef: batch.Plan.SourceRef,
					TargetRef: batch.Plan.TargetRef, SourceHash: checkpoint,
					TargetHash: plumbing.ZeroHash, Kind: batch.Plan.Kind,
					Action: planner.ActionCreate,
					Reason: fmt.Sprintf("create %s at %s", batch.Plan.TargetRef, planner.ShortHash(checkpoint)),
				})
			}

desired := singleGP(batch.Plan.SourceRef, batch.TempRef, checkpoint)
			haves := planner.SingleHaveMap(current)
			packReader, err := p.SourceService.FetchPack(ctx, p.SourceConn, desired, haves)
			if err != nil {
				return result, fmt.Errorf("fetch source batch pack for %s: %w", batch.Plan.TargetRef, err)
			}
			packReader = gitproto.LimitPackReader(packReader, batchLimit)
			cmds := gitproto.ToPushCommands(plansToPushPlans(stagePlans))
			if err := gitproto.PushPack(ctx, p.TargetConn, p.TargetAdv, cmds, packReader, p.Verbose); err != nil {
				return result, fmt.Errorf("push bootstrap batch for %s: %w", batch.Plan.TargetRef, err)
			}
			progressf(p.Verbose, "bootstrap-batch: branch=%s batch=%d/%d complete",
				batch.Plan.TargetRef, idx+1, len(batch.Checkpoints))
			current = checkpoint
			result.BatchCount++
		}

if current.IsZero() {
			return result, fmt.Errorf("bootstrap batching for %s completed with no checkpoint state", batch.Plan.TargetRef)
		}
		if batch.ResumeHash == batch.Plan.SourceHash {
			cmds := []gitproto.PushCommand{{Name: batch.Plan.TargetRef, Old: plumbing.ZeroHash, New: batch.Plan.SourceHash}}
			if err := gitproto.PushCommands(ctx, p.TargetConn, p.TargetAdv, cmds, p.Verbose); err != nil {
				return result, fmt.Errorf("resume bootstrap cutover for %s: %w", batch.Plan.TargetRef, err)
			}
		}

cmds := []gitproto.PushCommand{{Name: batch.TempRef, Old: current, Delete: true}}
		if err := gitproto.PushCommands(ctx, p.TargetConn, p.TargetAdv, cmds, p.Verbose); err != nil {
			return result, fmt.Errorf("delete bootstrap temp ref for %s: %w", batch.Plan.TargetRef, err)
		}
		progressf(p.Verbose, "bootstrap-batch: branch=%s finalized", batch.Plan.TargetRef)
	}

// Tag phase (issue #1)
	if len(tagPlans) > 0 {
		progressf(p.Verbose, "bootstrap-batch: pushing %d tag(s) after branch batches", len(tagPlans))
		tagTargetRefs := planner.CopyRefHashMap(p.TargetRefs)
		for _, batch := range batches {
			tagTargetRefs[batch.Plan.TargetRef] = batch.Plan.SourceHash
		}
		packReader, err := p.SourceService.FetchPack(ctx, p.SourceConn, tagDesired, tagTargetRefs)
		if err != nil {
			if errors.Is(err, git.NoErrAlreadyUpToDate) {
				cmds := gitproto.ToPushCommands(plansToPushPlans(tagPlans))
				if err := gitproto.PushCommands(ctx, p.TargetConn, p.TargetAdv, cmds, p.Verbose); err != nil {
					return result, fmt.Errorf("create tag refs after bootstrap: %w", err)
				}
			} else {
				return result, fmt.Errorf("fetch bootstrap tag pack: %w", err)
			}
		} else {
			packReader = gitproto.LimitPackReader(packReader, p.MaxPackBytes)
			cmds := gitproto.ToPushCommands(plansToPushPlans(tagPlans))
			if err := gitproto.PushPack(ctx, p.TargetConn, p.TargetAdv, cmds, packReader, p.Verbose); err != nil {
				return result, fmt.Errorf("push bootstrap tags: %w", err)
			}
		}
	}

result.Pushed = len(plans)
	result.Batching = true
	result.RelayMode = "bootstrap-batch"
	return result, nil
}

// --- Checkpoint planning ---

func planBatches(ctx context.Context, p Params, desired []planner.DesiredRef) ([]planner.BootstrapBatch, error) {
	out := make([]planner.BootstrapBatch, 0, len(desired))
	for _, ref := range desired {
		checkpoints, err := PlanCheckpoints(ctx, p, ref)
		if err != nil {
			return nil, err
		}
		out = append(out, planner.BootstrapBatch{
			Plan: planner.BranchPlan{
				Branch: ref.Label, SourceRef: ref.SourceRef,
				TargetRef: ref.TargetRef, SourceHash: ref.SourceHash,
				Kind: ref.Kind, Action: planner.ActionCreate,
			},
			TempRef:     planner.BootstrapTempRef(ref.TargetRef),
			ResumeHash:  p.TargetRefs[planner.BootstrapTempRef(ref.TargetRef)],
			Checkpoints: checkpoints,
		})
	}
	return out, nil
}

// PlanCheckpoints plans the checkpoint hashes for a single branch during batched bootstrap.
func PlanCheckpoints(ctx context.Context, p Params, ref planner.DesiredRef) ([]plumbing.Hash, error) {
	progressf(p.Verbose, "bootstrap-batch: fetching commit graph for %s", ref.TargetRef)
	graphStore := memory.NewStorage()
	gpRef := gitproto.DesiredRef{SourceRef: ref.SourceRef, TargetRef: ref.TargetRef, SourceHash: ref.SourceHash}
	if err := p.SourceService.FetchCommitGraph(ctx, graphStore, p.SourceConn, gpRef); err != nil {
		return nil, fmt.Errorf("fetch bootstrap planning graph for %s: %w", ref.TargetRef, err)
	}
	chain, err := planner.FirstParentChain(graphStore, ref.SourceHash)
	if err != nil {
		return nil, fmt.Errorf("walk first-parent chain for %s: %w", ref.TargetRef, err)
	}
	if len(chain) == 0 {
		return nil, fmt.Errorf("empty first-parent chain for %s", ref.TargetRef)
	}

// Issue #14: Use a commit-count heuristic for the initial span estimate
	// to reduce expensive fetch-and-discard probes. Typical compressed commit
	// + tree overhead averages ~2-5 KiB per commit in a mature repo.
	const avgBytesPerCommit = 4096
	initialSpan := 0
	if p.BatchMaxPack > 0 {
		initialSpan = int(p.BatchMaxPack / avgBytesPerCommit)
		if initialSpan > len(chain) {
			initialSpan = len(chain)
		}
		if initialSpan < 1 {
			initialSpan = 1
		}
	}

checkpoints := make([]plumbing.Hash, 0, len(chain))
	prevIdx := -1
	prevHash := plumbing.ZeroHash
	prevSpan := initialSpan
	for prevIdx < len(chain)-1 {
		bestIdx, err := planner.SampledCheckpointUnderLimit(chain, prevIdx, prevSpan, func(idx int) (bool, error) {
			tooLarge, err := packExceedsLimit(ctx, p, ref, chain[idx], prevHash, p.BatchMaxPack)
			if err != nil {
				return false, fmt.Errorf("measure bootstrap batch for %s at %s: %w", ref.TargetRef, planner.ShortHash(chain[idx]), err)
			}
			return tooLarge, nil
		})
		if err != nil {
			return nil, err
		}
		if bestIdx <= prevIdx {
			return nil, fmt.Errorf("could not find bootstrap checkpoint for %s under batch-max-pack-bytes=%d", ref.TargetRef, p.BatchMaxPack)
		}
		prevSpan = bestIdx - prevIdx
		prevIdx = bestIdx
		prevHash = chain[bestIdx]
		checkpoints = append(checkpoints, prevHash)
		progressf(p.Verbose, "bootstrap-batch: branch=%s planned-checkpoint=%s selected=%d chain-len=%d",
			ref.TargetRef, planner.ShortHash(prevHash), len(checkpoints), len(chain))
	}
	return checkpoints, nil
}

func packExceedsLimit(ctx context.Context, p Params, ref planner.DesiredRef, want, have plumbing.Hash, limit int64) (bool, error) {
	desired := singleGP(ref.SourceRef, ref.TargetRef, want)
	haves := planner.SingleHaveMap(have)
	packReader, err := p.SourceService.FetchPack(ctx, p.SourceConn, desired, haves)
	if err != nil {
		return false, err
	}
	defer packReader.Close()
	_, err = io.Copy(io.Discard, gitproto.LimitPackReader(packReader, limit))
	if err == nil {
		return false, nil
	}
	if strings.Contains(err.Error(), "source pack exceeded max-pack-bytes limit") {
		return true, nil
	}
	return false, err
}

// --- GitHub preflight ---

func githubBatchLimit(ctx context.Context, p Params) (int64, bool) {
	if p.BatchMaxPack > 0 || p.SourceConn == nil || p.SourceConn.Endpoint == nil {
		return 0, false
	}
	if p.SourceService == nil || p.SourceService.Protocol != "v2" {
		return 0, false
	}
	if p.SourceService.V2Caps == nil || !p.SourceService.V2Caps.FetchSupports("filter") {
		return 0, false
	}
	repoSizeKB, ok := lookupGitHubRepoSizeKB(ctx, p.SourceConn)
	if !ok || repoSizeKB < githubLargeRepoThresholdKB {
		return 0, false
	}
	limit := int64(defaultAutoBatchMaxPackBytes)
	if p.MaxPackBytes > 0 && p.MaxPackBytes < limit {
		limit = p.MaxPackBytes
	}
	if limit <= 0 {
		return 0, false
	}
	return limit, true
}

func lookupGitHubRepoSizeKB(ctx context.Context, conn *gitproto.Conn) (int64, bool) {
	owner, repo, ok := GitHubOwnerRepo(conn)
	if !ok {
		return 0, false
	}
	apiURL := strings.TrimRight(GitHubRepoAPIBaseURL, "/") + "/repos/" + owner + "/" + repo
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, apiURL, nil)
	if err != nil {
		return 0, false
	}
	req.Header.Set("Accept", "application/vnd.github+json")
	req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
	req.Header.Set("User-Agent", capability.DefaultAgent())
	req.Header.Set(gitproto.StatsPhaseHeader, "github repo metadata")
	resp, err := conn.HTTP.Do(req)
	if err != nil {
		return 0, false
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return 0, false
	}
	var payload struct{ Size int64 `json:"size"` }
	if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil || payload.Size <= 0 {
		return 0, false
	}
	return payload.Size, true
}

// GitHubOwnerRepo extracts the owner/repo from a GitHub endpoint.
func GitHubOwnerRepo(conn *gitproto.Conn) (string, string, bool) {
	if conn == nil || conn.Endpoint == nil {
		return "", "", false
	}
	ep := conn.Endpoint
	if ep.Protocol != "http" && ep.Protocol != "https" {
		return "", "", false
	}
	if !strings.EqualFold(ep.Host, "github.com") {
		return "", "", false
	}
	path := strings.TrimSuffix(strings.Trim(ep.Path, "/"), ".git")
	parts := strings.Split(path, "/")
	if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
		return "", "", false
	}
	return parts[0], parts[1], true
}

func autoBatchMaxPackBytes(p Params, err error) (int64, bool) {
	if p.BatchMaxPack > 0 || !isTargetBodyLimitError(err) {
		return 0, false
	}
	if p.SourceService == nil || p.SourceService.Protocol != "v2" {
		return 0, false
	}
	if p.SourceService.V2Caps == nil || !p.SourceService.V2Caps.FetchSupports("filter") {
		return 0, false
	}
	limit := int64(defaultAutoBatchMaxPackBytes)
	if targetLimit := targetBodyLimit(err); targetLimit > 0 {
		derived := targetLimit / 2
		if derived <= 0 {
			derived = targetLimit
		}
		if derived < limit {
			limit = derived
		}
	}
	if p.MaxPackBytes > 0 && p.MaxPackBytes < limit {
		limit = p.MaxPackBytes
	}
	if limit <= 0 {
		return 0, false
	}
	return limit, true
}

func isTargetBodyLimitError(err error) bool {
	if err == nil {
		return false
	}
	msg := strings.ToLower(err.Error())
	return strings.Contains(msg, "body exceeded size limit") ||
		(strings.Contains(msg, "request body") && strings.Contains(msg, "too large")) ||
		(strings.Contains(msg, "payload") && strings.Contains(msg, "too large")) ||
		strings.Contains(msg, "http 413")
}

func targetBodyLimit(err error) int64 {
	if err == nil {
		return 0
	}
	matches := bodyLimitPattern.FindStringSubmatch(strings.ToLower(err.Error()))
	if len(matches) != 2 {
		return 0
	}
	limit, parseErr := strconv.ParseInt(matches[1], 10, 64)
	if parseErr != nil {
		return 0
	}
	return limit
}

// --- Shared helpers ---

func toGP(desired map[plumbing.ReferenceName]planner.DesiredRef) map[plumbing.ReferenceName]gitproto.DesiredRef {
	out := make(map[plumbing.ReferenceName]gitproto.DesiredRef, len(desired))
	for k, v := range desired {
		out[k] = gitproto.DesiredRef{
			SourceRef: v.SourceRef, TargetRef: v.TargetRef,
			SourceHash: v.SourceHash, IsTag: v.Kind == planner.RefKindTag,
		}
	}
	return out
}

func singleGP(sourceRef, targetRef plumbing.ReferenceName, hash plumbing.Hash) map[plumbing.ReferenceName]gitproto.DesiredRef {
	return map[plumbing.ReferenceName]gitproto.DesiredRef{
		targetRef: {SourceRef: sourceRef, TargetRef: targetRef, SourceHash: hash},
	}
}

func plansToPushPlans(plans []planner.BranchPlan) []gitproto.PushPlan {
	out := make([]gitproto.PushPlan, len(plans))
	for i, p := range plans {
		out[i] = gitproto.PushPlan{
			TargetRef: p.TargetRef, TargetHash: p.TargetHash, SourceHash: p.SourceHash,
			Delete: p.Action == planner.ActionDelete,
		}
	}
	return out
}

func progressf(verbose bool, format string, args ...any) {
	if !verbose {
		return
	}
	fmt.Fprintf(os.Stderr, "[git-sync] %s\n", fmt.Sprintf(format, args...))
}
```

Ainternal/strategy/bootstrap/bootstrap.go+528

```
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

package bootstrap

import (
	"errors"
	"testing"
)

func TestIsTargetBodyLimitError(t *testing.T) {
	tests := []struct {
		name string
		err  error
		want bool
	}{
		{
			name: "nil error",
			err:  nil,
			want: false,
		},
		{
			name: "body exceeded size limit",
			err:  errors.New("body exceeded size limit 1048576"),
			want: true,
		},
		{
			name: "case insensitive body exceeded",
			err:  errors.New("Body Exceeded Size Limit 999"),
			want: true,
		},
		{
			name: "request body too large",
			err:  errors.New("request body is too large"),
			want: true,
		},
		{
			name: "payload too large",
			err:  errors.New("payload is too large for this endpoint"),
			want: true,
		},
		{
			name: "HTTP 413",
			err:  errors.New("server returned HTTP 413"),
			want: true,
		},
		{
			name: "unrelated error",
			err:  errors.New("connection refused"),
			want: false,
		},
		{
			name: "partial match body without too large",
			err:  errors.New("request body is fine"),
			want: false,
		},
	}

for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := isTargetBodyLimitError(tt.err)
			if got != tt.want {
				t.Errorf("isTargetBodyLimitError(%v) = %v, want %v", tt.err, got, tt.want)
			}
		})
	}
}

func TestTargetBodyLimit(t *testing.T) {
	tests := []struct {
		name string
		err  error
		want int64
	}{
		{
			name: "nil error",
			err:  nil,
			want: 0,
		},
		{
			name: "extracts numeric limit from error",
			err:  errors.New("body exceeded size limit 1048576"),
			want: 1048576,
		},
		{
			name: "no limit in error message",
			err:  errors.New("connection refused"),
			want: 0,
		},
		{
			name: "limit with surrounding text",
			err:  errors.New("push target refs: body exceeded size limit 536870912 bytes"),
			want: 536870912,
		},
		{
			name: "case insensitive match",
			err:  errors.New("Body Exceeded Size Limit 2097152"),
			want: 2097152,
		},
		{
			name: "no number after pattern",
			err:  errors.New("body exceeded size limit"),
			want: 0,
		},
	}

for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := targetBodyLimit(tt.err)
			if got != tt.want {
				t.Errorf("targetBodyLimit(%v) = %d, want %d", tt.err, got, tt.want)
			}
		})
	}
}
```

Ainternal/strategy/bootstrap/bootstrap\_test.go+112

```
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

// Package incremental implements the incremental relay strategy for git-sync.
// This fast-path streams a pack from source directly to target when all updates
// are fast-forward branch updates or new tag creates.
package incremental

import (
	"context"
	"fmt"

"github.com/go-git/go-git/v5/plumbing"
	"github.com/go-git/go-git/v5/plumbing/protocol/packp"

"github.com/soph/git-sync/internal/gitproto"
	"github.com/soph/git-sync/internal/planner"
)

// Params holds the inputs for an incremental relay execution.
type Params struct {
	SourceConn    *gitproto.Conn
	TargetConn    *gitproto.Conn
	SourceService *gitproto.RefService
	TargetAdv     *packp.AdvRefs
	DesiredRefs   map[plumbing.ReferenceName]planner.DesiredRef
	TargetRefs    map[plumbing.ReferenceName]plumbing.Hash
	PushPlans     []planner.BranchPlan
	MaxPackBytes  int64
	Verbose       bool
}

// Result holds the outcome of an incremental relay.
type Result struct {
	Relay       bool
	RelayMode   string
	RelayReason string
}

// Execute attempts the incremental relay strategy. Returns (result, nil) on
// success, or (zero, nil) if the strategy is not applicable. Errors indicate
// a relay was attempted but failed.
func Execute(ctx context.Context, p Params, cfg planner.PlanConfig) (Result, error) {
	if ok, reason := planner.CanIncrementalRelay(cfg.Force, cfg.Prune, false, p.PushPlans, p.TargetAdv); ok {
		desired := toGP(planner.DesiredSubset(p.DesiredRefs, p.PushPlans))
		packReader, err := p.SourceService.FetchPack(ctx, p.SourceConn, desired, p.TargetRefs)
		if err != nil {
			return Result{}, fmt.Errorf("fetch source pack: %w", err)
		}
		packReader = gitproto.LimitPackReader(packReader, p.MaxPackBytes)
		cmds := gitproto.ToPushCommands(plansToPushPlans(p.PushPlans))
		if err := gitproto.PushPack(ctx, p.TargetConn, p.TargetAdv, cmds, packReader, p.Verbose); err != nil {
			return Result{}, fmt.Errorf("push target refs: %w", err)
		}
		return Result{Relay: true, RelayMode: "incremental", RelayReason: reason}, nil
	}

if ok, reason := planner.CanFullTagCreateRelay(p.PushPlans); ok {
		desired := toGP(planner.DesiredSubset(p.DesiredRefs, p.PushPlans))
		packReader, err := p.SourceService.FetchPack(ctx, p.SourceConn, desired, nil)
		if err != nil {
			return Result{}, fmt.Errorf("fetch source tag pack: %w", err)
		}
		packReader = gitproto.LimitPackReader(packReader, p.MaxPackBytes)
		cmds := gitproto.ToPushCommands(plansToPushPlans(p.PushPlans))
		if err := gitproto.PushPack(ctx, p.TargetConn, p.TargetAdv, cmds, packReader, p.Verbose); err != nil {
			return Result{}, fmt.Errorf("push target refs: %w", err)
		}
		return Result{Relay: true, RelayMode: "incremental", RelayReason: reason}, nil
	}

return Result{}, nil
}

func plansToPushPlans(plans []planner.BranchPlan) []gitproto.PushPlan {
	out := make([]gitproto.PushPlan, len(plans))
	for i, p := range plans {
		out[i] = gitproto.PushPlan{
			TargetRef: p.TargetRef, TargetHash: p.TargetHash, SourceHash: p.SourceHash,
			Delete: p.Action == planner.ActionDelete,
		}
	}
	return out
}
```

Ainternal/strategy/incremental/incremental.go+92

```
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

// Package materialized implements the materialized fallback push strategy.
// This path fetches objects into local memory, then encodes and pushes them
// to the target. Used when relay is not safe.
package materialized

import (
	"context"
	"fmt"

git "github.com/go-git/go-git/v5"
	"github.com/go-git/go-git/v5/plumbing"
	"github.com/go-git/go-git/v5/plumbing/protocol/packp"
	"github.com/go-git/go-git/v5/plumbing/storer"

"github.com/soph/git-sync/internal/gitproto"
	"github.com/soph/git-sync/internal/planner"
)

// Params holds the inputs for a materialized push.
type Params struct {
	Store         storer.Storer
	SourceConn    *gitproto.Conn
	SourceService *gitproto.RefService
	TargetConn    *gitproto.Conn
	TargetAdv     *packp.AdvRefs
	DesiredRefs   map[plumbing.ReferenceName]planner.DesiredRef
	TargetRefs    map[plumbing.ReferenceName]plumbing.Hash
	PushPlans     []planner.BranchPlan
	Verbose       bool
}

// MaxMaterializedObjects is the safety limit for the materialized fallback path.
// Beyond this count, the in-memory object store would consume excessive memory.
// Fail early rather than OOM (issue #15).
const MaxMaterializedObjects = 500_000

// Execute runs the materialized fallback: ensures tag objects are local,
// computes the object closure, and pushes to the target.
func Execute(ctx context.Context, p Params) error {
	if len(p.PushPlans) == 0 {
		return nil
	}

// Ensure tag objects are fetched locally
	if err := ensureTagObjects(ctx, p); err != nil {
		return fmt.Errorf("prepare local objects for push: %w", err)
	}

objects := make([]plumbing.Hash, 0, len(p.PushPlans))
	for _, plan := range p.PushPlans {
		if plan.Action == planner.ActionCreate || plan.Action == planner.ActionUpdate {
			objects = append(objects, plan.SourceHash)
		}
	}
	hashes, err := planner.ObjectsToPush(p.Store, objects, p.TargetRefs)
	if err != nil {
		return fmt.Errorf("compute objects to push: %w", err)
	}

// Issue #15: guard against unbounded memory usage on large non-relay syncs.
	if len(hashes) > MaxMaterializedObjects {
		return fmt.Errorf(
			"materialized push requires %d objects (limit %d); use bootstrap for large initial syncs",
			len(hashes), MaxMaterializedObjects,
		)
	}

cmds := gitproto.ToPushCommands(plansToPushPlans(p.PushPlans))
	if err := gitproto.PushObjects(ctx, p.TargetConn, p.TargetAdv, cmds, p.Store, hashes, p.Verbose); err != nil {
		return fmt.Errorf("push target refs: %w", err)
	}
	return nil
}

func ensureTagObjects(ctx context.Context, p Params) error {
	tagDesired := make(map[plumbing.ReferenceName]gitproto.DesiredRef)
	for _, plan := range p.PushPlans {
		if plan.Kind != planner.RefKindTag {
			continue
		}
		if d, ok := p.DesiredRefs[plan.TargetRef]; ok {
			tagDesired[plan.TargetRef] = gitproto.DesiredRef{
				SourceRef: d.SourceRef, TargetRef: d.TargetRef,
				SourceHash: d.SourceHash, IsTag: true,
			}
		}
	}
	if len(tagDesired) == 0 {
		return nil
	}
	err := p.SourceService.FetchToStore(ctx, p.Store, p.SourceConn, tagDesired, nil)
	if err != nil && err != git.NoErrAlreadyUpToDate {
		return err
	}
	return nil
}

Ainternal/strategy/materialized/materialized.go+107

```
2 unmodified lines

3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2 unmodified lines

23
24
25
22
23
24
25
26
26
27
28
29
30
31
32
31
33
34
35
36
1 unmodified line

38
39
40
39
41
42
41
43
44
45
46
47
48
49
48
49
50
51
52
53
54
52
55
56
54
57
58
56
57
59
60
59
61
62
61
63
64
63
65
66
67
66
68
69
70
71
8 unmodified lines

80
81
82
81
83
84
85
86
87
83
88
89
90
91
92
93
87
88
89
90
91
94
95
96
97
98
99
100
96
101
102
103
104
105
101
106
107
103
108
109
110
111
26 unmodified lines

138
139
140
136
141
142
143
144
145
138
146
147
148
149
141
150
151
152
153
145
154
155
156
157
158
150
159
160
152
161
162
163
164
165
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
171
172
173
174
3 unmodified lines

178
179
180
181
182
183
184

2 unmodified lines

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"testing"
	"time"

"github.com/go-git/go-git/v5/plumbing/transport"
	transporthttp "github.com/go-git/go-git/v5/plumbing/transport/http"

"github.com/soph/git-sync/internal/auth"
)

func TestResolveAuthMethodPrefersExplicitToken(t *testing.T) {
2 unmodified lines

t.Fatalf("new endpoint: %v", err)
	}

originalFill := gitCredentialFillCommand
	t.Cleanup(func() {
		gitCredentialFillCommand = originalFill
	})
	gitCredentialFillCommand = func(ctx context.Context, input string) ([]byte, error) {
	originalFill := auth.GitCredentialFillCommand
	t.Cleanup(func() { auth.GitCredentialFillCommand = originalFill })
	auth.GitCredentialFillCommand = func(ctx context.Context, input string) ([]byte, error) {
		t.Fatalf("unexpected git credential fill call with input %q", input)
		return nil, nil
	}

auth, err := resolveAuthMethod(Endpoint{
	resolved, err := auth.Resolve(auth.Endpoint{
		Username: "git",
		Token:    "explicit-token",
	}, ep)
1 unmodified line

t.Fatalf("resolve auth: %v", err)
	}

basic, ok := auth.(*transporthttp.BasicAuth)
	basic, ok := resolved.(*transporthttp.BasicAuth)
	if !ok {
		t.Fatalf("expected basic auth, got %T", auth)
		t.Fatalf("expected basic auth, got %T", resolved)
	}
	if basic.Username != "git" || basic.Password != "explicit-token" {
		t.Fatalf("unexpected auth: %+v", basic)
	}
}

func TestNewTransportConnSkipTLSVerify(t *testing.T) {
	conn, err := newTransportConn(Endpoint{
func TestNewConnSkipTLSVerify(t *testing.T) {
	stats := newStats(false)
	conn, err := newConn(Endpoint{
		URL:           "https://example.com/repo.git",
		SkipTLSVerify: true,
	}, "source", newStats(false))
	}, "source", stats)
	if err != nil {
		t.Fatalf("new transport conn: %v", err)
		t.Fatalf("new conn: %v", err)
	}

roundTripper, ok := conn.http.Transport.(*countingRoundTripper)
	rt, ok := conn.HTTP.Transport.(*countingRoundTripper)
	if !ok {
		t.Fatalf("expected countingRoundTripper, got %T", conn.http.Transport)
		t.Fatalf("expected countingRoundTripper, got %T", conn.HTTP.Transport)
	}
	base, ok := roundTripper.base.(*http.Transport)
	base, ok := rt.base.(*http.Transport)
	if !ok {
		t.Fatalf("expected *http.Transport base, got %T", roundTripper.base)
		t.Fatalf("expected *http.Transport base, got %T", rt.base)
	}
	if base.TLSClientConfig == nil || !base.TLSClientConfig.InsecureSkipVerify {
		t.Fatalf("expected InsecureSkipVerify transport, got %#v", base.TLSClientConfig)
		t.Fatalf("expected InsecureSkipVerify transport")
	}
}

8 unmodified lines

if err != nil {
		t.Fatalf("new endpoint: %v", err)
	}
	credHost := endpointCredentialHost(ep)
	credHost := ep.Host
	if ep.Port > 0 {
		credHost = ep.Host + ":8080"
	}
	writeEntireDBHostsFile(t, configDir, credHost, "test-user")
	if err := writeEntireDBStoredToken("entire:"+credHost, "test-user", "stored-token"); err != nil {
	// Store token with a future expiration so it's not treated as expired (issue #7).
	futureExpiry := time.Now().Unix() + 3600
	if err := auth.WriteStoredToken("entire:"+credHost, "test-user", fmt.Sprintf("stored-token|%d", futureExpiry)); err != nil {
		t.Fatalf("write token: %v", err)
	}

auth, err := resolveAuthMethod(Endpoint{}, ep)
	resolved, err := auth.Resolve(auth.Endpoint{}, ep)
	if err != nil {
		t.Fatalf("resolve auth: %v", err)
	}

basic, ok := auth.(*transporthttp.BasicAuth)
	basic, ok := resolved.(*transporthttp.BasicAuth)
	if !ok {
		t.Fatalf("expected basic auth, got %T", auth)
		t.Fatalf("expected basic auth, got %T", resolved)
	}
	if basic.Username != "git" || basic.Password != "stored-token" {
		t.Fatalf("unexpected auth: %+v", basic)
26 unmodified lines

if err != nil {
		t.Fatalf("new endpoint: %v", err)
	}
	credHost := endpointCredentialHost(ep)
	credHost := ep.Host
	if ep.Port > 0 {
		credHost = ep.Host + ":" + itoa(ep.Port)
	}
	writeEntireDBHostsFile(t, configDir, credHost, "test-user")
	if err := writeEntireDBStoredToken("entire:"+credHost, "test-user", encodeTokenWithExpiration("expired-token", -3600)); err != nil {
	// Expired token: expiration in the past
	if err := auth.WriteStoredToken("entire:"+credHost, "test-user", "expired-token|1"); err != nil {
		t.Fatalf("write expired token: %v", err)
	}
	if err := writeEntireDBStoredToken("entire:"+credHost+":refresh", "test-user", "refresh-token"); err != nil {
	if err := auth.WriteStoredToken("entire:"+credHost+":refresh", "test-user", "refresh-token"); err != nil {
		t.Fatalf("write refresh token: %v", err)
	}

auth, err := resolveAuthMethod(Endpoint{SkipTLSVerify: true}, ep)
	resolved, err := auth.Resolve(auth.Endpoint{SkipTLSVerify: true}, ep)
	if err != nil {
		t.Fatalf("resolve auth: %v", err)
	}

basic, ok := auth.(*transporthttp.BasicAuth)
	basic, ok := resolved.(*transporthttp.BasicAuth)
	if !ok {
		t.Fatalf("expected basic auth, got %T", auth)
		t.Fatalf("expected basic auth, got %T", resolved)
	}
	if basic.Password != "new-token" {
		t.Fatalf("unexpected password: %q", basic.Password)
	}

stored, err := readEntireDBStoredToken("entire:"+credHost, "test-user")
	if err != nil {
		t.Fatalf("read stored token: %v", err)
	}
	token, _ := decodeTokenWithExpiration(stored)
	if token != "new-token" {
		t.Fatalf("unexpected refreshed token: %q", token)
	}
}

func writeEntireDBHostsFile(t *testing.T, configDir, host, username string) {
	t.Helper()
	hosts := map[string]map[string]any{
		host: {
			"activeUser": username,
			"users":      []string{username},
		},
		host: {"activeUser": username, "users": []string{username}},
	}
	data, err := json.Marshal(hosts)
	if err != nil {
3 unmodified lines

t.Fatalf("write hosts: %v", err)
	}
}

func itoa(n int) string {
	return fmt.Sprintf("%d", n)
}
```

Minternal/syncer/auth\_test.go+48/-47

```
15 unmodified lines

16
17
18
19
20
21
22
23
24
438 unmodified lines

463
464
465
463
466
467
468
469
470
468
471
472
473
474
40 unmodified lines

515
516
517
515
518
519
520
521
519
522
523
524
525
523
526
527
528
529
530
531
532
533
528
534
535
536
537
538
539
540
541
1 unmodified line

543
544
545
536
546
547
548
549
77 unmodified lines

627
628
629
620
630
631
632
633

15 unmodified lines

"testing"

"github.com/go-git/go-git/v5/plumbing"
	"github.com/soph/git-sync/internal/gitproto"
	"github.com/soph/git-sync/internal/planner"
	bstrap "github.com/soph/git-sync/internal/strategy/bootstrap"
)

const gitHTTPBackendEnv = "GITSYNC_E2E_GIT_HTTP_BACKEND"
438 unmodified lines

if result.PlannedBatchCount != result.BatchCount {
		t.Fatalf("expected fresh batched bootstrap to complete all planned batches, got %+v", result)
	}
	if len(result.TempRefs) != 1 || result.TempRefs[0] != bootstrapTempRef(plumbing.NewBranchReferenceName(testBranch)).String() {
	if len(result.TempRefs) != 1 || result.TempRefs[0] != planner.BootstrapTempRef(plumbing.NewBranchReferenceName(testBranch)).String() {
		t.Fatalf("unexpected temp refs in batched bootstrap result: %+v", result)
	}

assertGitRefEqual(t, sourceBare, targetBare, plumbing.NewBranchReferenceName(testBranch))
	assertGitRefAbsent(t, targetBare, bootstrapTempRef(plumbing.NewBranchReferenceName(testBranch)))
	assertGitRefAbsent(t, targetBare, planner.BootstrapTempRef(plumbing.NewBranchReferenceName(testBranch)))
}

func TestBootstrap_GitHTTPBackendBatchedBranchResume(t *testing.T) {
40 unmodified lines

}

stats := newStats(false)
	sourceConn, err := newTransportConn(cfg.Source, "source", stats)
	sourceConn, err := newConn(cfg.Source, "source", stats)
	if err != nil {
		t.Fatalf("create source transport: %v", err)
	}
	sourceRefs, sourceService, err := listSourceRefs(context.Background(), sourceConn, cfg)
	sourceRefs, sourceService, err := gitproto.ListSourceRefs(context.Background(), sourceConn, cfg.ProtocolMode, planner.RefPrefixes(cfg.Mappings, cfg.IncludeTags))
	if err != nil {
		t.Fatalf("list source refs: %v", err)
	}
	desired, _, err := buildDesiredRefs(refHashMap(sourceRefs), cfg)
	desired, _, err := planner.BuildDesiredRefs(gitproto.RefHashMap(sourceRefs), planner.PlanConfig{
		Branches: cfg.Branches, Mappings: cfg.Mappings, IncludeTags: cfg.IncludeTags,
		Force: cfg.Force, Prune: cfg.Prune,
	})
	if err != nil {
		t.Fatalf("build desired refs: %v", err)
	}
	ref := desired[plumbing.NewBranchReferenceName(testBranch)]
	checkpoints, err := planBootstrapBranchCheckpoints(context.Background(), cfg, sourceConn, sourceService, ref)
	bParams := bstrap.Params{
		SourceConn: sourceConn, SourceService: sourceService,
		BatchMaxPack: cfg.BatchMaxPackBytes, Verbose: cfg.Verbose,
	}
	checkpoints, err := bstrap.PlanCheckpoints(context.Background(), bParams, ref)
	if err != nil {
		t.Fatalf("plan checkpoints: %v", err)
	}
1 unmodified line

t.Fatalf("expected multiple checkpoints for resume test, got %v", checkpoints)
	}

tempRef := bootstrapTempRef(plumbing.NewBranchReferenceName(testBranch))
	tempRef := planner.BootstrapTempRef(plumbing.NewBranchReferenceName(testBranch))
	runGit(t, worktree, "push", targetBare, checkpoints[0].String()+":"+tempRef.String())

result, err := Bootstrap(context.Background(), cfg)
77 unmodified lines

assertGitRefEqual(t, sourceBare, targetBare, plumbing.NewBranchReferenceName(testBranch))
	assertGitRefEqual(t, sourceBare, targetBare, plumbing.NewTagReferenceName("v1"))
	assertGitRefAbsent(t, targetBare, bootstrapTempRef(plumbing.NewBranchReferenceName(testBranch)))
	assertGitRefAbsent(t, targetBare, planner.BootstrapTempRef(plumbing.NewBranchReferenceName(testBranch)))
}

type gitHTTPBackendServer struct {
```

Minternal/syncer/git\_http\_backend\_test.go+18/-8

```
28 unmodified lines

29
30
31
32
33
34
35
36
37
461 unmodified lines

499
500
501
499
502
503
501
504
505
503
506
507
508
509
332 unmodified lines

842
843
844
842
845
846
847
848
710 unmodified lines

1559
1560
1561
1559
1562
1563
1564
1565
3 unmodified lines

1569
1570
1571
1569
1572
1573
1571
1574
1575
1573
1576
1577
1578
1579

28 unmodified lines

transporthttp "github.com/go-git/go-git/v5/plumbing/transport/http"
	transportserver "github.com/go-git/go-git/v5/plumbing/transport/server"
	"github.com/go-git/go-git/v5/storage/memory"
	"github.com/soph/git-sync/internal/auth"
	"github.com/soph/git-sync/internal/gitproto"
	"github.com/soph/git-sync/internal/planner"
)

const testBranch = "master"
461 unmodified lines

defer sourceServer.Close()
	defer targetServer.Close()

originalFill := gitCredentialFillCommand
	originalFill := auth.GitCredentialFillCommand
	t.Cleanup(func() {
		gitCredentialFillCommand = originalFill
		auth.GitCredentialFillCommand = originalFill
	})
	gitCredentialFillCommand = func(ctx context.Context, input string) ([]byte, error) {
	auth.GitCredentialFillCommand = func(ctx context.Context, input string) ([]byte, error) {
		if !strings.Contains(input, "protocol=http\n") {
			t.Fatalf("expected protocol in credential input, got %q", input)
		}
332 unmodified lines

if err != nil {
		t.Fatalf("source head: %v", err)
	}
	chain, err := firstParentChain(sourceRepo, head.Hash())
	chain, err := planner.FirstParentChain(sourceRepo.Storer, head.Hash())
	if err != nil {
		t.Fatalf("build commit chain: %v", err)
	}
710 unmodified lines

}

func decodeV2TestCommandRequest(body []byte) (v2TestCommandRequest, error) {
	reader := newPacketReader(bytes.NewReader(body))
	reader := gitproto.NewPacketReader(bytes.NewReader(body))
	req := v2TestCommandRequest{}
	inArgs := false

3 unmodified lines

return req, err
		}
		switch kind {
		case packetTypeFlush:
		case gitproto.PacketFlush:
			return req, nil
		case packetTypeDelim:
		case gitproto.PacketDelim:
			inArgs = true
		case packetTypeData:
		case gitproto.PacketData:
			line := strings.TrimSuffix(string(payload), "\n")
			if strings.HasPrefix(line, "command=") {
				req.Command = strings.TrimPrefix(line, "command=")
```

Minternal/syncer/integration\_test.go+11/-8

```
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

package syncer

import (
	"runtime"
	"sync"
	"time"
)

// Measurement holds performance measurement data.
type Measurement struct {
	Enabled            bool   `json:"enabled"`
	ElapsedMillis      int64  `json:"elapsed_millis"`
	PeakAllocBytes     uint64 `json:"peak_alloc_bytes"`
	PeakHeapInuseBytes uint64 `json:"peak_heap_inuse_bytes"`
	TotalAllocBytes    uint64 `json:"total_alloc_bytes"`
	GCCount            uint32 `json:"gc_count"`
}

func startMeasurement(enabled bool) func() Measurement {
	if !enabled {
		return func() Measurement { return Measurement{} }
	}

start := time.Now()
	var startStats runtime.MemStats
	runtime.ReadMemStats(&startStats)

done := make(chan struct{})
	var (
		mu            sync.Mutex
		peakAlloc     = startStats.Alloc
		peakHeapInuse = startStats.HeapInuse
		result        Measurement
	)

go func() {
		ticker := time.NewTicker(200 * time.Millisecond)
		defer ticker.Stop()
		for {
			select {
			case <-done:
				return
			case <-ticker.C:
				var current runtime.MemStats
				runtime.ReadMemStats(&current)
				mu.Lock()
				if current.Alloc > peakAlloc {
					peakAlloc = current.Alloc
				}
				if current.HeapInuse > peakHeapInuse {
					peakHeapInuse = current.HeapInuse
				}
				mu.Unlock()
			}
		}
	}()

var once sync.Once
	return func() Measurement {
		once.Do(func() {
			close(done)
			var endStats runtime.MemStats
			runtime.ReadMemStats(&endStats)
			mu.Lock()
			if endStats.Alloc > peakAlloc {
				peakAlloc = endStats.Alloc
			}
			if endStats.HeapInuse > peakHeapInuse {
				peakHeapInuse = endStats.HeapInuse
			}
			result = Measurement{
				Enabled:            true,
				ElapsedMillis:      time.Since(start).Milliseconds(),
				PeakAllocBytes:     peakAlloc,
				PeakHeapInuseBytes: peakHeapInuse,
				TotalAllocBytes:    endStats.TotalAlloc - startStats.TotalAlloc,
				GCCount:            endStats.NumGC - startStats.NumGC,
			}
			mu.Unlock()
		})
		return result
	}
}
```

Ainternal/syncer/measurement.go+83

package syncer

import (
	"bufio"
	"bytes"
	"context"
	"errors"
	"fmt"
	"io"
	"net/http"
	"sort"
	"strings"

git "github.com/go-git/go-git/v5"
	"github.com/go-git/go-git/v5/plumbing"
	"github.com/go-git/go-git/v5/plumbing/format/packfile"
	"github.com/go-git/go-git/v5/plumbing/format/pktline"
	"github.com/go-git/go-git/v5/plumbing/protocol/packp"
	"github.com/go-git/go-git/v5/plumbing/protocol/packp/capability"
	"github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband"
	"github.com/go-git/go-git/v5/plumbing/transport"
	transporthttp "github.com/go-git/go-git/v5/plumbing/transport/http"
	"github.com/go-git/go-git/v5/utils/ioutil"
)

const (
	delimPkt       = "0001"
	responseEndPkt = "0002"
	statsPhaseHdr  = "X-Git-Sync-Stats-Phase"
)

type packetType int

const (
	packetTypeData packetType = iota
	packetTypeFlush
	packetTypeDelim
	packetTypeResponseEnd
)

type v2CapabilityAdvertisement struct {
	Capabilities map[string]string
}

func (a *v2CapabilityAdvertisement) Supports(name string) bool {
	if a == nil {
		return false
	}
	_, ok := a.Capabilities[name]
	return ok
}

func (a *v2CapabilityAdvertisement) Value(name string) string {
	if a == nil {
		return ""
	}
	return a.Capabilities[name]
}

type packetReader struct {
	r *bufio.Reader
}

func newPacketReader(r io.Reader) *packetReader {
	if br, ok := r.(*bufio.Reader); ok {
		return &packetReader{r: br}
	}
	return &packetReader{r: bufio.NewReader(r)}
}

func (r *packetReader) Reader() *bufio.Reader {
	return r.r
}

func (r *packetReader) ReadPacket() (packetType, []byte, error) {
	header := make([]byte, 4)
	if _, err := io.ReadFull(r.r, header); err != nil {
		return packetTypeData, nil, err
	}

switch string(header) {
	case "0000":
		return packetTypeFlush, nil, nil
	case delimPkt:
		return packetTypeDelim, nil, nil
	case responseEndPkt:
		return packetTypeResponseEnd, nil, nil
	}

var headerArr [4]byte
	copy(headerArr[:], header)
	n, err := pktlineLength(headerArr)
	if err != nil {
		return packetTypeData, nil, err
	}
	if n <= 4 {
		return packetTypeData, nil, pktline.ErrInvalidPktLen
	}

payload := make([]byte, n-4)
	if _, err := io.ReadFull(r.r, payload); err != nil {
		return packetTypeData, nil, err
	}
	return packetTypeData, payload, nil
}

func pktlineLength(header [4]byte) (int, error) {
	var n int
	for _, b := range header {
		value, err := asciiHexToByte(b)
		if err != nil {
			return 0, pktline.ErrInvalidPktLen
		}
		n = 16*n + int(value)
	}
	return n, nil
}

func asciiHexToByte(b byte) (byte, error) {
	switch {
	case b >= '0' && b <= '9':
		return b - '0', nil
	case b >= 'a' && b <= 'f':
		return b - 'a' + 10, nil
	case b >= 'A' && b <= 'F':
		return b - 'A' + 10, nil
	default:
		return 0, pktline.ErrInvalidPktLen
	}
}

func decodeV2CapabilityAdvertisement(r io.Reader) (*v2CapabilityAdvertisement, error) {
	reader := newPacketReader(r)

var (
		kind    packetType
		payload []byte
		err     error
	)
	for {
		kind, payload, err = reader.ReadPacket()
		if err != nil {
			return nil, err
		}
		if kind == packetTypeFlush {
			continue
		}
		if kind != packetTypeData {
			return nil, fmt.Errorf("unexpected packet type %v before protocol advertisement", kind)
		}
		if strings.HasPrefix(string(payload), "# service=") {
			continue
		}
		if string(payload) != "version 2\n" {
			return nil, fmt.Errorf("unexpected protocol advertisement %q", payload)
		}
		break
	}

adv := &v2CapabilityAdvertisement{Capabilities: map[string]string{}}
	for {
		kind, payload, err = reader.ReadPacket()
		if err != nil {
			return nil, err
		}
		if kind == packetTypeFlush {
			return adv, nil
		}
		if kind != packetTypeData {
			return nil, fmt.Errorf("unexpected packet type %v in capability advertisement", kind)
		}

line := strings.TrimSuffix(string(payload), "\n")
		name, value, _ := strings.Cut(line, "=")
		adv.Capabilities[name] = value
	}
}

func encodeV2CommandRequest(command string, capabilityArgs []string, commandArgs []string) ([]byte, error) {
	var buf bytes.Buffer
	enc := pktline.NewEncoder(&buf)
	if err := enc.EncodeString("command=" + command + "\n"); err != nil {
		return nil, err
	}
	for _, arg := range capabilityArgs {
		if err := enc.EncodeString(arg + "\n"); err != nil {
			return nil, err
		}
	}
	if len(commandArgs) > 0 {
		if _, err := buf.WriteString(delimPkt); err != nil {
			return nil, err
		}
		for _, arg := range commandArgs {
			if err := enc.EncodeString(arg + "\n"); err != nil {
				return nil, err
			}
		}
	}
	if err := enc.Flush(); err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}

type sourceRefService struct {
	protocol string
	v1       *packp.AdvRefs
	v2       *v2CapabilityAdvertisement
}

func listSourceRefs(ctx context.Context, conn *transportConn, cfg Config) ([]*plumbing.Reference, *sourceRefService, error) {
	switch cfg.ProtocolMode {
	case protocolModeV1:
		adv, refs, err := listSourceRefsV1(ctx, conn)
		if err != nil {
			return nil, nil, err
		}
		return refs, &sourceRefService{protocol: protocolModeV1, v1: adv}, nil
	case protocolModeAuto, protocolModeV2:
		data, err := requestInfoRefs(ctx, conn, transport.UploadPackServiceName, "version=2")
		if err != nil {
			return nil, nil, err
		}

if adv, err := decodeV2CapabilityAdvertisement(bytes.NewReader(data)); err == nil {
			if !adv.Supports("ls-refs") || !adv.Supports("fetch") {
				return nil, nil, fmt.Errorf("source does not advertise required protocol v2 commands")
			}
			refs, err := listSourceRefsV2(ctx, conn, adv, cfg)
			if err != nil {
				return nil, nil, err
			}
			return refs, &sourceRefService{protocol: protocolModeV2, v2: adv}, nil
		}

if cfg.ProtocolMode == protocolModeV2 {
			return nil, nil, fmt.Errorf("source did not negotiate protocol v2")
		}

adv, err := decodeV1AdvertisedRefs(data)
		if err != nil {
			return nil, nil, err
		}
		refs, err := advertisedReferences(adv)
		if err != nil {
			return nil, nil, err
		}
		return refs, &sourceRefService{protocol: protocolModeV1, v1: adv}, nil
	default:
		return nil, nil, fmt.Errorf("unsupported protocol mode %q", cfg.ProtocolMode)
	}
}

func (s *sourceRefService) Fetch(ctx context.Context, repo *git.Repository, conn *transportConn, desired map[plumbing.ReferenceName]desiredRef, targetRefs map[plumbing.ReferenceName]plumbing.Hash) error {
	switch s.protocol {
	case protocolModeV2:
		return fetchSourceRefsV2(ctx, repo, conn, s.v2, desired, targetRefs)
	case protocolModeV1:
		return fetchSourceRefsWithHavesV1(ctx, repo, conn, s.v1, desired, targetRefs)
	default:
		return fmt.Errorf("unsupported source protocol %q", s.protocol)
	}
}

func (s *sourceRefService) FetchPack(ctx context.Context, conn *transportConn, desired map[plumbing.ReferenceName]desiredRef, targetRefs map[plumbing.ReferenceName]plumbing.Hash) (io.ReadCloser, error) {
	switch s.protocol {
	case protocolModeV2:
		return fetchSourcePackV2(ctx, conn, s.v2, desired, targetRefs)
	case protocolModeV1:
		return fetchSourcePackV1(ctx, conn, s.v1, desired, targetRefs)
	default:
		return nil, fmt.Errorf("unsupported source protocol %q", s.protocol)
	}
}

func sourceCapabilities(s *sourceRefService) []string {
	switch s.protocol {
	case protocolModeV2:
		keys := make([]string, 0, len(s.v2.Capabilities))
		for key, value := range s.v2.Capabilities {
			if value == "" {
				keys = append(keys, key)
				continue
			}
			keys = append(keys, key+"="+value)
		}
		sort.Strings(keys)
		return keys
	case protocolModeV1:
		if s.v1 == nil || s.v1.Capabilities == nil {
			return nil
		}
		all := s.v1.Capabilities.All()
		items := make([]string, 0, len(all))
		for _, cap := range all {
			values := s.v1.Capabilities.Get(cap)
			if len(values) == 0 {
				items = append(items, string(cap))
				continue
			}
			for _, value := range values {
				items = append(items, string(cap)+"="+value)
			}
		}
		sort.Strings(items)
		return items
	default:
		return nil
	}
}

func advCapabilities(adv *packp.AdvRefs) []string {
	if adv == nil || adv.Capabilities == nil {
		return nil
	}
	all := adv.Capabilities.All()
	items := make([]string, 0, len(all))
	for _, cap := range all {
		values := adv.Capabilities.Get(cap)
		if len(values) == 0 {
			items = append(items, string(cap))
			continue
		}
		for _, value := range values {
			items = append(items, string(cap)+"="+value)
		}
	}
	sort.Strings(items)
	return items
}

func listSourceRefsV1(ctx context.Context, conn *transportConn) (*packp.AdvRefs, []*plumbing.Reference, error) {
	adv, err := advertisedRefsV1(ctx, conn, transport.UploadPackServiceName)
	if err != nil {
		return nil, nil, err
	}
	refs, err := advertisedReferences(adv)
	if err != nil {
		return nil, nil, err
	}
	return adv, refs, nil
}

func listSourceRefsV2(ctx context.Context, conn *transportConn, adv *v2CapabilityAdvertisement, cfg Config) ([]*plumbing.Reference, error) {
	args := []string{"peel"}
	for _, prefix := range sourceRefPrefixes(cfg) {
		args = append(args, "ref-prefix "+prefix)
	}

body, err := encodeV2CommandRequest("ls-refs", v2RequestCapabilities(adv), args)
	if err != nil {
		return nil, err
	}

data, err := postRPCWithPhase(ctx, conn, transport.UploadPackServiceName, body, true, "upload-pack ls-refs")
	if err != nil {
		return nil, err
	}
	return decodeV2LSRefs(bytes.NewReader(data))
}

func fetchSourceRefsV2(
	ctx context.Context,
	repo *git.Repository,
	conn *transportConn,
	adv *v2CapabilityAdvertisement,
	desired map[plumbing.ReferenceName]desiredRef,
	targetRefs map[plumbing.ReferenceName]plumbing.Hash,
) error {
	wants := make([]plumbing.Hash, 0, len(desired))
	for _, ref := range desired {
		wants = append(wants, ref.SourceHash)
	}
	wants = sortedUniqueHashes(wants)
	haves := sortedUniqueHashes(mapsRefValues(targetRefs))
	if len(wants) == 0 {
		return git.NoErrAlreadyUpToDate
	}

commandArgs := make([]string, 0, len(wants)+len(haves)+4)
	commandArgs = append(commandArgs, "ofs-delta", "no-progress")
	for _, hash := range wants {
		commandArgs = append(commandArgs, "want "+hash.String())
	}
	for _, hash := range haves {
		commandArgs = append(commandArgs, "have "+hash.String())
	}
	commandArgs = append(commandArgs, "done")
	conn.stats.addWantsHaves("source upload-pack", len(wants), len(haves))

body, err := encodeV2CommandRequest("fetch", v2RequestCapabilities(adv), commandArgs)
	if err != nil {
		return err
	}

reader, err := postRPCStreamWithPhase(ctx, conn, transport.UploadPackServiceName, body, true, "upload-pack fetch")
	if err != nil {
		return err
	}
	defer ioutil.CheckClose(reader, &err)

if err := storeV2FetchPack(repo, reader); err != nil {
		return err
	}

return storeFetchedSourceRefs(repo, desired)
}

func fetchSourceCommitGraphV2(
	ctx context.Context,
	repo *git.Repository,
	conn *transportConn,
	adv *v2CapabilityAdvertisement,
	ref desiredRef,
) error {
	if !fetchCapabilitySupports(adv, "filter") {
		return fmt.Errorf("source does not advertise fetch filter support")
	}

commandArgs := []string{
		"ofs-delta",
		"no-progress",
		"filter tree:0",
		"want " + ref.SourceHash.String(),
		"done",
	}
	conn.stats.addWantsHaves("source upload-pack", 1, 0)

body, err := encodeV2CommandRequest("fetch", v2RequestCapabilities(adv), commandArgs)
	if err != nil {
		return err
	}

if err := storeV2FetchPack(repo, reader); err != nil {
		return err
	}
	return storeFetchedSourceRefs(repo, singleDesiredRef(ref.SourceRef, ref.TargetRef, ref.SourceHash))
}

func fetchSourcePackV2(
	ctx context.Context,
	conn *transportConn,
	adv *v2CapabilityAdvertisement,
	desired map[plumbing.ReferenceName]desiredRef,
	targetRefs map[plumbing.ReferenceName]plumbing.Hash,
) (io.ReadCloser, error) {
	body, wants, haves, err := sourceFetchRequestV2(adv, desired, targetRefs)
	if err != nil {
		return nil, err
	}
	if wants == 0 {
		return nil, git.NoErrAlreadyUpToDate
	}
	conn.stats.addWantsHaves("source upload-pack", wants, haves)

reader, err := postRPCStreamWithPhase(ctx, conn, transport.UploadPackServiceName, body, true, "upload-pack fetch")
	if err != nil {
		return nil, err
	}
	packReader, err := openV2FetchPackStream(reader)
	if err != nil {
		_ = reader.Close()
		return nil, err
	}
	return packReader, nil
}

func storeV2FetchPack(repo *git.Repository, r io.Reader) error {
	reader := newPacketReader(r)
	for {
		kind, payload, err := reader.ReadPacket()
		if err != nil {
			if errors.Is(err, io.EOF) {
				return nil
			}
			return fmt.Errorf("decode protocol v2 fetch response: %w", err)
		}

switch kind {
		case packetTypeFlush:
			return nil
		case packetTypeDelim, packetTypeResponseEnd:
			continue
		case packetTypeData:
			line := string(payload)
			switch line {
			case "packfile\n":
				demux := sideband.NewDemuxer(sideband.Sideband64k, reader.Reader())
				if err := packfile.UpdateObjectStorage(repo.Storer, demux); err != nil {
					return fmt.Errorf("store source packfile: %w", err)
				}
				return nil
			case "acknowledgments\n", "shallow-info\n":
				if err := skipV2Section(reader); err != nil {
					return err
				}
			default:
				return fmt.Errorf("unexpected protocol v2 fetch section %q", strings.TrimSpace(line))
			}
		}
	}
}

func openV2FetchPackStream(body io.ReadCloser) (io.ReadCloser, error) {
	reader := newPacketReader(body)
	for {
		kind, payload, err := reader.ReadPacket()
		if err != nil {
			if errors.Is(err, io.EOF) {
				return nil, io.ErrUnexpectedEOF
			}
			return nil, fmt.Errorf("decode protocol v2 fetch response: %w", err)
		}

switch kind {
		case packetTypeFlush:
			return nil, io.ErrUnexpectedEOF
		case packetTypeDelim, packetTypeResponseEnd:
			continue
		case packetTypeData:
			line := string(payload)
			switch line {
			case "packfile\n":
				return &wrappedReadCloser{
					Reader: sideband.NewDemuxer(sideband.Sideband64k, reader.Reader()),
					Closer: body,
				}, nil
			case "acknowledgments\n", "shallow-info\n":
				if err := skipV2Section(reader); err != nil {
					return nil, err
				}
			default:
				return nil, fmt.Errorf("unexpected protocol v2 fetch section %q", strings.TrimSpace(line))
			}
		}
	}
}

func skipV2Section(reader *packetReader) error {
	for {
		kind, _, err := reader.ReadPacket()
		if err != nil {
			return err
		}
		if kind == packetTypeDelim || kind == packetTypeFlush {
			return nil
		}
	}
}

func decodeV2LSRefs(r io.Reader) ([]*plumbing.Reference, error) {
	reader := newPacketReader(r)
	var refs []*plumbing.Reference
	for {
		kind, payload, err := reader.ReadPacket()
		if err != nil {
			return nil, err
		}
		if kind == packetTypeFlush {
			return refs, nil
		}
		if kind != packetTypeData {
			return nil, fmt.Errorf("unexpected packet type %v in ls-refs response", kind)
		}

fields := strings.Fields(strings.TrimSpace(string(payload)))
		if len(fields) < 2 {
			return nil, fmt.Errorf("malformed ls-refs response line %q", payload)
		}
		hash := plumbing.NewHash(fields[0])
		name := plumbing.ReferenceName(fields[1])
		refs = append(refs, plumbing.NewHashReference(name, hash))
	}
}

func sourceRefPrefixes(cfg Config) []string {
	prefixSet := map[string]struct{}{}

addPrefix := func(ref plumbing.ReferenceName) {
		switch {
		case ref.IsBranch():
			prefixSet["refs/heads/"] = struct{}{}
		case ref.IsTag():
			prefixSet["refs/tags/"] = struct{}{}
		}
	}

if len(cfg.Mappings) > 0 {
		for _, mapping := range cfg.Mappings {
			sourceRef, _, _, err := normalizeMapping(mapping)
			if err != nil {
				continue
			}
			addPrefix(sourceRef)
		}
	} else {
		prefixSet["refs/heads/"] = struct{}{}
	}
	if cfg.IncludeTags {
		prefixSet["refs/tags/"] = struct{}{}
	}

prefixes := make([]string, 0, len(prefixSet))
	for prefix := range prefixSet {
		prefixes = append(prefixes, prefix)
	}
	sort.Strings(prefixes)
	return prefixes
}

func fetchCapabilitySupports(adv *v2CapabilityAdvertisement, feature string) bool {
	if adv == nil {
		return false
	}
	values := strings.Fields(adv.Value("fetch"))
	for _, value := range values {
		if value == feature {
			return true
		}
	}
	return false
}

func v2RequestCapabilities(adv *v2CapabilityAdvertisement) []string {
	var caps []string
	if agent := adv.Value("agent"); agent != "" {
		caps = append(caps, "agent="+capability.DefaultAgent())
	}
	return caps
}

func sourceFetchRequestV2(
	adv *v2CapabilityAdvertisement,
	desired map[plumbing.ReferenceName]desiredRef,
	targetRefs map[plumbing.ReferenceName]plumbing.Hash,
) ([]byte, int, int, error) {
	wants := make([]plumbing.Hash, 0, len(desired))
	for _, ref := range desired {
		wants = append(wants, ref.SourceHash)
	}
	wants = sortedUniqueHashes(wants)
	haves := sortedUniqueHashes(mapsRefValues(targetRefs))
	if len(wants) == 0 {
		return nil, 0, 0, nil
	}

commandArgs := make([]string, 0, len(wants)+len(haves)+4)
	commandArgs = append(commandArgs, "ofs-delta", "no-progress")
	if desiredHasTag(desired) {
		commandArgs = append(commandArgs, "include-tag")
	}
	for _, hash := range wants {
		commandArgs = append(commandArgs, "want "+hash.String())
	}
	for _, hash := range haves {
		commandArgs = append(commandArgs, "have "+hash.String())
	}
	commandArgs = append(commandArgs, "done")

body, err := encodeV2CommandRequest("fetch", v2RequestCapabilities(adv), commandArgs)
	if err != nil {
		return nil, 0, 0, err
	}
	return body, len(wants), len(haves), nil
}

type wrappedReadCloser struct {
	io.Reader
	io.Closer
}

func storeFetchedSourceRefs(repo *git.Repository, desired map[plumbing.ReferenceName]desiredRef) error {
	for _, ref := range desired {
		localRef := plumbing.ReferenceName(localBranchRef(sourceRemoteName, ref.TargetRef.Short()))
		if ref.Kind == RefKindTag {
			localRef = plumbing.ReferenceName("refs/remotes/" + sourceRemoteName + "/tags/" + ref.TargetRef.Short())
		}
		if err := repo.Storer.SetReference(plumbing.NewHashReference(localRef, ref.SourceHash)); err != nil {
			return fmt.Errorf("set local source ref %s: %w", ref.SourceRef, err)
		}
	}
	return nil
}

func requestInfoRefs(ctx context.Context, conn *transportConn, service, gitProtocol string) ([]byte, error) {
	url := fmt.Sprintf("%s/info/refs?service=%s", conn.endpoint.String(), service)
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Accept", "*/*")
	req.Header.Set("User-Agent", capability.DefaultAgent())
	req.Header.Set(statsPhaseHdr, service+" info-refs")
	if gitProtocol != "" {
		req.Header.Set("Git-Protocol", gitProtocol)
	}
	applyAuth(req, conn.authMethod())

res, err := conn.http.Do(req)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()
	if err := transporthttp.NewErr(res); err != nil {
		return nil, err
	}
	return io.ReadAll(res.Body)
}

func advertisedRefsV1(ctx context.Context, conn *transportConn, service string) (*packp.AdvRefs, error) {
	data, err := requestInfoRefs(ctx, conn, service, "")
	if err != nil {
		return nil, err
	}
	return decodeV1AdvertisedRefs(data)
}

func decodeV1AdvertisedRefs(data []byte) (*packp.AdvRefs, error) {
	ar := packp.NewAdvRefs()
	if err := ar.Decode(bytes.NewReader(data)); err != nil {
		if err == packp.ErrEmptyAdvRefs {
			return nil, transport.ErrEmptyRemoteRepository
		}
		return nil, err
	}
	return ar, nil
}

func postRPC(ctx context.Context, conn *transportConn, service string, body []byte, gitProtocolV2 bool) ([]byte, error) {
	reader, err := postRPCStream(ctx, conn, service, body, gitProtocolV2)
	if err != nil {
		return nil, err
	}
	defer reader.Close()
	return io.ReadAll(reader)
}

func postRPCWithPhase(ctx context.Context, conn *transportConn, service string, body []byte, gitProtocolV2 bool, phase string) ([]byte, error) {
	reader, err := postRPCStreamWithPhase(ctx, conn, service, body, gitProtocolV2, phase)
	if err != nil {
		return nil, err
	}
	defer reader.Close()
	return io.ReadAll(reader)
}

func postRPCStream(ctx context.Context, conn *transportConn, service string, body []byte, gitProtocolV2 bool) (io.ReadCloser, error) {
	return postRPCStreamWithPhase(ctx, conn, service, body, gitProtocolV2, service)
}

func postRPCStreamWithPhase(ctx context.Context, conn *transportConn, service string, body []byte, gitProtocolV2 bool, phase string) (io.ReadCloser, error) {
	url := fmt.Sprintf("%s/%s", conn.endpoint.String(), service)
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", fmt.Sprintf("application/x-%s-request", service))
	req.Header.Set("Accept", fmt.Sprintf("application/x-%s-result", service))
	req.Header.Set("User-Agent", capability.DefaultAgent())
	req.Header.Set(statsPhaseHdr, phase)
	if gitProtocolV2 {
		req.Header.Set("Git-Protocol", "version=2")
	}
	applyAuth(req, conn.authMethod())

res, err := conn.http.Do(req)
	if err != nil {
		return nil, err
	}
	if err := transporthttp.NewErr(res); err != nil {
		_ = res.Body.Close()
		return nil, err
	}
	return res.Body, nil
}
```

Dinternal/syncer/protocol\_v2.go-782

```
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

package syncer

import (
	"bytes"
	"testing"

"github.com/go-git/go-git/v5/plumbing"
)

func TestPacketReaderHandlesSpecialPackets(t *testing.T) {
	reader := newPacketReader(bytes.NewBufferString("0000000100020006a\n"))

kind, payload, err := reader.ReadPacket()
	if err != nil {
		t.Fatalf("read flush: %v", err)
	}
	if kind != packetTypeFlush || payload != nil {
		t.Fatalf("unexpected flush packet: kind=%v payload=%q", kind, payload)
	}

kind, payload, err = reader.ReadPacket()
	if err != nil {
		t.Fatalf("read delim: %v", err)
	}
	if kind != packetTypeDelim {
		t.Fatalf("unexpected delim kind: %v", kind)
	}

kind, payload, err = reader.ReadPacket()
	if err != nil {
		t.Fatalf("read response-end: %v", err)
	}
	if kind != packetTypeResponseEnd {
		t.Fatalf("unexpected response-end kind: %v", kind)
	}

kind, payload, err = reader.ReadPacket()
	if err != nil {
		t.Fatalf("read data: %v", err)
	}
	if kind != packetTypeData || string(payload) != "a\n" {
		t.Fatalf("unexpected data packet: kind=%v payload=%q", kind, payload)
	}
}

func TestDecodeV2CapabilityAdvertisement(t *testing.T) {
	wire := "" +
		"000eversion 2\n" +
		"0013ls-refs=unborn\n" +
		"0012fetch=shallow\n" +
		"0013agent=git/test\n" +
		"0000"

adv, err := decodeV2CapabilityAdvertisement(bytes.NewBufferString(wire))
	if err != nil {
		t.Fatalf("decode advertisement: %v", err)
	}
	if !adv.Supports("ls-refs") {
		t.Fatalf("expected ls-refs capability")
	}
	if got := adv.Value("fetch"); got != "shallow" {
		t.Fatalf("unexpected fetch value %q", got)
	}
	if got := adv.Value("agent"); got != "git/test" {
		t.Fatalf("unexpected agent value %q", got)
	}
}

func TestEncodeV2CommandRequest(t *testing.T) {
	req, err := encodeV2CommandRequest(
		"ls-refs",
		[]string{"agent=git-sync/test"},
		[]string{"peel", "ref-prefix refs/heads/"},
	)
	if err != nil {
		t.Fatalf("encode request: %v", err)
	}

want := "" +
		"0014command=ls-refs\n" +
		"0018agent=git-sync/test\n" +
		"0001" +
		"0009peel\n" +
		"001bref-prefix refs/heads/\n" +
		"0000"
	if string(req) != want {
		t.Fatalf("unexpected request:\n%s\nwant:\n%s", req, want)
	}
}

func TestSourceFetchRequestV2IncludesIncludeTagForTagSync(t *testing.T) {
	adv := &v2CapabilityAdvertisement{
		Capabilities: map[string]string{
			"fetch": "thin-pack filter",
		},
	}
	desired := map[plumbing.ReferenceName]desiredRef{
		plumbing.NewTagReferenceName("v1"): {
			Kind:       RefKindTag,
			Label:      "v1",
			SourceRef:  plumbing.NewTagReferenceName("v1"),
			TargetRef:  plumbing.NewTagReferenceName("v1"),
			SourceHash: plumbing.NewHash("1111111111111111111111111111111111111111"),
		},
	}

body, wants, haves, err := sourceFetchRequestV2(adv, desired, nil)
	if err != nil {
		t.Fatalf("build fetch request: %v", err)
	}
	if wants != 1 || haves != 0 {
		t.Fatalf("unexpected wants/haves: wants=%d haves=%d", wants, haves)
	}
	if !bytes.Contains(body, []byte("include-tag\n")) {
		t.Fatalf("expected include-tag in fetch request, got:\n%s", body)
	}
}
```

Dinternal/syncer/protocol\_v2\_test.go-117

```
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

package syncer

import (
	"io"
	"net/http"
	"strings"
	"sync"

"github.com/soph/git-sync/internal/gitproto"
)

// ServiceStats tracks transfer statistics for a single service.
type ServiceStats struct {
	Name          string `json:"name"`
	Requests      int    `json:"requests"`
	RequestBytes  int64  `json:"request_bytes"`
	ResponseBytes int64  `json:"response_bytes"`
	Wants         int    `json:"wants"`
	Haves         int    `json:"haves"`
	Commands      int    `json:"commands"`
}

// Stats holds the collected transfer statistics.
type Stats struct {
	Enabled bool                     `json:"enabled"`
	Items   map[string]*ServiceStats `json:"items"`
}

// statsCollector is a concurrency-safe stats collector (issue #8).
type statsCollector struct {
	enabled bool
	mu      sync.Mutex
	items   map[string]*ServiceStats
}

func newStats(enabled bool) *statsCollector {
	return &statsCollector{enabled: enabled, items: map[string]*ServiceStats{}}
}

func (s *statsCollector) ensure(name string) *ServiceStats {
	item, ok := s.items[name]
	if !ok {
		item = &ServiceStats{Name: name}
		s.items[name] = item
	}
	return item
}

func (s *statsCollector) addWantsHaves(name string, wants, haves int) {
	if !s.enabled {
		return
	}
	s.mu.Lock()
	defer s.mu.Unlock()
	item := s.ensure(name)
	item.Wants += wants
	item.Haves += haves
}

func (s *statsCollector) addCommands(name string, commands int) {
	if !s.enabled {
		return
	}
	s.mu.Lock()
	defer s.mu.Unlock()
	item := s.ensure(name)
	item.Commands += commands
}

func (s *statsCollector) recordRoundTrip(name string, requestBytes, responseBytes int64) {
	if !s.enabled {
		return
	}
	s.mu.Lock()
	defer s.mu.Unlock()
	item := s.ensure(name)
	item.Requests++
	item.RequestBytes += requestBytes
	item.ResponseBytes += responseBytes
}

func (s *statsCollector) snapshot() Stats {
	s.mu.Lock()
	defer s.mu.Unlock()
	out := Stats{Enabled: s.enabled, Items: make(map[string]*ServiceStats, len(s.items))}
	for key, item := range s.items {
		copyItem := *item
		out.Items[key] = &copyItem
	}
	return out
}

// countingRoundTripper wraps an HTTP transport to record transfer stats.
type countingRoundTripper struct {
	base  http.RoundTripper
	label string
	stats *statsCollector
}

func (rt *countingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
	res, err := rt.base.RoundTrip(req)
	if err != nil {
		return nil, err
	}

serviceName := req.Header.Get(gitproto.StatsPhaseHeader)
	if serviceName == "" {
		serviceName = req.URL.Query().Get("service")
		if serviceName == "" {
			serviceName = strings.TrimPrefix(req.URL.Path[strings.LastIndex(req.URL.Path, "/")+1:], "/")
		}
	}
	name := strings.TrimSpace(rt.label + " " + serviceName)
	requestBytes := req.ContentLength
	if requestBytes < 0 {
		requestBytes = 0
	}

res.Body = &countingReadCloser{
		ReadCloser: res.Body,
		onClose: func(n int64) {
			rt.stats.recordRoundTrip(name, requestBytes, n)
		},
	}
	return res, nil
}

type countingReadCloser struct {
	io.ReadCloser
	n       int64
	onClose func(int64)
}

func (c *countingReadCloser) Read(p []byte) (int, error) {
	n, err := c.ReadCloser.Read(p)
	c.n += int64(n)
	return n, err
}

func (c *countingReadCloser) Close() error {
	err := c.ReadCloser.Close()
	if c.onClose != nil {
		c.onClose(c.n)
		c.onClose = nil
	}
	return err
}
```

Ainternal/syncer/stats.go+148

```
1
2
3
4
5
6
4
7
6
8
9
10
10
11
12
13
14
15
16
17
11
19
12
21
22
13
14
15
26
27
16
29
30
17
18
33
19
35
36
20
21
22
23
24
25
26
27
28
29
40
30
31
32
44
45
46
47
33
34
50
51
52
35
36
37
38
2 unmodified lines

41
42
43
61
62
63
64
44
45
46
47
48
49
50
11 unmodified lines

62
63
64
83
65
66
67
68
69
70
71
72
86
87
73
74
75
76
77
78
79
80
81
90
91
92
93
94
95
96
97
98
82
83
84
85
86
101
87
88
89
90
91
92
93
94
103
104
105
106
107
108
109
110
95
96
97
98
14 unmodified lines

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
7 unmodified lines

151
152
153
144
145
146
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
5 unmodified lines

190
191
192
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
193
230
194
195
196
197
4 unmodified lines

202
203
204
241
242
205
206
207
244
245
246
247
248
249
250
251
252
208
209
210
211
212
213
214
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
215
216
217
3 unmodified lines

221
222
223
368
369
224
225
226
371
372
227
228
229
374
375
376
377
378
379
380
381
382
383
384
385
386
230
231
232
233
234
235
236
237
238
388
239
240
241
242
243
244
245
246
247
390
391
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
398
399
400
401
402
403
404
405
406
380
381
408
382
383
384
385
386
387
388
389
390
391
392
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
393
394
395
396
397
398
399
444
400
401
402
403
446
404
405
406
407
408
451
452
453
454
455
456
457
458
459
409
410
411
412
413
462
414
415
416
465
417
418
419
420
421
422
423
424
425
426
427
428
471
429
430
431
432
433
434
477
478
479
480
481
482
483
484
435
436
437
438
439
440
441
490
491
492
493
494
495
496
442
443
444
445
9 unmodified lines

455
456
457
512
458
459
460
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
546
547
548
549
550
476
477
478
479
480
481
482
483
484
485
486
6 unmodified lines

493
494
495
563
496
497
498
499
500
501
502
570
571
572
573
574
575
576
503
504
505
4 unmodified lines

510
511
512
587
588
513
514
590
515
516
592
593
594
595
517
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
518
519
520
521
522
523
524
620
621
622
525
526
527
528
529
530
531
532
533
627
628
629
630
631
632
633
534
535
536
537
638
639
538
539
641
540
541
542
644
645
646
543
544
545
546
547
548
649
650
651
652
653
654
655
656
657
658
659
660
661
662
549
550
551
666
667
668
552
553
554
555
670
671
556
557
558
559
560
675
676
677
678
679
680
681
682
561
684
685
686
562
563
564
565
688
566
567
568
569
570
693
694
695
696
697
698
699
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
709
710
711
712
713
714
715
716
717
718
719
720
721
586
587
588
589
14 unmodified lines

604
605
606
742
607
608
609
610
611
10 unmodified lines

622
623
624
625
626
627
628
629
630
631
632
633
634
762
635
636
764
637
638
766
767
639
640
641
642
643
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
644
645
646
647
648
649
929
930
931
650
651
652
933
653
654
655
656
657
937
658
659
660
661
662
663
664
665
666
667
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
668
669
670
671
672
673
674
675
676
999
1000
1001
1002
1003
1004
1005
677
678
1007
1008
1009
1010
1011
1012
1013
1014
1015
679
680
681
682
1017
1018
683
684
685
686
687
688
1020
1021
1022
1023
689
690
1026
1027
1028
691
692
693
694
695
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
696
697
698
699
2 unmodified lines

702
703
704
2608
705
2610
706
707
708
709
710
711
712
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
713
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143

// Package syncer provides the top-level orchestration for git-sync.
// It delegates to internal/gitproto for protocol, internal/planner for
// planning, and internal/auth for credentials.
package syncer

import (
	"bytes"
	"context"
	"crypto/tls"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"runtime"
	"sort"
	"strconv"
	"strings"
	"sync"
	"time"

git "github.com/go-git/go-git/v5"
	"github.com/go-git/go-git/v5/plumbing"
	"github.com/go-git/go-git/v5/plumbing/format/packfile"
	"github.com/go-git/go-git/v5/plumbing/object"
	"github.com/go-git/go-git/v5/plumbing/protocol/packp"
	"github.com/go-git/go-git/v5/plumbing/protocol/packp/capability"
	"github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband"
	"github.com/go-git/go-git/v5/plumbing/storer"
	"github.com/go-git/go-git/v5/plumbing/transport"
	transporthttp "github.com/go-git/go-git/v5/plumbing/transport/http"
	"github.com/go-git/go-git/v5/storage/memory"
	"github.com/go-git/go-git/v5/utils/ioutil"
	"github.com/zalando/go-keyring"

"github.com/soph/git-sync/internal/auth"
	"github.com/soph/git-sync/internal/gitproto"
	"github.com/soph/git-sync/internal/planner"
	bstrap "github.com/soph/git-sync/internal/strategy/bootstrap"
	"github.com/soph/git-sync/internal/strategy/incremental"
	"github.com/soph/git-sync/internal/strategy/materialized"
)

const (
	sourceRemoteName = "source"
	protocolModeAuto = "auto"
	protocolModeV1   = "v1"
	protocolModeV2   = "v2"

defaultAutoBatchMaxPackBytes = 512 * 1024 * 1024
	entireCLIClientID            = "entire-cli"
	githubLargeRepoThresholdKB   = 1536 * 1024
)

var bodyLimitPattern = regexp.MustCompile(`body exceeded size limit ([0-9]+)`)
var githubRepoAPIBaseURL = "https://api.github.com"

// Endpoint holds the connection configuration for a remote.
type Endpoint struct {
	URL           string
	Username      string
2 unmodified lines

SkipTLSVerify bool
}

type RefMapping struct {
	Source string
	Target string
}
// RefMapping is a user-specified source:target ref mapping.
type RefMapping = planner.RefMapping

// Config holds all configuration for a sync operation.
type Config struct {
	Source            Endpoint
	Target            Endpoint
11 unmodified lines

ProtocolMode      string
}

type RefKind string
// Re-export types from planner for CLI compatibility.
type (
	RefKind    = planner.RefKind
	Action     = planner.Action
	BranchPlan = planner.BranchPlan
)

const (
	RefKindBranch RefKind = "branch"
	RefKindTag    RefKind = "tag"
	RefKindBranch = planner.RefKindBranch
	RefKindTag    = planner.RefKindTag
	ActionCreate  = planner.ActionCreate
	ActionUpdate  = planner.ActionUpdate
	ActionDelete  = planner.ActionDelete
	ActionSkip    = planner.ActionSkip
	ActionBlock   = planner.ActionBlock
)

type BranchPlan struct {
	Branch     string                 `json:"branch"`
	SourceRef  plumbing.ReferenceName `json:"source_ref"`
	TargetRef  plumbing.ReferenceName `json:"target_ref"`
	SourceHash plumbing.Hash          `json:"source_hash"`
	TargetHash plumbing.Hash          `json:"target_hash"`
	Kind       RefKind                `json:"kind"`
	Action     Action                 `json:"action"`
	Reason     string                 `json:"reason"`
type RefInfo struct {
	Name string        `json:"name"`
	Hash plumbing.Hash `json:"hash"`
}

type Action string
func (r RefInfo) MarshalJSON() ([]byte, error) {
	type ri struct {
		Name string `json:"name"`
		Hash string `json:"hash"`
	}
	return json.Marshal(ri{Name: r.Name, Hash: r.Hash.String()})
}

const (
	ActionCreate Action = "create"
	ActionUpdate Action = "update"
	ActionDelete Action = "delete"
	ActionSkip   Action = "skip"
	ActionBlock  Action = "block"
)

// Result holds the outcome of a sync or bootstrap operation.
type Result struct {
	Plans              []BranchPlan `json:"plans"`
	Pushed             int          `json:"pushed"`
14 unmodified lines

Protocol           string       `json:"protocol"`
}

func (r Result) Lines() []string {
	lines := make([]string, 0, len(r.Plans)+8)
	for _, plan := range r.Plans {
		lines = append(lines, planner.FormatPlanLine(plan))
	}
	summary := fmt.Sprintf(
		"summary: pushed=%d deleted=%d skipped=%d blocked=%d protocol=%s relay=%t relay-mode=%s relay-reason=%s batching=%t batch-count=%d planned-batches=%d",
		r.Pushed, r.Deleted, r.Skipped, r.Blocked, r.Protocol, r.Relay, r.RelayMode, r.RelayReason, r.Batching, r.BatchCount, r.PlannedBatchCount,
	)
	if r.DryRun {
		summary += " dry-run=true"
	}
	lines = append(lines, summary)
	lines = append(lines, statsLines(r.Stats)...)
	lines = append(lines, measurementLine(r.Measurement)...)
	if r.BootstrapSuggested {
		lines = append(lines, "hint: target refs are absent; bootstrap can seed them without local object storage")
	}
	if r.Batching && len(r.TempRefs) > 0 {
		lines = append(lines, fmt.Sprintf("batching: temp-refs=%s", strings.Join(r.TempRefs, ",")))
	}
	return lines
}

// ProbeResult holds the outcome of a probe operation.
type ProbeResult struct {
	SourceURL     string      `json:"source_url"`
	TargetURL     string      `json:"target_url,omitempty"`
7 unmodified lines

Measurement   Measurement `json:"measurement"`
}

type RefInfo struct {
	Name string        `json:"name"`
	Hash plumbing.Hash `json:"hash"`
func (r ProbeResult) Lines() []string {
	lines := []string{
		fmt.Sprintf("source: %s", r.SourceURL),
		fmt.Sprintf("requested-protocol: %s", r.RequestedMode),
		fmt.Sprintf("negotiated-protocol: %s", r.Protocol),
	}
	if len(r.RefPrefixes) > 0 {
		lines = append(lines, "ref-prefixes: "+strings.Join(r.RefPrefixes, ", "))
	}
	if len(r.Capabilities) > 0 {
		lines = append(lines, "source-capabilities: "+strings.Join(r.Capabilities, ", "))
	}
	if r.TargetURL != "" {
		lines = append(lines, "target: "+r.TargetURL)
	}
	if len(r.TargetCaps) > 0 {
		lines = append(lines, "target-capabilities: "+strings.Join(r.TargetCaps, ", "))
	}
	lines = append(lines, fmt.Sprintf("refs: %d", len(r.Refs)))
	for _, ref := range r.Refs {
		lines = append(lines, fmt.Sprintf("ref: %s %s", ref.Hash.String(), ref.Name))
	}
	lines = append(lines, statsLines(r.Stats)...)
	lines = append(lines, measurementLine(r.Measurement)...)
	return lines
}

// FetchResult holds the outcome of a fetch operation.
type FetchResult struct {
	SourceURL      string          `json:"source_url"`
	RequestedMode  string          `json:"requested_mode"`
5 unmodified lines

Measurement    Measurement     `json:"measurement"`
}

type entireAuthHostInfo struct {
	ActiveUser string   `json:"activeUser"`
	Users      []string `json:"users"`
}

type oauthTokenResponse struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	ExpiresIn    int64  `json:"expires_in"`
}

type Stats struct {
	Enabled bool                     `json:"enabled"`
	Items   map[string]*ServiceStats `json:"items"`
}

type ServiceStats struct {
	Name          string `json:"name"`
	Requests      int    `json:"requests"`
	RequestBytes  int64  `json:"request_bytes"`
	ResponseBytes int64  `json:"response_bytes"`
	Wants         int    `json:"wants"`
	Haves         int    `json:"haves"`
	Commands      int    `json:"commands"`
}

type Measurement struct {
	Enabled            bool   `json:"enabled"`
	ElapsedMillis      int64  `json:"elapsed_millis"`
	PeakAllocBytes     uint64 `json:"peak_alloc_bytes"`
	PeakHeapInuseBytes uint64 `json:"peak_heap_inuse_bytes"`
	TotalAllocBytes    uint64 `json:"total_alloc_bytes"`
	GCCount            uint32 `json:"gc_count"`
}

func (p BranchPlan) MarshalJSON() ([]byte, error) {
	type branchPlanJSON struct {
		Branch     string  `json:"branch"`
		SourceRef  string  `json:"source_ref"`
		TargetRef  string  `json:"target_ref"`
		SourceHash string  `json:"source_hash"`
		TargetHash string  `json:"target_hash"`
		Kind       RefKind `json:"kind"`
		Action     Action  `json:"action"`
		Reason     string  `json:"reason"`
	}
	return json.Marshal(branchPlanJSON{
		Branch:     p.Branch,
		SourceRef:  p.SourceRef.String(),
		TargetRef:  p.TargetRef.String(),
		SourceHash: p.SourceHash.String(),
		TargetHash: p.TargetHash.String(),
		Kind:       p.Kind,
		Action:     p.Action,
		Reason:     p.Reason,
	})
}

func (r RefInfo) MarshalJSON() ([]byte, error) {
	type refInfoJSON struct {
		Name string `json:"name"`
		Hash string `json:"hash"`
	}
	return json.Marshal(refInfoJSON{
		Name: r.Name,
		Hash: r.Hash.String(),
	})
}

func (r FetchResult) MarshalJSON() ([]byte, error) {
	type fetchResultJSON struct {
	type fr struct {
		SourceURL      string      `json:"source_url"`
		RequestedMode  string      `json:"requested_mode"`
		Protocol       string      `json:"protocol"`
4 unmodified lines

Measurement    Measurement `json:"measurement"`
	}
	haves := make([]string, 0, len(r.Haves))
	for _, hash := range r.Haves {
		haves = append(haves, hash.String())
	for _, h := range r.Haves {
		haves = append(haves, h.String())
	}
	return json.Marshal(fetchResultJSON{
		SourceURL:      r.SourceURL,
		RequestedMode:  r.RequestedMode,
		Protocol:       r.Protocol,
		Wants:          r.Wants,
		Haves:          haves,
		FetchedObjects: r.FetchedObjects,
		Stats:          r.Stats,
		Measurement:    r.Measurement,
	return json.Marshal(fr{
		SourceURL: r.SourceURL, RequestedMode: r.RequestedMode,
		Protocol: r.Protocol, Wants: r.Wants, Haves: haves,
		FetchedObjects: r.FetchedObjects, Stats: r.Stats, Measurement: r.Measurement,
	})
}

func (r Result) Lines() []string {
	lines := make([]string, 0, len(r.Plans)+8)
	for _, plan := range r.Plans {
		label := plan.Branch
		if plan.TargetRef != "" {
			label = plan.TargetRef.String()
		}
		line := fmt.Sprintf("%s %s", strings.ToUpper(string(plan.Action)), label)
		if plan.Reason != "" {
			line += " - " + plan.Reason
		}
		lines = append(lines, line)
	}

summary := fmt.Sprintf(
		"summary: pushed=%d deleted=%d skipped=%d blocked=%d protocol=%s relay=%t relay-mode=%s relay-reason=%s batching=%t batch-count=%d planned-batches=%d",
		r.Pushed, r.Deleted, r.Skipped, r.Blocked, r.Protocol, r.Relay, r.RelayMode, r.RelayReason, r.Batching, r.BatchCount, r.PlannedBatchCount,
	)
	if r.DryRun {
		summary += " dry-run=true"
	}
	lines = append(lines, summary)

if r.Stats.Enabled {
		keys := make([]string, 0, len(r.Stats.Items))
		for key := range r.Stats.Items {
			keys = append(keys, key)
		}
		sort.Strings(keys)
		for _, key := range keys {
			item := r.Stats.Items[key]
			lines = append(lines, fmt.Sprintf(
				"stats: %s requests=%d request-bytes=%d response-bytes=%d wants=%d haves=%d commands=%d",
				item.Name, item.Requests, item.RequestBytes, item.ResponseBytes, item.Wants, item.Haves, item.Commands,
			))
		}
	}
	if r.Measurement.Enabled {
		lines = append(lines, fmt.Sprintf(
			"measurement: elapsed-ms=%d peak-alloc-bytes=%d peak-heap-inuse-bytes=%d total-alloc-bytes=%d gc-count=%d",
			r.Measurement.ElapsedMillis, r.Measurement.PeakAllocBytes, r.Measurement.PeakHeapInuseBytes, r.Measurement.TotalAllocBytes, r.Measurement.GCCount,
		))
	}
	if r.BootstrapSuggested {
		lines = append(lines, "hint: target refs are absent; bootstrap can seed them without local object storage")
	}

if r.Batching && len(r.TempRefs) > 0 {
		lines = append(lines, fmt.Sprintf("batching: temp-refs=%s", strings.Join(r.TempRefs, ",")))
	}

return lines
}

func (r ProbeResult) Lines() []string {
	lines := []string{
		fmt.Sprintf("source: %s", r.SourceURL),
		fmt.Sprintf("requested-protocol: %s", r.RequestedMode),
		fmt.Sprintf("negotiated-protocol: %s", r.Protocol),
	}

if len(r.RefPrefixes) > 0 {
		lines = append(lines, "ref-prefixes: "+strings.Join(r.RefPrefixes, ", "))
	}
	if len(r.Capabilities) > 0 {
		lines = append(lines, "source-capabilities: "+strings.Join(r.Capabilities, ", "))
	}
	if r.TargetURL != "" {
		lines = append(lines, "target: "+r.TargetURL)
	}
	if len(r.TargetCaps) > 0 {
		lines = append(lines, "target-capabilities: "+strings.Join(r.TargetCaps, ", "))
	}

lines = append(lines, fmt.Sprintf("refs: %d", len(r.Refs)))
	for _, ref := range r.Refs {
		lines = append(lines, fmt.Sprintf("ref: %s %s", ref.Hash.String(), ref.Name))
	}

return lines
}

func (r FetchResult) Lines() []string {
	lines := []string{
		fmt.Sprintf("source: %s", r.SourceURL),
3 unmodified lines

fmt.Sprintf("haves: %d", len(r.Haves)),
		fmt.Sprintf("fetched-objects: %d", r.FetchedObjects),
	}
	for _, want := range r.Wants {
		lines = append(lines, fmt.Sprintf("want: %s %s", want.Hash.String(), want.Name))
	for _, w := range r.Wants {
		lines = append(lines, fmt.Sprintf("want: %s %s", w.Hash.String(), w.Name))
	}
	for _, have := range r.Haves {
		lines = append(lines, fmt.Sprintf("have: %s", have.String()))
	for _, h := range r.Haves {
		lines = append(lines, fmt.Sprintf("have: %s", h.String()))
	}
	if r.Stats.Enabled {
		keys := make([]string, 0, len(r.Stats.Items))
		for key := range r.Stats.Items {
			keys = append(keys, key)
		}
		sort.Strings(keys)
		for _, key := range keys {
			item := r.Stats.Items[key]
			lines = append(lines, fmt.Sprintf(
				"stats: %s requests=%d request-bytes=%d response-bytes=%d wants=%d haves=%d commands=%d",
				item.Name, item.Requests, item.RequestBytes, item.ResponseBytes, item.Wants, item.Haves, item.Commands,
			))
		}
	lines = append(lines, statsLines(r.Stats)...)
	lines = append(lines, measurementLine(r.Measurement)...)
	return lines
}

func statsLines(s Stats) []string {
	if !s.Enabled {
		return nil
	}
	if r.Measurement.Enabled {
	keys := make([]string, 0, len(s.Items))
	for k := range s.Items {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	var lines []string
	for _, k := range keys {
		item := s.Items[k]
		lines = append(lines, fmt.Sprintf(
			"measurement: elapsed-ms=%d peak-alloc-bytes=%d peak-heap-inuse-bytes=%d total-alloc-bytes=%d gc-count=%d",
			r.Measurement.ElapsedMillis, r.Measurement.PeakAllocBytes, r.Measurement.PeakHeapInuseBytes, r.Measurement.TotalAllocBytes, r.Measurement.GCCount,
			"stats: %s requests=%d request-bytes=%d response-bytes=%d wants=%d haves=%d commands=%d",
			item.Name, item.Requests, item.RequestBytes, item.ResponseBytes, item.Wants, item.Haves, item.Commands,
		))
	}
	return lines
}

func measurementLine(m Measurement) []string {
	if !m.Enabled {
		return nil
	}
	return []string{fmt.Sprintf(
		"measurement: elapsed-ms=%d peak-alloc-bytes=%d peak-heap-inuse-bytes=%d total-alloc-bytes=%d gc-count=%d",
		m.ElapsedMillis, m.PeakAllocBytes, m.PeakHeapInuseBytes, m.TotalAllocBytes, m.GCCount,
	)}
}

// --- Session setup ---

func newConn(raw Endpoint, label string, stats *statsCollector) (*gitproto.Conn, error) {
	ep, err := transport.NewEndpoint(raw.URL)
	if err != nil {
		return nil, err
	}
	authEp := auth.Endpoint{
		Username:      raw.Username,
		Token:         raw.Token,
		BearerToken:   raw.BearerToken,
		SkipTLSVerify: raw.SkipTLSVerify,
	}
	authMethod, err := auth.Resolve(authEp, ep)
	if err != nil {
		return nil, err
	}
	baseRT := gitproto.NewHTTPTransport(raw.SkipTLSVerify)
	rt := &countingRoundTripper{base: baseRT, label: label, stats: stats}
	return gitproto.NewConn(ep, label, authMethod, rt), nil
}

func planConfig(cfg Config) planner.PlanConfig {
	return planner.PlanConfig{
		Branches:    cfg.Branches,
		Mappings:    cfg.Mappings,
		IncludeTags: cfg.IncludeTags,
		Force:       cfg.Force,
		Prune:       cfg.Prune,
	}
}

// toGitprotoDesired converts planner DesiredRefs to gitproto DesiredRefs.
func toGitprotoDesired(desired map[plumbing.ReferenceName]planner.DesiredRef) map[plumbing.ReferenceName]gitproto.DesiredRef {
	out := make(map[plumbing.ReferenceName]gitproto.DesiredRef, len(desired))
	for k, v := range desired {
		out[k] = gitproto.DesiredRef{
			SourceRef:  v.SourceRef,
			TargetRef:  v.TargetRef,
			SourceHash: v.SourceHash,
			IsTag:      v.Kind == planner.RefKindTag,
		}
	}
	return out
}

// --- Session setup (issue #12) ---

// syncSession holds the shared state for a sync operation, reducing
// setup duplication across Run, Bootstrap, Probe, and Fetch.
type syncSession struct {
	cfg             Config
	stats           *statsCollector
	sourceConn      *gitproto.Conn
	targetConn      *gitproto.Conn
	sourceService   *gitproto.RefService
	targetAdv       *packp.AdvRefs
	sourceRefMap    map[plumbing.ReferenceName]plumbing.Hash
	targetRefMap    map[plumbing.ReferenceName]plumbing.Hash
	measurementDone func() Measurement
}

// newSession performs the shared setup: protocol validation, mapping validation,
// connection creation, and ref discovery.
func newSession(ctx context.Context, cfg Config, needTarget bool) (*syncSession, error) {
	if err := validateProtocol(&cfg); err != nil {
		return nil, err
	}
	if _, err := planner.ValidateMappings(cfg.Mappings); err != nil {
		return nil, err
	}

s := &syncSession{
		cfg:             cfg,
		stats:           newStats(cfg.ShowStats),
		measurementDone: startMeasurement(cfg.MeasureMemory),
	}

var err error
	s.sourceConn, err = newConn(cfg.Source, "source", s.stats)
	if err != nil {
		return nil, fmt.Errorf("create source transport: %w", err)
	}

refPrefixes := planner.RefPrefixes(cfg.Mappings, cfg.IncludeTags)
	sourceRefs, sourceService, err := gitproto.ListSourceRefs(ctx, s.sourceConn, cfg.ProtocolMode, refPrefixes)
	if err != nil {
		return nil, fmt.Errorf("list source refs: %w", err)
	}
	s.sourceService = sourceService
	s.sourceRefMap = gitproto.RefHashMap(sourceRefs)

if needTarget {
		s.targetConn, err = newConn(cfg.Target, "target", s.stats)
		if err != nil {
			return nil, fmt.Errorf("create target transport: %w", err)
		}
		s.targetAdv, err = gitproto.AdvertisedRefsV1(ctx, s.targetConn, transport.ReceivePackServiceName)
		if err != nil {
			return nil, fmt.Errorf("list target refs: %w", err)
		}
		targetRefSlice, err := gitproto.AdvRefsToSlice(s.targetAdv)
		if err != nil {
			return nil, fmt.Errorf("decode target refs: %w", err)
		}
		s.targetRefMap = gitproto.RefHashMap(targetRefSlice)
	}

return s, nil
}

// --- Public API ---

// Run executes a sync or plan operation.
func Run(ctx context.Context, cfg Config) (Result, error) {
	measurementDone := startMeasurement(cfg.MeasureMemory)
	if cfg.ProtocolMode == "" {
		cfg.ProtocolMode = protocolModeAuto
	}
	if cfg.ProtocolMode != protocolModeAuto && cfg.ProtocolMode != protocolModeV1 && cfg.ProtocolMode != protocolModeV2 {
		return Result{}, fmt.Errorf("unsupported protocol mode %q", cfg.ProtocolMode)
	}

repo, err := git.Init(memory.NewStorage(), nil)
	s, err := newSession(ctx, cfg, true)
	if err != nil {
		return Result{}, fmt.Errorf("init in-memory repository: %w", err)
		return Result{}, err
	}
	measurementDone := s.measurementDone
	stats := s.stats
	sourceConn := s.sourceConn
	targetConn := s.targetConn
	sourceService := s.sourceService
	targetAdv := s.targetAdv
	sourceRefMap := s.sourceRefMap
	targetRefMap := s.targetRefMap

stats := newStats(cfg.ShowStats)
	sourceConn, err := newTransportConn(cfg.Source, "source", stats)
	if err != nil {
		return Result{}, fmt.Errorf("create source transport: %w", err)
	}
	targetConn, err := newTransportConn(cfg.Target, "target", stats)
	if err != nil {
		return Result{}, fmt.Errorf("create target transport: %w", err)
	}

sourceRefs, sourceService, err := listSourceRefs(ctx, sourceConn, cfg)
	if err != nil {
		return Result{}, fmt.Errorf("list source refs: %w", err)
	}
	targetAdv, err := advertisedRefsV1(ctx, targetConn, transport.ReceivePackServiceName)
	if err != nil {
		return Result{}, fmt.Errorf("list target refs: %w", err)
	}
	targetRefs, err := advertisedReferences(targetAdv)
	if err != nil {
		return Result{}, fmt.Errorf("decode target refs: %w", err)
	}

sourceRefMap := refHashMap(sourceRefs)
	targetRefMap := refHashMap(targetRefs)

desiredRefs, managedTargets, err := buildDesiredRefs(sourceRefMap, cfg)
	desiredRefs, managedTargets, err := planner.BuildDesiredRefs(sourceRefMap, planConfig(cfg))
	if err != nil {
		return Result{}, err
	}
	if len(desiredRefs) == 0 {
		return Result{}, fmt.Errorf("no source refs matched")
	}
	if ok, reason := canBootstrapRelay(cfg, desiredRefs, targetRefMap); ok {

// Check for bootstrap opportunity (before allocating in-memory repo)
	if ok, reason := planner.CanBootstrapRelay(cfg.Force, cfg.Prune, desiredRefs, targetRefMap); ok {
		if cfg.DryRun {
			plans, err := buildBootstrapPlans(desiredRefs, targetRefMap)
			plans, err := planner.BuildBootstrapPlans(desiredRefs, targetRefMap)
			if err != nil {
				return Result{}, err
			}
			return Result{
				Plans:              plans,
				DryRun:             true,
				Relay:              false,
				RelayMode:          "",
				RelayReason:        reason,
				BootstrapSuggested: true,
				Stats:              stats.snapshot(),
				Measurement:        measurementDone(),
				Protocol:           sourceService.protocol,
				Plans: plans, DryRun: true, RelayReason: reason,
				BootstrapSuggested: true, Stats: stats.snapshot(),
				Measurement: measurementDone(), Protocol: sourceService.Protocol,
			}, nil
		}
		return bootstrapWithInputs(ctx, cfg, stats, sourceConn, targetConn, sourceService, targetAdv, desiredRefs, targetRefMap, reason)
		return bootstrapWithInputs(ctx, cfg, stats, sourceConn, targetConn, sourceService, targetAdv, desiredRefs, targetRefMap, reason, measurementDone)
	}

if err := sourceService.Fetch(ctx, repo, sourceConn, desiredRefs, targetRefMap); err != nil {
	// Normal sync: allocate in-memory repo and fetch objects
	repo, err := git.Init(memory.NewStorage(), nil)
	if err != nil {
		return Result{}, fmt.Errorf("init in-memory repository: %w", err)
	}
	gpDesired := toGitprotoDesired(desiredRefs)
	if err := sourceService.FetchToStore(ctx, repo.Storer, sourceConn, gpDesired, targetRefMap); err != nil {
		if !errors.Is(err, git.NoErrAlreadyUpToDate) {
			return Result{}, err
		}
	}

plans, err := buildPlans(repo, desiredRefs, targetRefMap, managedTargets, cfg)
	plans, err := planner.BuildPlans(repo.Storer, desiredRefs, targetRefMap, managedTargets, planConfig(cfg))
	if err != nil {
		return Result{}, err
	}

result := Result{
		Plans:       plans,
		DryRun:      cfg.DryRun,
		Relay:       false,
		RelayMode:   "",
		RelayReason: "",
		Stats:       stats.snapshot(),
		Measurement: measurementDone(),
		Protocol:    sourceService.protocol,
		Plans: plans, DryRun: cfg.DryRun, Protocol: sourceService.Protocol,
		Stats: stats.snapshot(), Measurement: measurementDone(),
	}

pushPlans := make([]BranchPlan, 0, len(plans))
	for _, plan := range plans {
		switch plan.Action {
		case ActionCreate, ActionUpdate:
			if cfg.DryRun {
				result.Skipped++
				continue
			}
			pushPlans = append(pushPlans, plan)
		case ActionDelete:
		case ActionCreate, ActionUpdate, ActionDelete:
			if cfg.DryRun {
				result.Skipped++
				continue
9 unmodified lines

if !cfg.DryRun && result.Blocked > 0 {
		return result, fmt.Errorf("blocked %d ref update(s); rerun with --force where appropriate", result.Blocked)
	}
	result.RelayReason = relayFallbackReason(cfg, pushPlans, targetAdv)
	result.RelayReason = planner.RelayFallbackReason(cfg.Force, cfg.Prune, cfg.DryRun, pushPlans, targetAdv)

if !cfg.DryRun {
		if ok, reason := canIncrementalRelay(cfg, pushPlans, targetAdv); ok {
			relayPlans := append([]BranchPlan(nil), pushPlans...)
			desiredRelay := desiredSubsetForPlans(desiredRefs, relayPlans)
			packReader, err := sourceService.FetchPack(ctx, sourceConn, desiredRelay, targetRefMap)
			if err != nil {
				return result, fmt.Errorf("fetch source pack: %w", err)
			}
			defer packReader.Close()
			packReader = limitPackReadCloser(packReader, cfg.MaxPackBytes)
			if err := pushPackToTarget(ctx, targetConn, targetAdv, relayPlans, packReader, cfg.Verbose); err != nil {
				return result, fmt.Errorf("push target refs: %w", err)
			}
			result.Relay = true
			result.RelayMode = "incremental"
			result.RelayReason = reason
		} else if ok, reason := canFullTagCreateRelay(pushPlans); ok {
			relayPlans := append([]BranchPlan(nil), pushPlans...)
			desiredRelay := desiredSubsetForPlans(desiredRefs, relayPlans)
			packReader, err := sourceService.FetchPack(ctx, sourceConn, desiredRelay, nil)
			if err != nil {
				return result, fmt.Errorf("fetch source tag pack: %w", err)
			}
			defer packReader.Close()
			packReader = limitPackReadCloser(packReader, cfg.MaxPackBytes)
			if err := pushPackToTarget(ctx, targetConn, targetAdv, relayPlans, packReader, cfg.Verbose); err != nil {
				return result, fmt.Errorf("push target refs: %w", err)
			}
			result.Relay = true
			result.RelayMode = "incremental"
			result.RelayReason = reason
		// Try incremental relay first
		incResult, err := incremental.Execute(ctx, incremental.Params{
			SourceConn: sourceConn, TargetConn: targetConn,
			SourceService: sourceService, TargetAdv: targetAdv,
			DesiredRefs: desiredRefs, TargetRefs: targetRefMap,
			PushPlans: pushPlans, MaxPackBytes: cfg.MaxPackBytes, Verbose: cfg.Verbose,
		}, planConfig(cfg))
		if err != nil {
			return result, err
		}
		if incResult.Relay {
			result.Relay = incResult.Relay
			result.RelayMode = incResult.RelayMode
			result.RelayReason = incResult.RelayReason
		} else if len(pushPlans) > 0 {
			if err := ensureLocalObjectsForPush(ctx, repo, sourceConn, sourceService, desiredRefs, pushPlans); err != nil {
				return result, fmt.Errorf("prepare local objects for push: %w", err)
			}
			if err := pushToTarget(ctx, repo, targetConn, targetAdv, pushPlans, targetRefMap, cfg.Verbose); err != nil {
				return result, fmt.Errorf("push target refs: %w", err)
			// Materialized fallback
			if err := materialized.Execute(ctx, materialized.Params{
				Store: repo.Storer, SourceConn: sourceConn, SourceService: sourceService,
				TargetConn: targetConn, TargetAdv: targetAdv,
				DesiredRefs: desiredRefs, TargetRefs: targetRefMap,
				PushPlans: pushPlans, Verbose: cfg.Verbose,
			}); err != nil {
				return result, err
			}
		}
	}
6 unmodified lines

result.Deleted++
		}
	}

result.Stats = stats.snapshot()
	result.Measurement = measurementDone()
	return result, nil
}

// Bootstrap seeds an empty target with relay behavior.
func Bootstrap(ctx context.Context, cfg Config) (Result, error) {
	measurementDone := startMeasurement(cfg.MeasureMemory)
	if cfg.ProtocolMode == "" {
		cfg.ProtocolMode = protocolModeAuto
	}
	if cfg.ProtocolMode != protocolModeAuto && cfg.ProtocolMode != protocolModeV1 && cfg.ProtocolMode != protocolModeV2 {
		return Result{}, fmt.Errorf("unsupported protocol mode %q", cfg.ProtocolMode)
	}
	if cfg.Force {
		return Result{}, fmt.Errorf("bootstrap does not support --force")
	}
4 unmodified lines

return Result{}, fmt.Errorf("bootstrap does not support dry-run; use plan or sync")
	}

stats := newStats(cfg.ShowStats)
	sourceConn, err := newTransportConn(cfg.Source, "source", stats)
	s, err := newSession(ctx, cfg, true)
	if err != nil {
		return Result{}, fmt.Errorf("create source transport: %w", err)
		return Result{}, err
	}
	targetConn, err := newTransportConn(cfg.Target, "target", stats)
	if err != nil {
		return Result{}, fmt.Errorf("create target transport: %w", err)
	}

sourceRefMap := refHashMap(sourceRefs)
	targetRefMap := refHashMap(targetRefs)

desiredRefs, _, err := buildDesiredRefs(sourceRefMap, cfg)
	desiredRefs, _, err := planner.BuildDesiredRefs(s.sourceRefMap, planConfig(cfg))
	if err != nil {
		return Result{}, err
	}
	if len(desiredRefs) == 0 {
		return Result{}, fmt.Errorf("no source refs matched")
	}
	_, reason := canBootstrapRelay(cfg, desiredRefs, targetRefMap)
	result, err := bootstrapWithInputs(ctx, cfg, stats, sourceConn, targetConn, sourceService, targetAdv, desiredRefs, targetRefMap, reason)
	result.Measurement = measurementDone()

_, reason := planner.CanBootstrapRelay(cfg.Force, cfg.Prune, desiredRefs, s.targetRefMap)
	result, err := bootstrapWithInputs(ctx, cfg, s.stats, s.sourceConn, s.targetConn, s.sourceService, s.targetAdv, desiredRefs, s.targetRefMap, reason, s.measurementDone)
	result.Measurement = s.measurementDone()
	return result, err
}

// Probe inspects source and optionally target remotes.
func Probe(ctx context.Context, cfg Config) (ProbeResult, error) {
	measurementDone := startMeasurement(cfg.MeasureMemory)
	if cfg.ProtocolMode == "" {
		cfg.ProtocolMode = protocolModeAuto
	}
	if cfg.ProtocolMode != protocolModeAuto && cfg.ProtocolMode != protocolModeV1 && cfg.ProtocolMode != protocolModeV2 {
		return ProbeResult{}, fmt.Errorf("unsupported protocol mode %q", cfg.ProtocolMode)
	}
	if cfg.Source.URL == "" {
		return ProbeResult{}, fmt.Errorf("source repository URL is required")
	}

stats := newStats(cfg.ShowStats)
	sourceConn, err := newTransportConn(cfg.Source, "source", stats)
	s, err := newSession(ctx, cfg, cfg.Target.URL != "")
	if err != nil {
		return ProbeResult{}, fmt.Errorf("create source transport: %w", err)
		return ProbeResult{}, err
	}

refs, service, err := listSourceRefs(ctx, sourceConn, cfg)
	if err != nil {
		return ProbeResult{}, fmt.Errorf("list source refs: %w", err)
	refInfos := make([]RefInfo, 0, len(s.sourceRefMap))
	for name, hash := range s.sourceRefMap {
		refInfos = append(refInfos, RefInfo{Name: name.String(), Hash: hash})
	}
	sort.Slice(refInfos, func(i, j int) bool { return refInfos[i].Name < refInfos[j].Name })

refInfos := make([]RefInfo, 0, len(refs))
	for _, ref := range refs {
		if ref.Type() != plumbing.HashReference {
			continue
		}
		refInfos = append(refInfos, RefInfo{
			Name: ref.Name().String(),
			Hash: ref.Hash(),
		})
	}
	sort.Slice(refInfos, func(i, j int) bool {
		return refInfos[i].Name < refInfos[j].Name
	})

result := ProbeResult{
		SourceURL:     cfg.Source.URL,
		RequestedMode: cfg.ProtocolMode,
		Protocol:      service.protocol,
		RefPrefixes:   sourceRefPrefixes(cfg),
		Capabilities:  sourceCapabilities(service),
		Protocol:      s.sourceService.Protocol,
		RefPrefixes:   planner.RefPrefixes(cfg.Mappings, cfg.IncludeTags),
		Capabilities:  s.sourceService.Capabilities(),
		Refs:          refInfos,
		Stats:         stats.snapshot(),
		Measurement:   measurementDone(),
		Stats:         s.stats.snapshot(),
		Measurement:   s.measurementDone(),
	}

if cfg.Target.URL != "" {
		targetConn, err := newTransportConn(cfg.Target, "target", stats)
		if err != nil {
			return ProbeResult{}, fmt.Errorf("create target transport: %w", err)
		}
		targetAdv, err := advertisedRefsV1(ctx, targetConn, transport.ReceivePackServiceName)
		if err != nil {
			return ProbeResult{}, fmt.Errorf("list target refs: %w", err)
		}
		result.TargetURL = cfg.Target.URL
		result.TargetCaps = advCapabilities(targetAdv)
		result.Stats = stats.snapshot()
		result.Measurement = measurementDone()
		result.TargetCaps = gitproto.AdvRefsCaps(s.targetAdv)
		result.Stats = s.stats.snapshot()
		result.Measurement = s.measurementDone()
	}

return result, nil
}

// Fetch exercises source-side fetch negotiation.
func Fetch(ctx context.Context, cfg Config, haveRefs []string, haveHashes []plumbing.Hash) (FetchResult, error) {
	measurementDone := startMeasurement(cfg.MeasureMemory)
	if cfg.ProtocolMode == "" {
		cfg.ProtocolMode = protocolModeAuto
	}
	if cfg.ProtocolMode != protocolModeAuto && cfg.ProtocolMode != protocolModeV1 && cfg.ProtocolMode != protocolModeV2 {
		return FetchResult{}, fmt.Errorf("unsupported protocol mode %q", cfg.ProtocolMode)
	}
	if cfg.Source.URL == "" {
		return FetchResult{}, fmt.Errorf("source repository URL is required")
	}

s, err := newSession(ctx, cfg, false)
	if err != nil {
		return FetchResult{}, err
	}

repo, err := git.Init(memory.NewStorage(), nil)
	if err != nil {
		return FetchResult{}, fmt.Errorf("init in-memory repository: %w", err)
	}
	sourceRefMap := s.sourceRefMap

stats := newStats(cfg.ShowStats)
	sourceConn, err := newTransportConn(cfg.Source, "source", stats)
	if err != nil {
		return FetchResult{}, fmt.Errorf("create source transport: %w", err)
	}

sourceRefs, sourceService, err := listSourceRefs(ctx, sourceConn, cfg)
	if err != nil {
		return FetchResult{}, fmt.Errorf("list source refs: %w", err)
	}
	sourceRefMap := refHashMap(sourceRefs)

desiredRefs, _, err := buildDesiredRefs(sourceRefMap, cfg)
	desiredRefs, _, err := planner.BuildDesiredRefs(sourceRefMap, planConfig(cfg))
	if err != nil {
		return FetchResult{}, err
	}
14 unmodified lines

targetRefMap[plumbing.ReferenceName(fmt.Sprintf("refs/haves/%d", idx))] = hash
	}

if err := sourceService.Fetch(ctx, repo, sourceConn, desiredRefs, targetRefMap); err != nil {
	gpDesired := toGitprotoDesired(desiredRefs)
	if err := s.sourceService.FetchToStore(ctx, repo.Storer, s.sourceConn, gpDesired, targetRefMap); err != nil {
		if !errors.Is(err, git.NoErrAlreadyUpToDate) {
			return FetchResult{}, err
		}
10 unmodified lines

return FetchResult{}, fmt.Errorf("count fetched objects: %w", err)
	}

haveValues := make([]plumbing.Hash, 0, len(targetRefMap))
	for _, h := range targetRefMap {
		if !h.IsZero() {
			haveValues = append(haveValues, h)
		}
	}

return FetchResult{
		SourceURL:      cfg.Source.URL,
		RequestedMode:  cfg.ProtocolMode,
		Protocol:       sourceService.protocol,
		Protocol:       s.sourceService.Protocol,
		Wants:          wants,
		Haves:          sortedUniqueHashes(mapsRefValues(targetRefMap)),
		Haves:          gitproto.SortedUniqueHashes(haveValues),
		FetchedObjects: objectCount,
		Stats:          stats.snapshot(),
		Measurement:    measurementDone(),
		Stats:          s.stats.snapshot(),
		Measurement:    s.measurementDone(),
	}, nil
}

func buildBootstrapPlans(
	desired map[plumbing.ReferenceName]desiredRef,
	targetRefs map[plumbing.ReferenceName]plumbing.Hash,
) ([]BranchPlan, error) {
	targetNames := make([]plumbing.ReferenceName, 0, len(desired))
	for _, want := range desired {
		targetNames = append(targetNames, want.TargetRef)
	}
	sort.Slice(targetNames, func(i, j int) bool { return targetNames[i] < targetNames[j] })

func canBootstrapRelay(
	cfg Config,
	desired map[plumbing.ReferenceName]desiredRef,
	targetRefs map[plumbing.ReferenceName]plumbing.Hash,
) (bool, string) {
	if cfg.Force || cfg.Prune {
		return false, "bootstrap-disabled-by-force-or-prune"
	}
	if len(desired) == 0 {
		return false, "bootstrap-no-managed-refs"
	}
	for targetRef := range desired {
		if !targetRefs[targetRef].IsZero() {
			return false, "bootstrap-target-ref-exists"
		}
	}
	return true, "empty-target-managed-refs"
}

func canIncrementalRelay(cfg Config, plans []BranchPlan, targetAdv *packp.AdvRefs) (bool, string) {
	if cfg.Force || cfg.Prune || cfg.DryRun {
		return false, "incremental-disabled-by-force-prune-or-dry-run"
	}
	if len(plans) == 0 {
		return false, "incremental-no-plans"
	}
	if targetAdv == nil || targetAdv.Capabilities == nil {
		return false, "incremental-missing-target-capabilities"
	}
	if targetAdv.Capabilities.Supports(capability.Capability("no-thin")) {
		return false, "incremental-target-no-thin"
	}

func relayFallbackReason(cfg Config, plans []BranchPlan, targetAdv *packp.AdvRefs) string {
	if ok, reason := canIncrementalRelay(cfg, plans, targetAdv); ok {
		return reason
	} else if ok, reason := canFullTagCreateRelay(plans); ok {
		return reason
	} else {
		return reason
	}
}

func canFullTagCreateRelay(plans []BranchPlan) (bool, string) {
	if len(plans) == 0 {
		return false, "incremental-no-plans"
	}
	for _, plan := range plans {
		if plan.Kind != RefKindTag {
			return false, "incremental-tag-relay-non-tag-plan"
		}
		if !plan.SourceRef.IsTag() || !plan.TargetRef.IsTag() {
			return false, "incremental-tag-relay-non-tag-mapping"
		}
		if plan.Action != ActionCreate {
			return false, "incremental-tag-relay-tag-action-not-create"
		}
	}
	return true, "tag-create-full-pack"
}

func desiredSubsetForPlans(
	desired map[plumbing.ReferenceName]desiredRef,
	plans []BranchPlan,
) map[plumbing.ReferenceName]desiredRef {
	out := make(map[plumbing.ReferenceName]desiredRef, len(plans))
	for _, plan := range plans {
		if ref, ok := desired[plan.TargetRef]; ok {
			out[plan.TargetRef] = ref
		}
	}
	return out
}

func ensureLocalObjectsForPush(
	ctx context.Context,
	repo *git.Repository,
	sourceConn *transportConn,
	sourceService *sourceRefService,
	desired map[plumbing.ReferenceName]desiredRef,
	plans []BranchPlan,
) error {
	tagDesired := make(map[plumbing.ReferenceName]desiredRef)
	for _, plan := range plans {
		if plan.Kind != RefKindTag {
			continue
		}
		if desiredRef, ok := desired[plan.TargetRef]; ok {
			tagDesired[plan.TargetRef] = desiredRef
		}
	}
	if len(tagDesired) == 0 {
		return nil
	}
	return sourceService.Fetch(ctx, repo, sourceConn, tagDesired, nil)
}
// --- Bootstrap implementation ---

func bootstrapWithInputs(
	ctx context.Context,
	cfg Config,
	stats *statsCollector,
	sourceConn *transportConn,
	targetConn *transportConn,
	sourceService *sourceRefService,
	sourceConn, targetConn *gitproto.Conn,
	sourceService *gitproto.RefService,
	targetAdv *packp.AdvRefs,
	desiredRefs map[plumbing.ReferenceName]desiredRef,
	desiredRefs map[plumbing.ReferenceName]planner.DesiredRef,
	targetRefs map[plumbing.ReferenceName]plumbing.Hash,
	relayReason string,
	measurementDone func() Measurement,
) (Result, error) {
	plans, err := buildBootstrapPlans(desiredRefs, targetRefs)
	bResult, err := bstrap.Execute(ctx, bstrap.Params{
		SourceConn: sourceConn, TargetConn: targetConn,
		SourceService: sourceService, TargetAdv: targetAdv,
		DesiredRefs: desiredRefs, TargetRefs: targetRefs,
		MaxPackBytes: cfg.MaxPackBytes, BatchMaxPack: cfg.BatchMaxPackBytes,
		Verbose: cfg.Verbose,
	}, relayReason)
	if err != nil {
		return Result{}, err
	}

result := Result{
		Plans:       plans,
		Relay:       true,
		RelayMode:   "bootstrap",
		RelayReason: relayReason,
		Stats:       stats.snapshot(),
		Protocol:    sourceService.protocol,
	}

if batchLimit, ok := githubBootstrapBatchMaxPackBytes(ctx, cfg, sourceConn, sourceService); ok {
		cfg.BatchMaxPackBytes = batchLimit
		progressf(
			cfg.Verbose,
			"bootstrap: github repo-size preflight selected batched mode with batch-max-pack-bytes=%d",
			cfg.BatchMaxPackBytes,
		)
	}

if cfg.BatchMaxPackBytes > 0 {
		return bootstrapBatchedWithInputs(ctx, cfg, stats, sourceConn, targetConn, sourceService, targetAdv, plans, desiredRefs, targetRefs, result)
	}

progressf(cfg.Verbose, "bootstrap: fetching %d ref(s) from source", len(plans))

packReader, err := sourceService.FetchPack(ctx, sourceConn, desiredRefs, nil)
	if err != nil {
		if errors.Is(err, git.NoErrAlreadyUpToDate) {
			return result, nil
		}
		return result, fmt.Errorf("fetch source pack: %w", err)
	}
	packReader = limitPackReadCloser(packReader, cfg.MaxPackBytes)

progressf(cfg.Verbose, "bootstrap: pushing %d ref(s) to target", len(plans))
	pushErr := pushPackToTarget(ctx, targetConn, targetAdv, plans, packReader, cfg.Verbose)
	if closeErr := packReader.Close(); closeErr != nil && pushErr == nil {
		pushErr = closeErr
	}
	if pushErr != nil {
		autoBatchSize, ok := autoBatchMaxPackBytes(cfg, sourceService, pushErr)
		if !ok {
			return result, fmt.Errorf("push target refs: %w", pushErr)
		}
		progressf(
			cfg.Verbose,
			"bootstrap: target rejected single-pack push; retrying with batch-max-pack-bytes=%d",
			autoBatchSize,
		)
		cfg.BatchMaxPackBytes = autoBatchSize
		return bootstrapBatchedWithInputs(ctx, cfg, stats, sourceConn, targetConn, sourceService, targetAdv, plans, desiredRefs, targetRefs, result)
	}

result.Pushed = len(plans)
	result.Stats = stats.snapshot()
	return result, nil
	return Result{
		Plans: bResult.Plans, Pushed: bResult.Pushed,
		Relay: bResult.Relay, RelayMode: bResult.RelayMode, RelayReason: bResult.RelayReason,
		Batching: bResult.Batching, BatchCount: bResult.BatchCount,
		PlannedBatchCount: bResult.PlannedBatchCount, TempRefs: bResult.TempRefs,
		Stats: stats.snapshot(), Measurement: measurementDone(), Protocol: sourceService.Protocol,
	}, nil
}

func autoBatchMaxPackBytes(cfg Config, sourceService *sourceRefService, err error) (int64, bool) {
	if cfg.BatchMaxPackBytes > 0 || !isTargetBodyLimitError(err) {
		return 0, false
	}
	if sourceService == nil || sourceService.protocol != protocolModeV2 || !fetchCapabilitySupports(sourceService.v2, "filter") {
		return 0, false
	}
// --- Helpers ---

batchLimit := int64(defaultAutoBatchMaxPackBytes)
	if targetLimit := targetBodyLimit(err); targetLimit > 0 {
		derivedLimit := targetLimit / 2
		if derivedLimit <= 0 {
			derivedLimit = targetLimit
		}
		if derivedLimit < batchLimit {
			batchLimit = derivedLimit
		}
func validateProtocol(cfg *Config) error {
	if cfg.ProtocolMode == "" {
		cfg.ProtocolMode = protocolModeAuto
	}
	if cfg.MaxPackBytes > 0 && cfg.MaxPackBytes < batchLimit {
		batchLimit = cfg.MaxPackBytes
	switch cfg.ProtocolMode {
	case protocolModeAuto, protocolModeV1, protocolModeV2:
		return nil
	default:
		return fmt.Errorf("unsupported protocol mode %q", cfg.ProtocolMode)
	}
	if batchLimit <= 0 {
		return 0, false
	}
	return batchLimit, true
}

func githubBootstrapBatchMaxPackBytes(ctx context.Context, cfg Config, sourceConn *transportConn, sourceService *sourceRefService) (int64, bool) {
	if cfg.BatchMaxPackBytes > 0 {
		return 0, false
func parseHaveRef(raw string) plumbing.ReferenceName {
	raw = strings.TrimSpace(raw)
	if strings.HasPrefix(raw, "refs/") {
		return plumbing.ReferenceName(raw)
	}
	if sourceConn == nil || sourceConn.endpoint == nil {
		return 0, false
	}
	if sourceService == nil || sourceService.protocol != protocolModeV2 || !fetchCapabilitySupports(sourceService.v2, "filter") {
		return 0, false
	}
	repoSizeKB, ok := lookupGitHubRepoSizeKB(ctx, sourceConn)
	if !ok || repoSizeKB < githubLargeRepoThresholdKB {
		return 0, false
	}

batchLimit := int64(defaultAutoBatchMaxPackBytes)
	if cfg.MaxPackBytes > 0 && cfg.MaxPackBytes < batchLimit {
		batchLimit = cfg.MaxPackBytes
	}
	if batchLimit <= 0 {
		return 0, false
	}
	return batchLimit, true
}

func lookupGitHubRepoSizeKB(ctx context.Context, sourceConn *transportConn) (int64, bool) {
	owner, repo, ok := githubOwnerRepo(sourceConn)
	if !ok {
		return 0, false
	}

apiURL := strings.TrimRight(githubRepoAPIBaseURL, "/") + "/repos/" + owner + "/" + repo
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, apiURL, nil)
	if err != nil {
		return 0, false
	}
	req.Header.Set("Accept", "application/vnd.github+json")
	req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
	req.Header.Set("User-Agent", capability.DefaultAgent())
	req.Header.Set(statsPhaseHdr, "github repo metadata")

resp, err := sourceConn.http.Do(req)
	if err != nil {
		return 0, false
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return 0, false
	}

var payload struct {
		Size int64 `json:"size"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {
		return 0, false
	}
	if payload.Size <= 0 {
		return 0, false
	}
	return payload.Size, true
}

func githubOwnerRepo(sourceConn *transportConn) (string, string, bool) {
	if sourceConn == nil || sourceConn.endpoint == nil {
		return "", "", false
	}
	ep := sourceConn.endpoint
	if ep.Protocol != "http" && ep.Protocol != "https" {
		return "", "", false
	}
	if !strings.EqualFold(ep.Host, "github.com") {
		return "", "", false
	}

path := strings.Trim(ep.Path, "/")
	if strings.HasSuffix(path, ".git") {
		path = strings.TrimSuffix(path, ".git")
	}
	parts := strings.Split(path, "/")
	if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
		return "", "", false
	}
	return parts[0], parts[1], true
}

func isTargetBodyLimitError(err error) bool {
	if err == nil {
		return false
	}
	message := strings.ToLower(err.Error())
	return strings.Contains(message, "body exceeded size limit") ||
		(strings.Contains(message, "request body") && strings.Contains(message, "too large")) ||
		(strings.Contains(message, "payload") && strings.Contains(message, "too large")) ||
		strings.Contains(message, "http 413")
}

type bootstrapBatch struct {
	Plan        BranchPlan
	TempRef     plumbing.ReferenceName
	ResumeHash  plumbing.Hash
	Checkpoints []plumbing.Hash
}

func bootstrapBatchedWithInputs(
	ctx context.Context,
	cfg Config,
	stats *statsCollector,
	sourceConn *transportConn,
	targetConn *transportConn,
	sourceService *sourceRefService,
	targetAdv *packp.AdvRefs,
	plans []BranchPlan,
	desiredRefs map[plumbing.ReferenceName]desiredRef,
	targetRefs map[plumbing.ReferenceName]plumbing.Hash,
	result Result,
) (Result, error) {
	if sourceService.protocol != protocolModeV2 {
		return result, fmt.Errorf("bootstrap batching currently requires protocol v2")
	}
	if !fetchCapabilitySupports(sourceService.v2, "filter") {
		return result, fmt.Errorf("bootstrap batching requires source fetch filter support")
	}

planRefs := make([]desiredRef, 0, len(plans))
	tagPlans := make([]BranchPlan, 0, len(plans))
	tagDesired := make(map[plumbing.ReferenceName]desiredRef)
	for _, plan := range plans {
		if plan.Kind == RefKindTag {
			tagPlans = append(tagPlans, plan)
			if desired, ok := desiredRefs[plan.TargetRef]; ok {
				tagDesired[plan.TargetRef] = desired
			}
			continue
		}
		if !plan.SourceRef.IsBranch() || !plan.TargetRef.IsBranch() {
			return result, fmt.Errorf("bootstrap batching currently supports branch refs and create-only tags")
		}
		planRefs = append(planRefs, desiredRef{
			Kind:       plan.Kind,
			Label:      plan.Branch,
			SourceRef:  plan.SourceRef,
			TargetRef:  plan.TargetRef,
			SourceHash: plan.SourceHash,
		})
	}

var (
		batches []bootstrapBatch
		err     error
	)
	if len(planRefs) > 0 {
		progressf(cfg.Verbose, "bootstrap-batch: planning checkpoints for %d branch ref(s)", len(planRefs))
		batches, err = planBootstrapBatches(ctx, cfg, sourceConn, sourceService, planRefs, targetRefs)
		if err != nil {
			return result, err
		}
	}

batchLimit := cfg.BatchMaxPackBytes
	if cfg.MaxPackBytes > 0 && (batchLimit == 0 || cfg.MaxPackBytes < batchLimit) {
		batchLimit = cfg.MaxPackBytes
	}

for _, batch := range batches {
		result.PlannedBatchCount += len(batch.Checkpoints)
		result.TempRefs = append(result.TempRefs, batch.TempRef.String())
		progressf(
			cfg.Verbose,
			"bootstrap-batch: branch=%s temp-ref=%s planned-batches=%d resume=%s",
			batch.Plan.TargetRef,
			batch.TempRef,
			len(batch.Checkpoints),
			shortHash(batch.ResumeHash),
		)
		current := batch.ResumeHash
		startIdx, err := bootstrapResumeIndex(batch.Checkpoints, batch.ResumeHash)
		if err != nil {
			return result, fmt.Errorf("resume bootstrap batch for %s: %w", batch.Plan.TargetRef, err)
		}
		for idx := startIdx; idx < len(batch.Checkpoints); idx++ {
			checkpoint := batch.Checkpoints[idx]
			progressf(
				cfg.Verbose,
				"bootstrap-batch: branch=%s batch=%d/%d from=%s to=%s",
				batch.Plan.TargetRef,
				idx+1,
				len(batch.Checkpoints),
				shortHash(current),
				shortHash(checkpoint),
			)
			stagePlans := []BranchPlan{
				{
					Branch:     batch.Plan.Branch,
					SourceRef:  batch.Plan.SourceRef,
					TargetRef:  batch.TempRef,
					SourceHash: checkpoint,
					TargetHash: current,
					Kind:       batch.Plan.Kind,
					Action:     actionForTargetHash(current),
					Reason:     fmt.Sprintf("%s -> %s via %s", shortHash(current), shortHash(checkpoint), batch.TempRef),
				},
			}
			if idx == len(batch.Checkpoints)-1 {
				stagePlans = append(stagePlans, BranchPlan{
					Branch:     batch.Plan.Branch,
					SourceRef:  batch.Plan.SourceRef,
					TargetRef:  batch.Plan.TargetRef,
					SourceHash: checkpoint,
					TargetHash: plumbing.ZeroHash,
					Kind:       batch.Plan.Kind,
					Action:     ActionCreate,
					Reason:     fmt.Sprintf("create %s at %s", batch.Plan.TargetRef, shortHash(checkpoint)),
				})
			}

packReader, err := sourceService.FetchPack(ctx, sourceConn, singleDesiredRef(batch.Plan.SourceRef, batch.TempRef, checkpoint), singleHaveMap(current))
			if err != nil {
				return result, fmt.Errorf("fetch source batch pack for %s: %w", batch.Plan.TargetRef, err)
			}
			packReader = limitPackReadCloser(packReader, batchLimit)
			if err := pushPackToTarget(ctx, targetConn, targetAdv, stagePlans, packReader, cfg.Verbose); err != nil {
				return result, fmt.Errorf("push bootstrap batch for %s: %w", batch.Plan.TargetRef, err)
			}
			progressf(
				cfg.Verbose,
				"bootstrap-batch: branch=%s batch=%d/%d complete",
				batch.Plan.TargetRef,
				idx+1,
				len(batch.Checkpoints),
			)
			current = checkpoint
			result.BatchCount++
		}

if current.IsZero() {
			return result, fmt.Errorf("bootstrap batching for %s completed with no checkpoint state", batch.Plan.TargetRef)
		}
		if batch.ResumeHash == batch.Plan.SourceHash {
			if err := pushCommandsToTarget(ctx, targetConn, targetAdv, []BranchPlan{{
				Branch:     batch.Plan.Branch,
				SourceRef:  batch.Plan.SourceRef,
				TargetRef:  batch.Plan.TargetRef,
				SourceHash: batch.Plan.SourceHash,
				TargetHash: plumbing.ZeroHash,
				Kind:       batch.Plan.Kind,
				Action:     ActionCreate,
				Reason:     fmt.Sprintf("create %s at %s", batch.Plan.TargetRef, shortHash(batch.Plan.SourceHash)),
			}}, cfg.Verbose); err != nil {
				return result, fmt.Errorf("resume bootstrap cutover for %s: %w", batch.Plan.TargetRef, err)
			}
		}

deleteTempPlan := BranchPlan{
			Branch:     batch.Plan.Branch,
			TargetRef:  batch.TempRef,
			SourceHash: plumbing.ZeroHash,
			TargetHash: current,
			Kind:       batch.Plan.Kind,
			Action:     ActionDelete,
			Reason:     fmt.Sprintf("delete temp ref %s", batch.TempRef),
		}
		if err := pushCommandsToTarget(ctx, targetConn, targetAdv, []BranchPlan{deleteTempPlan}, cfg.Verbose); err != nil {
			return result, fmt.Errorf("delete bootstrap temp ref for %s: %w", batch.Plan.TargetRef, err)
		}
		progressf(cfg.Verbose, "bootstrap-batch: branch=%s finalized", batch.Plan.TargetRef)
	}

if len(tagPlans) > 0 {
		progressf(cfg.Verbose, "bootstrap-batch: pushing %d tag(s) after branch batches", len(tagPlans))
		tagTargetRefs := copyRefHashMap(targetRefs)
		for _, batch := range batches {
			tagTargetRefs[batch.Plan.TargetRef] = batch.Plan.SourceHash
		}
		packReader, err := sourceService.FetchPack(ctx, sourceConn, tagDesired, tagTargetRefs)
		if err != nil {
			if !errors.Is(err, git.NoErrAlreadyUpToDate) {
				return result, fmt.Errorf("fetch bootstrap tag pack: %w", err)
			}
		} else {
			defer packReader.Close()
			packReader = limitPackReadCloser(packReader, cfg.MaxPackBytes)
			if err := pushPackToTarget(ctx, targetConn, targetAdv, tagPlans, packReader, cfg.Verbose); err != nil {
				return result, fmt.Errorf("push bootstrap tags: %w", err)
			}
		}
	}

result.Pushed = len(plans)
	result.Batching = true
	result.RelayMode = "bootstrap-batch"
	result.Stats = stats.snapshot()
	return result, nil
}

func actionForTargetHash(hash plumbing.Hash) Action {
	if hash.IsZero() {
		return ActionCreate
	}
	return ActionUpdate
}

func singleDesiredRef(sourceRef, targetRef plumbing.ReferenceName, hash plumbing.Hash) map[plumbing.ReferenceName]desiredRef {
	return map[plumbing.ReferenceName]desiredRef{
		targetRef: {
			Kind:       RefKindBranch,
			Label:      targetRef.Short(),
			SourceRef:  sourceRef,
			TargetRef:  targetRef,
			SourceHash: hash,
		},
	}
}

func singleHaveMap(hash plumbing.Hash) map[plumbing.ReferenceName]plumbing.Hash {
	if hash.IsZero() {
		return nil
	}
	return map[plumbing.ReferenceName]plumbing.Hash{
		plumbing.ReferenceName("refs/gitsync/have"): hash,
	}
}

func bootstrapTempRef(targetRef plumbing.ReferenceName) plumbing.ReferenceName {
	return plumbing.ReferenceName("refs/gitsync/bootstrap/heads/" + targetRef.Short())
}

func planBootstrapBatches(
	ctx context.Context,
	cfg Config,
	sourceConn *transportConn,
	sourceService *sourceRefService,
	desired []desiredRef,
	targetRefs map[plumbing.ReferenceName]plumbing.Hash,
) ([]bootstrapBatch, error) {
	out := make([]bootstrapBatch, 0, len(desired))
	for _, ref := range desired {
		checkpoints, err := planBootstrapBranchCheckpoints(ctx, cfg, sourceConn, sourceService, ref)
		if err != nil {
			return nil, err
		}
		out = append(out, bootstrapBatch{
			Plan: BranchPlan{
				Branch:     ref.Label,
				SourceRef:  ref.SourceRef,
				TargetRef:  ref.TargetRef,
				SourceHash: ref.SourceHash,
				Kind:       ref.Kind,
				Action:     ActionCreate,
			},
			TempRef:     bootstrapTempRef(ref.TargetRef),
			ResumeHash:  targetRefs[bootstrapTempRef(ref.TargetRef)],
			Checkpoints: checkpoints,
		})
	}
	return out, nil
}

func planBootstrapBranchCheckpoints(
	ctx context.Context,
	cfg Config,
	sourceConn *transportConn,
	sourceService *sourceRefService,
	ref desiredRef,
) ([]plumbing.Hash, error) {
	progressf(cfg.Verbose, "bootstrap-batch: fetching commit graph for %s", ref.TargetRef)
	graphRepo, err := git.Init(memory.NewStorage(), nil)
	if err != nil {
		return nil, fmt.Errorf("init bootstrap planning repository: %w", err)
	}
	if err := fetchSourceCommitGraphV2(ctx, graphRepo, sourceConn, sourceService.v2, ref); err != nil {
		return nil, fmt.Errorf("fetch bootstrap planning graph for %s: %w", ref.TargetRef, err)
	}

chain, err := firstParentChain(graphRepo, ref.SourceHash)
	if err != nil {
		return nil, fmt.Errorf("walk first-parent chain for %s: %w", ref.TargetRef, err)
	}
	if len(chain) == 0 {
		return nil, fmt.Errorf("empty first-parent chain for %s", ref.TargetRef)
	}

checkpoints := make([]plumbing.Hash, 0, len(chain))
	prevIdx := -1
	prevHash := plumbing.ZeroHash
	prevSpan := 0
	for prevIdx < len(chain)-1 {
		bestIdx, err := largestCheckpointUnderLimit(ctx, cfg, sourceConn, sourceService, ref, chain, prevIdx, prevHash, prevSpan)
		if err != nil {
			return nil, err
		}
		if bestIdx <= prevIdx {
			return nil, fmt.Errorf("could not find bootstrap checkpoint for %s under batch-max-pack-bytes=%d", ref.TargetRef, cfg.BatchMaxPackBytes)
		}
		prevSpan = bestIdx - prevIdx
		prevIdx = bestIdx
		prevHash = chain[bestIdx]
		checkpoints = append(checkpoints, prevHash)
		progressf(
			cfg.Verbose,
			"bootstrap-batch: branch=%s planned-checkpoint=%s selected=%d chain-len=%d",
			ref.TargetRef,
			shortHash(prevHash),
			len(checkpoints),
			len(chain),
		)
	}
	return checkpoints, nil
}

func largestCheckpointUnderLimit(
	ctx context.Context,
	cfg Config,
	sourceConn *transportConn,
	sourceService *sourceRefService,
	ref desiredRef,
	chain []plumbing.Hash,
	prevIdx int,
	prevHash plumbing.Hash,
	prevSpan int,
) (int, error) {
	return sampledCheckpointUnderLimitByProbe(chain, prevIdx, prevSpan, func(idx int) (bool, error) {
		tooLarge, err := sourcePackExceedsLimit(ctx, sourceConn, sourceService, ref, chain[idx], prevHash, cfg.BatchMaxPackBytes)
		if err != nil {
			return false, fmt.Errorf("measure bootstrap batch for %s at %s: %w", ref.TargetRef, shortHash(chain[idx]), err)
		}
		if tooLarge {
			progressf(cfg.Verbose, "bootstrap-batch: sample %s exceeds limit=%d", shortHash(chain[idx]), cfg.BatchMaxPackBytes)
		} else {
			progressf(cfg.Verbose, "bootstrap-batch: sample %s fits limit=%d", shortHash(chain[idx]), cfg.BatchMaxPackBytes)
		}
		return tooLarge, nil
	})
}

func sampledCheckpointUnderLimitByProbe(
	chain []plumbing.Hash,
	prevIdx int,
	prevSpan int,
	probe func(idx int) (bool, error),
) (int, error) {
	lo := prevIdx + 1
	hi := len(chain) - 1
	if lo > hi {
		return -1, nil
	}

tooLarge, err := probe(lo)
	if err != nil {
		return -1, err
	}
	if tooLarge {
		return -1, nil
	}
	return lo, nil
}

func sampledCheckpointCandidates(lo, hi int, prevSpan int) []int {
	if lo > hi {
		return nil
	}

set := map[int]struct{}{}
	add := func(idx int) {
		if idx < lo {
			idx = lo
		}
		if idx > hi {
			idx = hi
		}
		set[idx] = struct{}{}
	}

projected := hi
	if prevSpan > 0 {
		projected = lo + prevSpan - 1
	}
	add(projected)

func firstParentChain(repo *git.Repository, tip plumbing.Hash) ([]plumbing.Hash, error) {
	commit, err := repo.CommitObject(tip)
	if err != nil {
		return nil, err
	}
	reversed := make([]plumbing.Hash, 0, 128)
	for {
		reversed = append(reversed, commit.Hash)
		if len(commit.ParentHashes) == 0 {
			break
		}
		commit, err = repo.CommitObject(commit.ParentHashes[0])
		if err != nil {
			return nil, err
		}
	}

chain := make([]plumbing.Hash, 0, len(reversed))
	for i := len(reversed) - 1; i >= 0; i-- {
		chain = append(chain, reversed[i])
	}
	return chain, nil
}

func sourcePackExceedsLimit(
	ctx context.Context,
	sourceConn *transportConn,
	sourceService *sourceRefService,
	ref desiredRef,
	want plumbing.Hash,
	have plumbing.Hash,
	limit int64,
) (bool, error) {
	packReader, err := sourceService.FetchPack(ctx, sourceConn, singleDesiredRef(ref.SourceRef, ref.TargetRef, want), singleHaveMap(have))
	if err != nil {
		return false, err
	}
	defer packReader.Close()
	_, err = io.Copy(io.Discard, limitPackReadCloser(packReader, limit))
	if err == nil {
		return false, nil
	}
	if strings.Contains(err.Error(), "source pack exceeded max-pack-bytes limit") {
		return true, nil
	}
	return false, err
}

func bootstrapResumeIndex(checkpoints []plumbing.Hash, resumeHash plumbing.Hash) (int, error) {
	if resumeHash.IsZero() {
		return 0, nil
	}
	for idx, checkpoint := range checkpoints {
		if checkpoint == resumeHash {
			return idx + 1, nil
		}
	}
	return 0, fmt.Errorf("temp ref hash %s does not match any planned checkpoint", resumeHash)
}

func selectBranches(source map[string]plumbing.Hash, requested []string) map[string]plumbing.Hash {
	if len(requested) == 0 {
		return source
	}

selected := make(map[string]plumbing.Hash, len(requested))
	for _, branch := range requested {
		if hash, ok := source[branch]; ok {
			selected[branch] = hash
		}
	}
	return selected
}

func buildDesiredRefs(sourceRefs map[plumbing.ReferenceName]plumbing.Hash, cfg Config) (map[plumbing.ReferenceName]desiredRef, map[plumbing.ReferenceName]managedTarget, error) {
	desired := make(map[plumbing.ReferenceName]desiredRef)
	managed := make(map[plumbing.ReferenceName]managedTarget)

addManaged := func(sourceRef, targetRef plumbing.ReferenceName, kind RefKind, hash plumbing.Hash) error {
		if hash.IsZero() {
			return fmt.Errorf("source ref %s not found", sourceRef)
		}
		short := targetRef.Short()
		desired[targetRef] = desiredRef{
			Kind:       kind,
			Label:      short,
			SourceRef:  sourceRef,
			TargetRef:  targetRef,
			SourceHash: hash,
		}
		managed[targetRef] = managedTarget{Kind: kind, Label: short}
		return nil
	}

if len(cfg.Mappings) > 0 {
		for _, mapping := range cfg.Mappings {
			sourceRef, targetRef, kind, err := normalizeMapping(mapping)
			if err != nil {
				return nil, nil, err
			}
			if err := addManaged(sourceRef, targetRef, kind, sourceRefs[sourceRef]); err != nil {
				return nil, nil, err
			}
		}
	} else {
		branches := branchMapFromRefHashMap(sourceRefs)
		selected := selectBranches(branches, cfg.Branches)
		for branch, hash := range selected {
			refName := plumbing.NewBranchReferenceName(branch)
			if err := addManaged(refName, refName, RefKindBranch, hash); err != nil {
				return nil, nil, err
			}
		}
	}

return desired, managed, nil
}

func normalizeMapping(mapping RefMapping) (plumbing.ReferenceName, plumbing.ReferenceName, RefKind, error) {
	src := strings.TrimSpace(mapping.Source)
	dst := strings.TrimSpace(mapping.Target)
	if src == "" || dst == "" {
		return "", "", "", fmt.Errorf("invalid mapping %q:%q", mapping.Source, mapping.Target)
	}

if strings.HasPrefix(src, "refs/") || strings.HasPrefix(dst, "refs/") {
		sourceRef := plumbing.ReferenceName(src)
		targetRef := plumbing.ReferenceName(dst)
		kind := refKindFromName(targetRef)
		if kind == "" {
			return "", "", "", fmt.Errorf("unsupported mapped ref kind: %s -> %s", src, dst)
		}
		return sourceRef, targetRef, kind, nil
	}

return plumbing.NewBranchReferenceName(src), plumbing.NewBranchReferenceName(dst), RefKindBranch, nil
}

func refKindFromName(name plumbing.ReferenceName) RefKind {
	switch {
	case name.IsBranch():
		return RefKindBranch
	case name.IsTag():
		return RefKindTag
	default:
		return ""
	}
}

type desiredRef struct {
	Kind       RefKind
	Label      string
	SourceRef  plumbing.ReferenceName
	TargetRef  plumbing.ReferenceName
	SourceHash plumbing.Hash
}

type managedTarget struct {
	Kind  RefKind
	Label string
}

func buildPlans(
	repo *git.Repository,
	desired map[plumbing.ReferenceName]desiredRef,
	targetRefs map[plumbing.ReferenceName]plumbing.Hash,
	managed map[plumbing.ReferenceName]managedTarget,
	cfg Config,
) ([]BranchPlan, error) {
	if cfg.Prune {
		for targetRef := range targetRefs {
			if _, ok := managed[targetRef]; ok {
				continue
			}
			switch {
			case targetRef.IsTag() && cfg.IncludeTags:
				managed[targetRef] = managedTarget{Kind: RefKindTag, Label: targetRef.Short()}
			case targetRef.IsBranch() && len(cfg.Mappings) == 0 && len(cfg.Branches) == 0:
				managed[targetRef] = managedTarget{Kind: RefKindBranch, Label: targetRef.Short()}
			}
		}
	}

plans := make([]BranchPlan, 0, len(targetNames)+8)
	for _, targetRef := range targetNames {
		info := managed[targetRef]
		want, existsInDesired := desired[targetRef]
		targetHash, existsOnTarget := targetRefs[targetRef]

plan, err := planRef(repo, want, targetHash, cfg.Force)
		if err != nil {
			return nil, err
		}
		plans = append(plans, plan)
	}

sort.Slice(plans, func(i, j int) bool {
		return plans[i].TargetRef.String() < plans[j].TargetRef.String()
	})
	return plans, nil
}

func planRef(repo *git.Repository, want desiredRef, targetHash plumbing.Hash, force bool) (BranchPlan, error) {
	plan := BranchPlan{
		Branch:     want.Label,
		SourceRef:  want.SourceRef,
		TargetRef:  want.TargetRef,
		SourceHash: want.SourceHash,
		TargetHash: targetHash,
		Kind:       want.Kind,
	}

if want.SourceHash == targetHash {
		plan.Action = ActionSkip
		plan.Reason = fmt.Sprintf("%s already current", shortHash(want.SourceHash))
		return plan, nil
	}

sourceCommit, err := repo.CommitObject(want.SourceHash)
	if err != nil {
		return plan, fmt.Errorf("load source commit for %s: %w", want.TargetRef, err)
	}

isFF, err := reachesCommitHash(repo.Storer, sourceCommit, targetHash)
	if err != nil {
		return plan, fmt.Errorf("check fast-forward for %s: %w", want.TargetRef, err)
	}
	if isFF {
		plan.Action = ActionUpdate
		plan.Reason = fmt.Sprintf("%s -> %s", shortHash(targetHash), shortHash(want.SourceHash))
		return plan, nil
	}

if force {
		plan.Action = ActionUpdate
		plan.Reason = fmt.Sprintf("%s -> %s (force)", shortHash(targetHash), shortHash(want.SourceHash))
		return plan, nil
	}

plan.Action = ActionBlock
	plan.Reason = fmt.Sprintf("%s is not an ancestor of %s", shortHash(targetHash), shortHash(want.SourceHash))
	return plan, nil
}

func planBranch(repo *git.Repository, branch string, sourceHash, targetHash plumbing.Hash) (BranchPlan, error) {
	return planRef(repo, desiredRef{
		Kind:       RefKindBranch,
		Label:      branch,
		SourceRef:  plumbing.NewBranchReferenceName(branch),
		TargetRef:  plumbing.NewBranchReferenceName(branch),
		SourceHash: sourceHash,
	}, targetHash, false)
}

func fetchSourceRefsWithHavesV1(
	ctx context.Context,
	repo *git.Repository,
	conn *transportConn,
	sourceAdv *packp.AdvRefs,
	desired map[plumbing.ReferenceName]desiredRef,
	targetRefs map[plumbing.ReferenceName]plumbing.Hash,
) error {
	session, err := conn.transport.NewUploadPackSession(conn.endpoint, conn.authMethod())
	if err != nil {
		return fmt.Errorf("open source upload-pack session: %w", err)
	}
	defer session.Close()

req := packp.NewUploadPackRequestFromCapabilities(sourceAdv.Capabilities)
	for _, ref := range desired {
		req.Wants = append(req.Wants, ref.SourceHash)
	}
	req.Wants = sortedUniqueHashes(req.Wants)
	req.Haves = sortedUniqueHashes(mapsRefValues(targetRefs))
	if len(req.Wants) == 0 {
		return git.NoErrAlreadyUpToDate
	}
	if sourceAdv.Capabilities.Supports(capability.NoProgress) {
		_ = req.Capabilities.Set(capability.NoProgress)
	}
	if desiredHasTag(desired) && sourceAdv.Capabilities.Supports(capability.IncludeTag) {
		_ = req.Capabilities.Set(capability.IncludeTag)
	}
	conn.stats.addWantsHaves("source upload-pack", len(req.Wants), len(req.Haves))

if err := packfile.UpdateObjectStorage(repo.Storer, buildSidebandIfSupported(req.Capabilities, reader, nil)); err != nil {
		return fmt.Errorf("store source packfile: %w", err)
	}

for _, ref := range desired {
		localRef := plumbing.ReferenceName(localBranchRef(sourceRemoteName, ref.TargetRef.Short()))
		if ref.Kind == RefKindTag {
			localRef = plumbing.ReferenceName("refs/remotes/" + sourceRemoteName + "/tags/" + ref.TargetRef.Short())
		}
		if err := repo.Storer.SetReference(plumbing.NewHashReference(localRef, ref.SourceHash)); err != nil {
			return fmt.Errorf("set local source ref %s: %w", ref.SourceRef, err)
		}
	}
	return nil
}

func fetchSourcePackV1(
	ctx context.Context,
	conn *transportConn,
	sourceAdv *packp.AdvRefs,
	desired map[plumbing.ReferenceName]desiredRef,
	targetRefs map[plumbing.ReferenceName]plumbing.Hash,
) (io.ReadCloser, error) {
	session, err := conn.transport.NewUploadPackSession(conn.endpoint, conn.authMethod())
	if err != nil {
		return nil, fmt.Errorf("open source upload-pack session: %w", err)
	}

req := packp.NewUploadPackRequestFromCapabilities(sourceAdv.Capabilities)
	for _, ref := range desired {
		req.Wants = append(req.Wants, ref.SourceHash)
	}
	req.Wants = sortedUniqueHashes(req.Wants)
	req.Haves = sortedUniqueHashes(mapsRefValues(targetRefs))
	if len(req.Wants) == 0 {
		_ = session.Close()
		return nil, git.NoErrAlreadyUpToDate
	}
	if sourceAdv.Capabilities.Supports(capability.NoProgress) {
		_ = req.Capabilities.Set(capability.NoProgress)
	}
	if desiredHasTag(desired) && sourceAdv.Capabilities.Supports(capability.IncludeTag) {
		_ = req.Capabilities.Set(capability.IncludeTag)
	}
	conn.stats.addWantsHaves("source upload-pack", len(req.Wants), len(req.Haves))

reader, err := session.UploadPack(ctx, req)
	if err != nil {
		_ = session.Close()
		if errors.Is(err, transport.ErrEmptyUploadPackRequest) {
			return nil, git.NoErrAlreadyUpToDate
		}
		return nil, fmt.Errorf("source upload-pack: %w", err)
	}
	return &sessionReadCloser{
		Reader: buildSidebandIfSupported(req.Capabilities, reader, nil),
		closeFn: func() error {
			_ = reader.Close()
			return session.Close()
		},
	}, nil
}

func desiredHasTag(desired map[plumbing.ReferenceName]desiredRef) bool {
	for _, ref := range desired {
		if ref.Kind == RefKindTag {
			return true
		}
	}
	return false
}

func pushToTarget(
	ctx context.Context,
	repo *git.Repository,
	conn *transportConn,
	targetAdv *packp.AdvRefs,
	plans []BranchPlan,
	targetRefs map[plumbing.ReferenceName]plumbing.Hash,
	verbose bool,
) error {
	session, err := conn.transport.NewReceivePackSession(conn.endpoint, conn.authMethod())
	if err != nil {
		return fmt.Errorf("open target receive-pack session: %w", err)
	}
	defer session.Close()

req := packp.NewReferenceUpdateRequestFromCapabilities(targetAdv.Capabilities)
	req.Progress = progressWriter(verbose)
	if targetAdv.Capabilities.Supports(capability.Sideband64k) {
		_ = req.Capabilities.Set(capability.Sideband64k)
	} else if targetAdv.Capabilities.Supports(capability.Sideband) {
		_ = req.Capabilities.Set(capability.Sideband)
	}

commands := make([]*packp.Command, 0, len(plans))
	objects := make([]plumbing.Hash, 0, len(plans))
	hasDelete := false
	hasUpdates := false
	for _, plan := range plans {
		cmd := &packp.Command{
			Name: plan.TargetRef,
			Old:  targetRefs[plan.TargetRef],
		}
		switch plan.Action {
		case ActionCreate, ActionUpdate:
			cmd.New = plan.SourceHash
			objects = append(objects, plan.SourceHash)
			hasUpdates = true
		case ActionDelete:
			cmd.New = plumbing.ZeroHash
			hasDelete = true
		}
		commands = append(commands, cmd)
	}
	req.Commands = commands
	conn.stats.addCommands("target receive-pack", len(commands))
	if hasDelete {
		if !targetAdv.Capabilities.Supports(capability.DeleteRefs) {
			return fmt.Errorf("target does not support delete-refs")
		}
		_ = req.Capabilities.Set(capability.DeleteRefs)
	}

hashesToPush, err := objectsToPush(repo.Storer, objects, targetRefs)
	if err != nil {
		return fmt.Errorf("compute objects to push: %w", err)
	}

report, err := receivePack(ctx, session, repo.Storer, req, hashesToPush, hasUpdates, !targetAdv.Capabilities.Supports(capability.OFSDelta))
	if err != nil {
		return err
	}
	if report != nil {
		if err := report.Error(); err != nil {
			return err
		}
	}
	return nil
}

func pushPackToTarget(
	ctx context.Context,
	conn *transportConn,
	targetAdv *packp.AdvRefs,
	plans []BranchPlan,
	pack io.ReadCloser,
	verbose bool,
) error {
	session, err := conn.transport.NewReceivePackSession(conn.endpoint, conn.authMethod())
	if err != nil {
		return fmt.Errorf("open target receive-pack session: %w", err)
	}
	defer session.Close()

commands := make([]*packp.Command, 0, len(plans))
	for _, plan := range plans {
		cmd := &packp.Command{
			Name: plan.TargetRef,
			Old:  plan.TargetHash,
		}
		switch plan.Action {
		case ActionCreate, ActionUpdate:
			cmd.New = plan.SourceHash
		default:
			return fmt.Errorf("streamed pack push only supports create and update actions")
		}
		commands = append(commands, cmd)
	}
	req.Commands = commands
	conn.stats.addCommands("target receive-pack", len(commands))

report, err := receivePackStream(ctx, session, req, pack)
	if err != nil {
		return err
	}
	if report != nil {
		if err := report.Error(); err != nil {
			return err
		}
	}
	return nil
}

func pushCommandsToTarget(
	ctx context.Context,
	conn *transportConn,
	targetAdv *packp.AdvRefs,
	plans []BranchPlan,
	verbose bool,
) error {
	session, err := conn.transport.NewReceivePackSession(conn.endpoint, conn.authMethod())
	if err != nil {
		return fmt.Errorf("open target receive-pack session: %w", err)
	}
	defer session.Close()

commands := make([]*packp.Command, 0, len(plans))
	hasDelete := false
	for _, plan := range plans {
		cmd := &packp.Command{
			Name: plan.TargetRef,
			Old:  plan.TargetHash,
		}
		switch plan.Action {
		case ActionCreate, ActionUpdate:
			cmd.New = plan.SourceHash
		case ActionDelete:
			cmd.New = plumbing.ZeroHash
			hasDelete = true
		default:
			return fmt.Errorf("command-only target push does not support %s", plan.Action)
		}
		commands = append(commands, cmd)
	}
	req.Commands = commands
	conn.stats.addCommands("target receive-pack", len(commands))
	if hasDelete {
		if !targetAdv.Capabilities.Supports(capability.DeleteRefs) {
			return fmt.Errorf("target does not support delete-refs")
		}
		_ = req.Capabilities.Set(capability.DeleteRefs)
	}

report, err := receivePack(ctx, session, nil, req, nil, false, false)
	if err != nil {
		return err
	}
	if report != nil {
		if err := report.Error(); err != nil {
			return err
		}
	}
	return nil
}

func receivePack(
	ctx context.Context,
	session transport.ReceivePackSession,
	store storer.Storer,
	req *packp.ReferenceUpdateRequest,
	hashes []plumbing.Hash,
	sendPack bool,
	useRefDeltas bool,
) (*packp.ReportStatus, error) {
	if !sendPack {
		return session.ReceivePack(ctx, req)
	}

rd, wr := io.Pipe()
	req.Packfile = rd
	done := make(chan error, 1)

report, err := session.ReceivePack(ctx, req)
	if err != nil {
		_ = rd.Close()
		return nil, err
	}
	if err := <-done; err != nil {
		return nil, err
	}
	return report, nil
}

func receivePackStream(
	ctx context.Context,
	session transport.ReceivePackSession,
	req *packp.ReferenceUpdateRequest,
	pack io.ReadCloser,
) (*packp.ReportStatus, error) {
	req.Packfile = pack
	report, err := session.ReceivePack(ctx, req)
	if err != nil {
		_ = pack.Close()
		return nil, err
	}
	return report, pack.Close()
}

func objectsToPush(store storer.Storer, wants []plumbing.Hash, targetRefs map[plumbing.ReferenceName]plumbing.Hash) ([]plumbing.Hash, error) {
	targetHaves := sortedUniqueHashes(mapsRefValues(targetRefs))
	if len(wants) == 0 {
		return nil, nil
	}

haveSet := make(map[plumbing.Hash]struct{}, len(targetHaves))
	for _, hash := range targetHaves {
		haveSet[hash] = struct{}{}
	}

filteredWants := make([]plumbing.Hash, 0, len(wants))
	for _, hash := range sortedUniqueHashes(wants) {
		if _, ok := haveSet[hash]; ok {
			continue
		}
		filteredWants = append(filteredWants, hash)
	}
	if len(filteredWants) == 0 {
		return nil, nil
	}

seen := make(map[plumbing.Hash]bool, len(filteredWants)*4)
	objects := make([]plumbing.Hash, 0, len(filteredWants)*16)
	for _, hash := range filteredWants {
		if err := collectPushObjects(store, hash, haveSet, seen, &objects); err != nil {
			return nil, err
		}
	}
	return objects, nil
}

func collectPushObjects(
	store storer.EncodedObjectStorer,
	hash plumbing.Hash,
	externalHaves map[plumbing.Hash]struct{},
	seen map[plumbing.Hash]bool,
	out *[]plumbing.Hash,
) error {
	if hash.IsZero() {
		return nil
	}
	if _, ok := externalHaves[hash]; ok {
		return nil
	}
	if seen[hash] {
		return nil
	}
	seen[hash] = true

obj, err := store.EncodedObject(plumbing.AnyObject, hash)
	if err != nil {
		return fmt.Errorf("load object %s: %w", hash, err)
	}

switch obj.Type() {
	case plumbing.CommitObject:
		commit, err := object.GetCommit(store, hash)
		if err != nil {
			return fmt.Errorf("load commit %s: %w", hash, err)
		}
		if err := collectPushObjects(store, commit.TreeHash, externalHaves, seen, out); err != nil {
			return err
		}
		for _, parentHash := range commit.ParentHashes {
			if err := collectPushObjects(store, parentHash, externalHaves, seen, out); err != nil {
				return err
			}
		}
	case plumbing.TreeObject:
		tree, err := object.GetTree(store, hash)
		if err != nil {
			return fmt.Errorf("load tree %s: %w", hash, err)
		}
		for _, entry := range tree.Entries {
			if err := collectPushObjects(store, entry.Hash, externalHaves, seen, out); err != nil {
				return err
			}
		}
	case plumbing.TagObject:
		tag, err := object.GetTag(store, hash)
		if err != nil {
			return fmt.Errorf("load tag %s: %w", hash, err)
		}
		if err := collectPushObjects(store, tag.Target, externalHaves, seen, out); err != nil {
			return err
		}
	case plumbing.BlobObject:
	default:
		return fmt.Errorf("unsupported object type %s for %s", obj.Type(), hash)
	}

*out = append(*out, hash)
	return nil
}

type sessionReadCloser struct {
	io.Reader
	closeFn func() error
}

func (r *sessionReadCloser) Close() error {
	if r.closeFn == nil {
		return nil
	}
	return r.closeFn()
}

func limitPackReadCloser(r io.ReadCloser, maxBytes int64) io.ReadCloser {
	if maxBytes <= 0 {
		return r
	}
	return &packLimitReadCloser{
		ReadCloser: r,
		maxBytes:   maxBytes,
	}
}

type packLimitReadCloser struct {
	io.ReadCloser
	maxBytes int64
	read     int64
}

func (r *packLimitReadCloser) Read(p []byte) (int, error) {
	n, err := r.ReadCloser.Read(p)
	r.read += int64(n)
	if r.read > r.maxBytes {
		return n, fmt.Errorf("source pack exceeded max-pack-bytes limit (%d)", r.maxBytes)
	}
	return n, err
}

func startMeasurement(enabled bool) func() Measurement {
	if !enabled {
		return func() Measurement { return Measurement{} }
	}

start := time.Now()
	var startStats runtime.MemStats
	runtime.ReadMemStats(&startStats)

done := make(chan struct{})
	var (
		mu            sync.Mutex
		peakAlloc     = startStats.Alloc
		peakHeapInuse = startStats.HeapInuse
		result        Measurement
	)

go func() {
		ticker := time.NewTicker(10 * time.Millisecond)
		defer ticker.Stop()
		for {
			select {
			case <-done:
				return
			case <-ticker.C:
				var current runtime.MemStats
				runtime.ReadMemStats(&current)
				mu.Lock()
				if current.Alloc > peakAlloc {
					peakAlloc = current.Alloc
				}
				if current.HeapInuse > peakHeapInuse {
					peakHeapInuse = current.HeapInuse
				}
				mu.Unlock()
			}
		}
	}()

func branchMapFromRefHashMap(refs map[plumbing.ReferenceName]plumbing.Hash) map[string]plumbing.Hash {
	branches := make(map[string]plumbing.Hash)
	for name, hash := range refs {
		if name.IsBranch() {
			branches[name.Short()] = hash
		}
	}
	return branches
}

func refHashMap(refs []*plumbing.Reference) map[plumbing.ReferenceName]plumbing.Hash {
	out := make(map[plumbing.ReferenceName]plumbing.Hash)
	for _, ref := range refs {
		if ref.Type() == plumbing.HashReference {
			out[ref.Name()] = ref.Hash()
		}
	}
	return out
}

func advertisedReferences(ar *packp.AdvRefs) ([]*plumbing.Reference, error) {
	refs, err := ar.AllReferences()
	if err != nil {
		return nil, err
	}

iter, err := refs.IterReferences()
	if err != nil {
		return nil, err
	}
	defer iter.Close()

var out []*plumbing.Reference
	err = iter.ForEach(func(ref *plumbing.Reference) error {
		out = append(out, ref)
		return nil
	})
	return out, err
}

type transportConn struct {
	label     string
	endpoint  *transport.Endpoint
	transport transport.Transport
	http      *http.Client
	raw       Endpoint
	auth      transport.AuthMethod
	stats     *statsCollector
}

func newTransportConn(raw Endpoint, label string, stats *statsCollector) (*transportConn, error) {
	ep, err := transport.NewEndpoint(raw.URL)
	if err != nil {
		return nil, err
	}
	auth, err := resolveAuthMethod(raw, ep)
	if err != nil {
		return nil, err
	}

baseTransport := http.DefaultTransport
	if raw.SkipTLSVerify {
		if cloned, ok := http.DefaultTransport.(*http.Transport); ok {
			transportClone := cloned.Clone()
			if transportClone.TLSClientConfig == nil {
				transportClone.TLSClientConfig = &tls.Config{MinVersion: tls.VersionTLS12}
			}
			transportClone.TLSClientConfig.InsecureSkipVerify = true
			baseTransport = transportClone
		}
	}

httpClient := &http.Client{
		Transport: &countingRoundTripper{
			base:  baseTransport,
			label: label,
			stats: stats,
		},
	}

return &transportConn{
		label:     label,
		endpoint:  ep,
		transport: transporthttp.NewClient(httpClient),
		http:      httpClient,
		raw:       raw,
		auth:      auth,
		stats:     stats,
	}, nil
}

func (c *transportConn) authMethod() transport.AuthMethod {
	return c.auth
}

func applyAuth(req *http.Request, authMethod transport.AuthMethod) {
	switch auth := authMethod.(type) {
	case *transporthttp.BasicAuth:
		auth.SetAuth(req)
	case *transporthttp.TokenAuth:
		auth.SetAuth(req)
	}
}

func reachesCommitHash(store storer.EncodedObjectStorer, start *object.Commit, target plumbing.Hash) (bool, error) {
	if start.Hash == target {
		return true, nil
	}

seen := map[plumbing.Hash]bool{}
	stack := []*object.Commit{start}

for len(stack) > 0 {
		current := stack[len(stack)-1]
		stack = stack[:len(stack)-1]
		if seen[current.Hash] {
			continue
		}
		seen[current.Hash] = true

for _, parentHash := range current.ParentHashes {
			if parentHash == target {
				return true, nil
			}
			if seen[parentHash] {
				continue
			}
			parent, err := object.GetCommit(store, parentHash)
			if err != nil {
				if errors.Is(err, plumbing.ErrObjectNotFound) {
					continue
				}
				return false, err
			}
			stack = append(stack, parent)
		}
	}

return false, nil
}

func mapsRefValues(input map[plumbing.ReferenceName]plumbing.Hash) []plumbing.Hash {
	out := make([]plumbing.Hash, 0, len(input))
	for _, hash := range input {
		if !hash.IsZero() {
			out = append(out, hash)
		}
	}
	return out
}

func copyRefHashMap(input map[plumbing.ReferenceName]plumbing.Hash) map[plumbing.ReferenceName]plumbing.Hash {
	out := make(map[plumbing.ReferenceName]plumbing.Hash, len(input))
	for name, hash := range input {
		out[name] = hash
	}
	return out
}

func sortedUniqueHashes(input []plumbing.Hash) []plumbing.Hash {
	seen := make(map[plumbing.Hash]bool, len(input))
	out := make([]plumbing.Hash, 0, len(input))
	for _, hash := range input {
		if seen[hash] {
			continue
		}
		seen[hash] = true
		out = append(out, hash)
	}
	plumbing.HashesSort(out)
	return out
	return plumbing.NewBranchReferenceName(raw)
}

func countObjects(store storer.EncodedObjectStorer) (int, error) {
2 unmodified lines

return 0, err
	}
	defer iter.Close()

count := 0
	err = iter.ForEach(func(obj plumbing.EncodedObject) error {
	err = iter.ForEach(func(_ plumbing.EncodedObject) error {
		count++
		return nil
	})
	return count, err
}

func localBranchRef(remoteName, branch string) string {
	return plumbing.NewRemoteReferenceName(remoteName, branch).String()
}

func shortHash(hash plumbing.Hash) string {
	if hash.IsZero() {
		return "<zero>"
	}
	value := hash.String()
	if len(value) > 8 {
		return value[:8]
	}
	return value
}

func parseHaveRef(raw string) plumbing.ReferenceName {
	raw = strings.TrimSpace(raw)
	if strings.HasPrefix(raw, "refs/") {
		return plumbing.ReferenceName(raw)
	}
	return plumbing.NewBranchReferenceName(raw)
}

func progressWriter(verbose bool) io.Writer {
	if !verbose {
		return nil
	}
	return os.Stderr
}

func progressf(verbose bool, format string, args ...interface{}) {
	if !verbose {
		return
	}
	fmt.Fprintf(os.Stderr, "[git-sync] %s\n", fmt.Sprintf(format, args...))
}

func (e Endpoint) authMethod() transport.AuthMethod {
	if e.BearerToken != "" {
		return &transporthttp.TokenAuth{Token: e.BearerToken}
	}
	if e.Token != "" {
		username := e.Username
		if username == "" {
			username = "git"
		}
		return &transporthttp.BasicAuth{Username: username, Password: e.Token}
	}
	return nil
}

var gitCredentialFillCommand = func(ctx context.Context, input string) ([]byte, error) {
	cmd := exec.CommandContext(ctx, "git", "credential", "fill")
	cmd.Stdin = strings.NewReader(input)
	return cmd.Output()
}

func resolveAuthMethod(raw Endpoint, ep *transport.Endpoint) (transport.AuthMethod, error) {
	if auth := raw.authMethod(); auth != nil {
		return auth, nil
	}
	if ep == nil {
		return nil, nil
	}
	if ep.Protocol != "http" && ep.Protocol != "https" {
		return nil, nil
	}
	if username, password, ok := lookupEntireDBCredential(raw, ep); ok {
		return &transporthttp.BasicAuth{Username: username, Password: password}, nil
	}
	username, password, ok := lookupGitCredential(ep)
	if !ok {
		return nil, nil
	}
	return &transporthttp.BasicAuth{Username: username, Password: password}, nil
}

func lookupEntireDBCredential(raw Endpoint, ep *transport.Endpoint) (string, string, bool) {
	if ep == nil || ep.Host == "" {
		return "", "", false
	}
	credHost := endpointCredentialHost(ep)
	token, ok := lookupEntireDBToken(credHost, endpointBaseURL(ep), raw.SkipTLSVerify)
	if !ok || token == "" {
		return "", "", false
	}
	username := raw.Username
	if username == "" {
		username = "git"
	}
	return username, token, true
}

func lookupEntireDBToken(host, baseURL string, skipTLSVerify bool) (string, bool) {
	configDir := os.Getenv("ENTIRE_CONFIG_DIR")
	if configDir == "" {
		home, err := os.UserHomeDir()
		if err != nil {
			return "", false
		}
		configDir = filepath.Join(home, ".config", "entire")
	}

username, ok := loadEntireDBActiveUser(host, configDir)
	if !ok || username == "" {
		return "", false
	}
	token, err := getEntireDBTokenWithRefresh(context.Background(), host, username, baseURL, skipTLSVerify)
	if err != nil {
		return "", false
	}
	if token == "" {
		return "", false
	}
	return token, true
}

func getEntireDBTokenWithRefresh(ctx context.Context, host, username, baseURL string, skipTLSVerify bool) (string, error) {
	encodedToken, err := readEntireDBStoredToken(entireCredentialService(host), username)
	if err != nil {
		return "", err
	}
	token, expiresAt := decodeTokenWithExpiration(encodedToken)
	if token == "" {
		return "", nil
	}
	if !tokenExpiredOrExpiring(expiresAt) {
		return token, nil
	}
	refreshed, err := refreshEntireDBAccessToken(ctx, host, username, baseURL, skipTLSVerify)
	if err != nil {
		return token, nil
	}
	return refreshed, nil
}

func decodeTokenWithExpiration(encoded string) (string, time.Time) {
	idx := strings.LastIndex(encoded, "|")
	if idx == -1 {
		return encoded, time.Time{}
	}
	token := encoded[:idx]
	expiresAtUnix, err := strconv.ParseInt(encoded[idx+1:], 10, 64)
	if err != nil {
		return encoded, time.Time{}
	}
	return token, time.Unix(expiresAtUnix, 0)
}

func tokenExpiredOrExpiring(expiresAt time.Time) bool {
	if expiresAt.IsZero() {
		return true
	}
	return time.Now().Add(5 * time.Minute).After(expiresAt)
}

func refreshEntireDBAccessToken(ctx context.Context, host, username, baseURL string, skipTLSVerify bool) (string, error) {
	refreshToken, err := readEntireDBStoredToken(entireCredentialService(host)+":refresh", username)
	if err != nil {
		return "", err
	}
	if refreshToken == "" || baseURL == "" {
		return "", errors.New("missing refresh token or base url")
	}

form := url.Values{}
	form.Set("grant_type", "refresh_token")
	form.Set("refresh_token", refreshToken)
	form.Set("client_id", entireCLIClientID)

client := &http.Client{
		Timeout: 30 * time.Second,
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: skipTLSVerify}, //nolint:gosec
		},
	}
	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("refresh failed with status %d", resp.StatusCode)
	}

if err := writeEntireDBStoredToken(
		entireCredentialService(host),
		username,
		encodeTokenWithExpiration(tokenResp.AccessToken, tokenResp.ExpiresIn),
	); err != nil {
		return "", err
	}
	if tokenResp.RefreshToken != "" {
		_ = writeEntireDBStoredToken(entireCredentialService(host)+":refresh", username, tokenResp.RefreshToken)
	}
	return tokenResp.AccessToken, nil
}

func encodeTokenWithExpiration(token string, expiresIn int64) string {
	return fmt.Sprintf("%s|%d", token, time.Now().Unix()+expiresIn)
}

func entireCredentialService(host string) string {
	return "entire:" + host
}

func readEntireDBStoredToken(service, username string) (string, error) {
	if os.Getenv("ENTIRE_TOKEN_STORE") == "file" {
		path := os.Getenv("ENTIRE_TOKEN_STORE_PATH")
		if path == "" {
			home, err := os.UserHomeDir()
			if err != nil {
				return "", err
			}
			path = filepath.Join(home, ".config", "entiredb", "tokens.json")
		}
		return readEntireDBFileToken(path, service, username)
	}
	return keyring.Get(service, username)
}

func writeEntireDBStoredToken(service, username, password string) error {
	if os.Getenv("ENTIRE_TOKEN_STORE") == "file" {
		path := os.Getenv("ENTIRE_TOKEN_STORE_PATH")
		if path == "" {
			home, err := os.UserHomeDir()
			if err != nil {
				return err
			}
			path = filepath.Join(home, ".config", "entiredb", "tokens.json")
		}
		return writeEntireDBFileToken(path, service, username, password)
	}
	return keyring.Set(service, username, password)
}

func readEntireDBFileToken(path, service, username string) (string, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		if os.IsNotExist(err) {
			return "", keyring.ErrNotFound
		}
		return "", err
	}
	var store map[string]map[string]string
	if err := json.Unmarshal(data, &store); err != nil {
		return "", err
	}
	users := store[service]
	if users == nil {
		return "", keyring.ErrNotFound
	}
	password, ok := users[username]
	if !ok {
		return "", keyring.ErrNotFound
	}
	return password, nil
}

func writeEntireDBFileToken(path, service, username, password string) error {
	store := map[string]map[string]string{}
	if data, err := os.ReadFile(path); err == nil {
		if err := json.Unmarshal(data, &store); err != nil {
			return err
		}
	} else if !os.IsNotExist(err) {
		return err
	}
	if store[service] == nil {
		store[service] = map[string]string{}
	}
	store[service][username] = password
	if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
		return err
	}
	data, err := json.Marshal(store)
	if err != nil {
		return err
	}
	return os.WriteFile(path, data, 0o600)
}

func lookupGitCredential(ep *transport.Endpoint) (string, string, bool) {
	input := credentialFillInput(ep)
	if input == "" {
		return "", "", false
	}
	output, err := gitCredentialFillCommand(context.Background(), input)
	if err != nil {
		return "", "", false
	}
	values := parseCredentialFillOutput(output)
	password := values["password"]
	if password == "" {
		return "", "", false
	}
	username := values["username"]
	if username == "" {
		if ep.User != "" {
			username = ep.User
		} else {
			username = "git"
		}
	}
	return username, password, true
}

func credentialFillInput(ep *transport.Endpoint) string {
	if ep == nil || ep.Host == "" {
		return ""
	}
	var builder strings.Builder
	builder.WriteString("protocol=")
	builder.WriteString(ep.Protocol)
	builder.WriteString("\n")
	builder.WriteString("host=")
	builder.WriteString(ep.Host)
	builder.WriteString("\n")
	if path := strings.TrimPrefix(ep.Path, "/"); path != "" {
		builder.WriteString("path=")
		builder.WriteString(path)
		builder.WriteString("\n")
	}
	if ep.User != "" {
		builder.WriteString("username=")
		builder.WriteString(ep.User)
		builder.WriteString("\n")
	}
	builder.WriteString("\n")
	return builder.String()
}

func parseCredentialFillOutput(output []byte) map[string]string {
	values := map[string]string{}
	for _, line := range bytes.Split(output, []byte{'\n'}) {
		line = bytes.TrimSpace(line)
		if len(line) == 0 {
			continue
		}
		key, value, ok := bytes.Cut(line, []byte{'='})
		if !ok {
			continue
		}
		values[string(key)] = string(value)
	}
	return values
}

func buildSidebandIfSupported(l *capability.List, reader io.Reader, p sideband.Progress) io.Reader {
	var t sideband.Type
	switch {
	case l.Supports(capability.Sideband):
		t = sideband.Sideband
	case l.Supports(capability.Sideband64k):
		t = sideband.Sideband64k
	default:
		return reader
	}

d := sideband.NewDemuxer(t, reader)
	d.Progress = p
	return d
}

type statsCollector struct {
	enabled bool
	items   map[string]*ServiceStats
}

func newStats(enabled bool) *statsCollector {
	return &statsCollector{enabled: enabled, items: map[string]*ServiceStats{}}
}

func (s *statsCollector) addWantsHaves(name string, wants, haves int) {
	if !s.enabled {
		return
	}
	item := s.ensure(name)
	item.Wants += wants
	item.Haves += haves
}

func (s *statsCollector) addCommands(name string, commands int) {
	if !s.enabled {
		return
	}
	item := s.ensure(name)
	item.Commands += commands
}

func (s *statsCollector) recordRoundTrip(name string, requestBytes, responseBytes int64) {
	if !s.enabled {
		return
	}
	item := s.ensure(name)
	item.Requests++
	item.RequestBytes += requestBytes
	item.ResponseBytes += responseBytes
}

func (s *statsCollector) snapshot() Stats {
	out := Stats{Enabled: s.enabled, Items: map[string]*ServiceStats{}}
	for key, item := range s.items {
		copyItem := *item
		out.Items[key] = &copyItem
	}
	return out
}

type countingRoundTripper struct {
	base  http.RoundTripper
	label string
	stats *statsCollector
}

func (rt *countingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
	res, err := rt.base.RoundTrip(req)
	if err != nil {
		return nil, err
	}

serviceName := req.Header.Get(statsPhaseHdr)
	if serviceName == "" {
		serviceName = req.URL.Query().Get("service")
		if serviceName == "" {
			serviceName = strings.TrimPrefix(req.URL.Path[strings.LastIndex(req.URL.Path, "/")+1:], "/")
		}
	}
	name := strings.TrimSpace(rt.label + " " + serviceName)
	requestBytes := req.ContentLength
	if requestBytes < 0 {
		requestBytes = 0
	}

res.Body = &countingReadCloser{
		ReadCloser: res.Body,
		onClose: func(n int64) {
			rt.stats.recordRoundTrip(name, requestBytes, n)
		},
	}
	return res, nil
}

type countingReadCloser struct {
	io.ReadCloser
	n       int64
	onClose func(int64)
}

func (c *countingReadCloser) Read(p []byte) (int, error) {
	n, err := c.ReadCloser.Read(p)
	c.n += int64(n)
	return n, err
}

func (c *countingReadCloser) Close() error {
	err := c.ReadCloser.Close()
	if c.onClose != nil {
		c.onClose(c.n)
		c.onClose = nil
	}
	return err
}
```

Minternal/syncer/syncer.go+373/-2803

```
1
2
3
4
5
6
7
8
4
10
5
12
13
14
15
6
7
8
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
9
157
10
11
12
159
13
14
161
15
16
17
18
3 unmodified lines

22
23
24
171
25
26
27
173
28
29
175
30
31
32
33
34
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

package syncer

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"slices"
	"testing"
	"time"

git "github.com/go-git/go-git/v5"
	"github.com/go-git/go-git/v5/plumbing"
	"github.com/go-git/go-git/v5/plumbing/object"
	"github.com/go-git/go-git/v5/storage/memory"
	bstrap "github.com/soph/git-sync/internal/strategy/bootstrap"
)

func TestSelectBranches(t *testing.T) {
	source := map[string]plumbing.Hash{
		"main": plumbing.NewHash("1111111111111111111111111111111111111111"),
		"dev":  plumbing.NewHash("2222222222222222222222222222222222222222"),
	}

got := selectBranches(source, []string{"dev", "missing"})
	if len(got) != 1 || got["dev"] != source["dev"] {
		t.Fatalf("unexpected branch selection: %#v", got)
	}
}

func TestPlanBranchSkip(t *testing.T) {
	hash := plumbing.NewHash("1111111111111111111111111111111111111111")
	plan, err := planBranch(nil, "main", hash, hash)
	if err != nil {
		t.Fatalf("planBranch returned error: %v", err)
	}
	if plan.Action != ActionSkip {
		t.Fatalf("expected skip, got %s", plan.Action)
	}
}

func TestPlanBranchCreate(t *testing.T) {
	repo, err := git.Init(memory.NewStorage(), nil)
	if err != nil {
		t.Fatalf("init repo: %v", err)
	}
	sourceHash := seedCommit(t, repo, nil)

plan := BranchPlan{
		Branch:     "main",
		SourceHash: sourceHash,
		Action:     ActionCreate,
	}

if plan.Action != ActionCreate {
		t.Fatalf("expected create")
	}
}

func TestPlanBranchFastForwardAndBlock(t *testing.T) {
	repo, err := git.Init(memory.NewStorage(), nil)
	if err != nil {
		t.Fatalf("init repo: %v", err)
	}

root := seedCommit(t, repo, nil)
	next := seedCommit(t, repo, []plumbing.Hash{root})
	side := seedCommit(t, repo, []plumbing.Hash{root})

ffPlan, err := planBranch(repo, "main", next, root)
	if err != nil {
		t.Fatalf("planBranch fast-forward: %v", err)
	}
	if ffPlan.Action != ActionUpdate {
		t.Fatalf("expected update, got %s", ffPlan.Action)
	}

blockPlan, err := planBranch(repo, "main", side, next)
	if err != nil {
		t.Fatalf("planBranch block: %v", err)
	}
	if blockPlan.Action != ActionBlock {
		t.Fatalf("expected block, got %s", blockPlan.Action)
	}
}

func seedCommit(t *testing.T, repo *git.Repository, parents []plumbing.Hash) plumbing.Hash {
	t.Helper()

now := time.Now().UTC()

obj := repo.Storer.NewEncodedObject()
	commit := &object.Commit{
		Author: object.Signature{
			Name:  "test",
			Email: "test@example.com",
			When:  now,
		},
		Committer: object.Signature{
			Name:  "test",
			Email: "test@example.com",
			When:  now,
		},
		Message:      fmt.Sprintf("test-%d-%d", len(parents), now.UnixNano()),
		TreeHash:     plumbing.ZeroHash,
		ParentHashes: parents,
	}

if err := commit.Encode(obj); err != nil {
		t.Fatalf("encode commit: %v", err)
	}
	hash, err := repo.Storer.SetEncodedObject(obj)
	if err != nil {
		t.Fatalf("store commit: %v", err)
	}
	return hash
}

func TestSampledCheckpointUnderLimitByProbe(t *testing.T) {
	chain := make([]plumbing.Hash, 40)
	for i := range chain {
		chain[i] = plumbing.NewHash(fmt.Sprintf("%040x", i+1))
	}

var probes []int
	best, err := sampledCheckpointUnderLimitByProbe(chain, 4, 8, func(idx int) (bool, error) {
		probes = append(probes, idx)
		return idx > 19, nil
	})
	if err != nil {
		t.Fatalf("sampledCheckpointUnderLimitByProbe: %v", err)
	}
	if best < 12 || best > 19 {
		t.Fatalf("expected a reasonable sampled checkpoint, got %d", best)
	}
	if len(probes) > 6 {
		t.Fatalf("expected fixed small probe count, got %d probes: %v", len(probes), probes)
	}
}

func TestGitHubOwnerRepo(t *testing.T) {
	conn, err := newTransportConn(Endpoint{URL: "https://github.com/torvalds/linux.git"}, "source", newStats(false))
	stats := newStats(false)
	conn, err := newConn(Endpoint{URL: "https://github.com/torvalds/linux.git"}, "source", stats)
	if err != nil {
		t.Fatalf("new transport conn: %v", err)
		t.Fatalf("new conn: %v", err)
	}
	owner, repo, ok := githubOwnerRepo(conn)
	owner, repo, ok := bstrap.GitHubOwnerRepo(conn)
	if !ok {
		t.Fatalf("expected github owner/repo match")
	}
3 unmodified lines

}

func TestGitHubOwnerRepoRejectsNonGitHubSource(t *testing.T) {
	conn, err := newTransportConn(Endpoint{URL: "https://gitlab.com/group/project.git"}, "source", newStats(false))
	stats := newStats(false)
	conn, err := newConn(Endpoint{URL: "https://gitlab.com/group/project.git"}, "source", stats)
	if err != nil {
		t.Fatalf("new transport conn: %v", err)
		t.Fatalf("new conn: %v", err)
	}
	if _, _, ok := githubOwnerRepo(conn); ok {
	if _, _, ok := bstrap.GitHubOwnerRepo(conn); ok {
		t.Fatalf("expected non-github source to be rejected")
	}
}

func TestGitHubBootstrapBatchMaxPackBytesLargeRepo(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/repos/torvalds/linux" {
			t.Fatalf("unexpected path: %s", r.URL.Path)
		}
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(fmt.Sprintf(`{"size":%d}`, githubLargeRepoThresholdKB+1)))
	}))
	defer server.Close()

originalAPIBaseURL := githubRepoAPIBaseURL
	githubRepoAPIBaseURL = server.URL
	t.Cleanup(func() {
		githubRepoAPIBaseURL = originalAPIBaseURL
	})

conn, err := newTransportConn(Endpoint{URL: "https://github.com/torvalds/linux.git"}, "source", newStats(false))
	if err != nil {
		t.Fatalf("new transport conn: %v", err)
	}

batchLimit, ok := githubBootstrapBatchMaxPackBytes(context.Background(), Config{}, conn, &sourceRefService{
		protocol: protocolModeV2,
		v2: &v2CapabilityAdvertisement{Capabilities: map[string]string{
			"fetch": "thin-pack filter",
		}},
	})
	if !ok {
		t.Fatalf("expected github preflight to select batched mode")
	}
	if batchLimit != defaultAutoBatchMaxPackBytes {
		t.Fatalf("unexpected batch limit: %d", batchLimit)
	}
}

func TestGitHubBootstrapBatchMaxPackBytesSkipsSmallRepo(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{"size":1024}`))
	}))
	defer server.Close()

originalAPIBaseURL := githubRepoAPIBaseURL
	githubRepoAPIBaseURL = server.URL
	t.Cleanup(func() {
		githubRepoAPIBaseURL = originalAPIBaseURL
	})

conn, err := newTransportConn(Endpoint{URL: "https://github.com/octocat/Hello-World.git"}, "source", newStats(false))
	if err != nil {
		t.Fatalf("new transport conn: %v", err)
	}

if _, ok := githubBootstrapBatchMaxPackBytes(context.Background(), Config{}, conn, &sourceRefService{
		protocol: protocolModeV2,
		v2: &v2CapabilityAdvertisement{Capabilities: map[string]string{
			"fetch": "thin-pack filter",
		}},
	}); ok {
		t.Fatalf("expected small github repo to keep single-pack bootstrap")
	}
}
```

Minternal/syncer/syncer\_test.go+9/-216
