Fix Remote Helper Dry-Run Push Issue

Claude Code·Fable 5.[1m]·pjbgf·2mo ago·49min·1 Checkpoint·3 file changes·+247/-67·88.8K tokens

The remote helper fails to dry run pushes as per Linear ticket ENT-1199:

Root cause

The bug is in git-remote-entire (the entireio/cli repo), not the server. handlePush in internal/remotehelper/githelper/push.go unconditionally POSTs to /git-receive-pack even when there is nothing to send — which is exactly what happens on every --dry-run push.

The full chain:

  1. git push --dry-run origin :cli-test drives the helper with option dry-run true, which the helper forwards as --dry-run to git send-pack --stateless-rpc --helper-status --stdin (options.go:54-56).
  2. In stateless-rpc mode, upstream send-pack guards the entire request emission with !args->dry_run — on a dry run it writes no receive-pack request at all. I reproduced this on git 2.54.0 by feeding send-pack the exact bytes the helper feeds it: its stdout is just an outer flush packet followed immediately by the helper-status line — 0000ok refs/heads/cli-test\n. A real (non-dry-run) deletion, by contrast, emits a proper command pktline first. This holds for any dry-run push, not just deletions — I verified a branch-update dry run produces the same empty request.
  3. gitproto.ReadSendPackRequest consumes that flush and returns an empty body; AppendAgentToReceivePackRequest passes empty input through unchanged; handlePush then POSTs the zero-byte body (push.go:133) and wraps the failure as the observed posting receive-pack: server error (HTTP 400): empty request body.
  4. The server (server/githttp/receive_pack.go:400 in this repo) deliberately rejects zero-byte bodies with 400 — a documented choice so that helper retries after an already-landed push don't page or trip replica failover. It does accept a flush-only body gracefully, but the helper sends literally zero bytes, since the flush belonged to send-pack's outer framing.
  5. Upstream remote-curl.c (which handlePush mirrors) handles this case explicitly: its rpc_service loop reads the first packet from send-pack and breaks without ever calling post_rpc when it's a flush. That's the behavior the helper failed to copy. (GitHub "working" in the repro is over SSH, so it never hits this path at all — but C git over HTTPS also works, thanks to that skip.)

Where the fix belongs

In entireio/cli push.go: when requestBody is empty after ReadSendPackRequest, skip the POST (and close respCh so the feeder goroutine exits). One trap for whoever implements it: in this case the helper must also skip the trailing-flush drain at push.go:153-159 — the single 0000 already consumed is the only flush send-pack emits on a dry run (the trailing packet_flush is guarded by cmds_sent), so the next bytes on stdout are the helper-status lines themselves. Blindly reading 4 more bytes would consume ok r and fail with "expected trailing flush".

Sketch a fix

2mo ago·3m

Confirmed the analysis against the code. Three facts shape the fix:

  • gitproto.ReadSendPackRequest (gitproto.go:244) returns cleanly on the outer flush with nothing written to dst — so on a dry run requestBody.Len() == 0 and push.go:133 POSTs zero bytes.
  • The feeder goroutine already handles a close(respCh)-without-send (push.go:100-104): it reports nil to feedErr and exits, so the skip path needs no goroutine changes.
  • Two existing invariant tests (TestInvariant_HelperStatusSurfacedOnSendPackError, TestInvariant_PushReusesListForPushAdvertisement in invariants_test.go) use shell stubs that emit an empty request followed by a trailing flush — a wire shape real send-pack never produces (trailing flush is guarded by cmds_sent). These stubs will need adjusting alongside the fix.

Sketch

In handlePush, branch after ReadSendPackRequest and move the POST and the trailing-flush drain into the non-empty arm:

Everything downstream stays shared and unchanged: helper-status relay works because on a dry run send-pack's remaining stdout is exactly the status lines; sp.Wait() returns 0 (dry-run success) or non-zero (all-rejected batch), and the existing relay-before-error ordering already surfaces error <ref> <reason> lines for the rejected case. The doc comment at the top of handlePush (steps 5–6 of the protocol flow) should gain a sentence about this branch.

Why the empty check is the right predicate (not opts.dryRun)

Keying off body emptiness rather than the dry-run option matches remote-curl's behavior and also covers the second producer of empty requests: a batch where send-pack rejects every update client-side (non-fast-forward without force) — cmds_sent stays 0, nothing is emitted, and the helper-status error lines follow directly. Keying off opts.dryRun would fix the ticket but leave that path broken, and would break if a future send-pack ever emitted something on dry runs.

Tests

  1. New invariant test (invariants_test.go), following the existing shell-stub pattern: stub git that emits only 0000 then ok refs/heads/cli-test\n — no second flush — and exits 0. Drive handlePush with &Options{dryRun: true} (the option is cosmetic here; the stub defines the wire shape) and a fakeTransport. Assert: err == nil, len(ft.rpcCalls) == 0 (no POST), and stdout is the status line plus the terminating blank line. A sibling case with error refs/... non-fast-forward + exit 1 pins the all-rejected batch.
  2. Fix the two existing stubs that emit 0000 (empty request) + 0000 (trailing flush): after this change that shape reads the second 0000 as part of helper-status and relays it to git. Since TestInvariant_HelperStatusSurfacedOnSendPackError models a server-side rejection (where real send-pack does send a request), the faithful fix is to make those stubs emit a minimal non-empty wrapped request before the trailing flush; the lazier alternative is dropping their second 0000. I'd do the former so the stubs keep matching real wire shapes.
  3. Optionally, an end-to-end check at the server integration layer (git push --dry-run for both a ref update and a deletion against a test server) — that's where the original repro lived, and it confirms git prints the usual (dry run) summary with helper exit 0.

One more trap worth noting for the implementer: AppendAgentToReceivePackRequest moves inside the else-branch in this sketch. That's deliberate — on the empty path there's no request to amend, and keeping it outside would force the awkward "amend empty, then check empty" ordering.

go ahead

2mo ago·14.1s

Base directory for this skill: /home/coder/.claude/plugins/cache/claude-plugins-official/superpowers/5.1.0/skills/test-driven-development

Test-Driven Development (TDD)

Overview

Write the test first. Watch it fail. Write minimal code to pass.

Core principle: If you didn't watch the test fail, you don't know if it tests the right thing.

Violating the letter of the rules is violating the spirit of the rules.

When to Use

Always:

  • New features
  • Bug fixes
  • Refactoring
  • Behavior changes

Exceptions (ask your human partner):

  • Throwaway prototypes
  • Generated code
  • Configuration files

Thinking "skip TDD just this once"? Stop. That's rationalization.

The Iron Law

Write code before the test? Delete it. Start over.

No exceptions:

  • Don't keep it as "reference"
  • Don't "adapt" it while writing tests
  • Don't look at it
  • Delete means delete

Implement fresh from tests. Period.

Red-Green-Refactor

RED - Write Failing Test

Write one minimal test showing what should happen.

<Good> ```typescript test('retries failed operations 3 times', async () => { let attempts = 0; const operation = () => { attempts++; if (attempts < 3) throw new Error('fail'); return 'success'; };

const result = await retryOperation(operation);

expect(result).toBe('success'); expect(attempts).toBe(3); });

Vague name, tests mock not code </Bad>

Requirements:

  • One behavior
  • Clear name
  • Real code (no mocks unless unavoidable)

Verify RED - Watch It Fail

MANDATORY. Never skip.

Confirm:

  • Test fails (not errors)
  • Failure message is expected
  • Fails because feature missing (not typos)

Test passes? You're testing existing behavior. Fix test.

Test errors? Fix error, re-run until it fails correctly.

GREEN - Minimal Code

Write simplest code to pass the test.

<Good> ```typescript async function retryOperation<T>(fn: () => Promise<T>): Promise<T> { for (let i = 0; i < 3; i++) { try { return await fn(); } catch (e) { if (i === 2) throw e; } } throw new Error('unreachable'); } ``` Just enough to pass </Good> <Bad> ```typescript async function retryOperation<T>( fn: () => Promise<T>, options?: { maxRetries?: number; backoff?: 'linear' | 'exponential'; onRetry?: (attempt: number) => void; } ): Promise<T> { // YAGNI } ``` Over-engineered </Bad>

Don't add features, refactor other code, or "improve" beyond the test.

Verify GREEN - Watch It Pass

MANDATORY.

Confirm:

  • Test passes
  • Other tests still pass
  • Output pristine (no errors, warnings)

Test fails? Fix code, not test.

Other tests fail? Fix now.

REFACTOR - Clean Up

After green only:

  • Remove duplication
  • Improve names
  • Extract helpers

Keep tests green. Don't add behavior.

Repeat

Next failing test for next feature.

Good Tests

QualityGoodBad
MinimalOne thing. "and" in name? Split it.test('validates email and domain and whitespace')
ClearName describes behaviortest('test1')
Shows intentDemonstrates desired APIObscures what code should do

Why Order Matters

"I'll write tests after to verify it works"

Tests written after code pass immediately. Passing immediately proves nothing:

  • Might test wrong thing
  • Might test implementation, not behavior
  • Might miss edge cases you forgot
  • You never saw it catch the bug

Test-first forces you to see the test fail, proving it actually tests something.

"I already manually tested all the edge cases"

Manual testing is ad-hoc. You think you tested everything but:

  • No record of what you tested
  • Can't re-run when code changes
  • Easy to forget cases under pressure
  • "It worked when I tried it" ≠ comprehensive

Automated tests are systematic. They run the same way every time.

"Deleting X hours of work is wasteful"

Sunk cost fallacy. The time is already gone. Your choice now:

  • Delete and rewrite with TDD (X more hours, high confidence)
  • Keep it and add tests after (30 min, low confidence, likely bugs)

The "waste" is keeping code you can't trust. Working code without real tests is technical debt.

"TDD is dogmatic, being pragmatic means adapting"

TDD IS pragmatic:

  • Finds bugs before commit (faster than debugging after)
  • Prevents regressions (tests catch breaks immediately)
  • Documents behavior (tests show how to use code)
  • Enables refactoring (change freely, tests catch breaks)

"Pragmatic" shortcuts = debugging in production = slower.

"Tests after achieve the same goals - it's spirit not ritual"

No. Tests-after answer "What does this do?" Tests-first answer "What should this do?"

Tests-after are biased by your implementation. You test what you built, not what's required. You verify remembered edge cases, not discovered ones.

Tests-first force edge case discovery before implementing. Tests-after verify you remembered everything (you didn't).

30 minutes of tests after ≠ TDD. You get coverage, lose proof tests work.

Common Rationalizations

ExcuseReality
"Too simple to test"Simple code breaks. Test takes 30 seconds.
"I'll test after"Tests passing immediately prove nothing.
"Tests after achieve same goals"Tests-after = "what does this do?" Tests-first = "what should this do?"
"Already manually tested"Ad-hoc ≠ systematic. No record, can't re-run.
"Deleting X hours is wasteful"Sunk cost fallacy. Keeping unverified code is technical debt.
"Keep as reference, write tests first"You'll adapt it. That's testing after. Delete means delete.
"Need to explore first"Fine. Throw away exploration, start with TDD.
"Test hard = design unclear"Listen to test. Hard to test = hard to use.
"TDD will slow me down"TDD faster than debugging. Pragmatic = test-first.
"Manual test faster"Manual doesn't prove edge cases. You'll re-test every change.
"Existing code has no tests"You're improving it. Add tests for existing code.

Red Flags - STOP and Start Over

  • Code before test
  • Test after implementation
  • Test passes immediately
  • Can't explain why test failed
  • Tests added "later"
  • Rationalizing "just this once"
  • "I already manually tested it"
  • "Tests after achieve the same purpose"
  • "It's about spirit not ritual"
  • "Keep as reference" or "adapt existing code"
  • "Already spent X hours, deleting is wasteful"
  • "TDD is dogmatic, I'm being pragmatic"
  • "This is different because..."

All of these mean: Delete code. Start over with TDD.

Example: Bug Fix

Bug: Empty email accepted

RED

Verify RED

GREEN

Verify GREEN

REFACTOR Extract validation for multiple fields if needed.

Verification Checklist

Before marking work complete:

  • Every new function/method has a test
  • Watched each test fail before implementing
  • Each test failed for expected reason (feature missing, not typo)
  • Wrote minimal code to pass each test
  • All tests pass
  • Output pristine (no errors, warnings)
  • Tests use real code (mocks only if unavoidable)
  • Edge cases and errors covered

Can't check all boxes? You skipped TDD. Start over.

When Stuck

ProblemSolution
Don't know how to testWrite wished-for API. Write assertion first. Ask your human partner.
Test too complicatedDesign too complicated. Simplify interface.
Must mock everythingCode too coupled. Use dependency injection.
Test setup hugeExtract helpers. Still complex? Simplify design.

Debugging Integration

Bug found? Write failing test reproducing it. Follow TDD cycle. Test proves fix and prevents regression.

Never fix bugs without a test.

Testing Anti-Patterns

When adding mocks or test utilities, read @testing-anti-patterns.md to avoid common pitfalls:

  • Testing mock behavior instead of real behavior
  • Adding test-only methods to production classes
  • Mocking without understanding dependencies

Final Rule

No exceptions without your human partner's permission.

2mo ago·23m

All green. Final state:

The fix (internal/remotehelper/githelper/push.go): when ReadSendPackRequest yields an empty body — a dry run or an all-rejected batch — handlePush now closes the feeder channel and skips both the POST and the trailing-flush drain, mirroring remote-curl.c:rpc_service, then relays helper-status as before.

Tests (all written first and watched fail):

  • TestInvariant_DryRunPushSkipsReceivePackPOST — stub in dry-run wire shape; asserts no POST and exact stdout.
  • TestInvariant_AllRejectedPushSkipsReceivePackPOST — same empty-request shape via client-side rejection; asserts no POST, error line relayed, send-pack's exit error surfaced.
  • TestInvariant_DryRunPushRealSendPack — drives handlePush with the real git binary against a temp repo; failed pre-fix with the exact production error (expected trailing flush from send-pack, got "ok r"), passes post-fix. This pins the wire-shape assumption against the installed git rather than our model of it.
  • The two pre-existing shell stubs emitted an impossible shape (empty request + trailing flush); they now emit a wrapped one-command request via a new wrappedSendPackRequest helper, and the repeated fake-transport literal was extracted to pushFakeTransport.

Verification: fmt and lint clean; unit (go test ./...), integration, and E2E canary all exited 0; -race passes on ./internal/remotehelper/.... One honest caveat: full-module -race (what mise run test:ci literally runs) cannot complete on this box — the disk hits bursty ENOSPC during race-instrumented linking (SIGBUS in the linker), which cost most of the wall-clock above. CI will run it with proper resources; I've saved a memory note about the workaround.

Proposed commit — files: push.go, invariants_test.go, consts_test.go (the goosWindows const for goconst):

Git identity checks out for DCO (paulo@entire.io). Ready to commit on dry-push when you give the go-ahead (unlock your GPG agent first).

go ahead

2mo ago·18.2s

commit

2mo ago·1m

Committed as f93cfcc on dry-push — 3 files, 247 insertions, 67 deletions. Author and DCO sign-off both match paulo@entire.io, working tree is clean, and the Entire checkpoint trailer was linked by the post-commit hook.

The branch is ready to push whenever you want (lint was run clean on this exact tree, per the pre-push requirement).