git push
[entire] Pushing entire/checkpoints/v1 to origin....
[entire] Syncing entire/checkpoints/v1 with remote....[entire] Detected disconnected session metadata (local and remote share no common ancestor)
[entire] Warning: couldn't sync entire/checkpoints/v1: metadata reconciliation failed: failed to collect local commits: commit chain exceeded 1000 commits without reaching root; aborting reconciliation
Everything up-to-date
The problem seems to be related to having a shallow clone of the checkpoint metadata branch, and for some reason the CLI is losing track of the local commits, which then causes it to think loads of commits are local, when in fact there is only a handful commits locally and the base commit is incorrect. Review the changes and ensure that first the tests confirm the problem, and then secondly that the fix fixes it.
Assistant· claude-opus-4-8
I'll start by using the systematic-debugging skill since this is a bug investigation, and I need to understand the recent changes and verify both the test coverage and the fix.
Assistant· claude-opus-4-8
Let me investigate the recent changes. I'll look at the commits mentioned and the relevant reconciliation code.
Assistant· claude-opus-4-8
Let me look at the full message of the foundational commit and the key source files.
Assistant· claude-opus-4-8
Let me read the current state of the key files.
Assistant· claude-opus-4-8
Now let me find hasReachableShallowBoundary, the key new helper.
Assistant· claude-opus-4-8
Now let me read the tests that were added to confirm the problem.
Assistant· claude-opus-4-8
I now have a thorough understanding of the changes. Let me run the relevant tests to confirm they pass with the current (fixed) code, then verify they actually catch the bug by reverting the fix.
Assistant· claude-opus-4-8
Tests pass. Now let me verify they actually catch the bug by temporarily reverting the fix to old behavior.
Assistant· claude-opus-4-8
The test catches the root cause. Let me revert the temporary change.
Assistant· claude-opus-4-8
The unit test catches the root cause. Now let me check the broader picture — the user's described symptom ("thinks loads of commits are local when there's only a handful") and the "exceeded 1000 commits" error come from the reconcile path. Let me check the git history of the shallow-boundary handling in collectCommitChain to understand the full fix scope.
Assistant· claude-opus-4-8
The shallow-boundary handling in collectCommitChain was an earlier separate fix (449c77710). The current "last commits" (eaada8378 onward) add the detection-level suppression. Let me verify the collectCommitChain test also catches its bug by reverting that handling.
Assistant· claude-opus-4-8
Let me empirically confirm my model of the production scenario (local complete/deep, only the remote tip shallow-bounded) with a scratch repo before deciding on test additions.
Assistant· claude-opus-4-8
Confirmed. The production scenario relies entirely on the remote-tip shallow check: rev-list L does not reach the shallow boundary (local is complete), only rev-list C does. The existing test TestMetadataDisconnected_ShallowSuppressesFalsePositive marks both tips shallow, so it doesn't isolate this — it would still pass even if the suppression only checked the local hash. That's a test-quality gap. Let me confirm that gap, then close it.
Let me look at the clone helpers first.
Assistant· claude-opus-4-8
Now let me confirm the gap empirically: temporarily make the suppression check only the local hash, and verify the existing test still passes (which would prove it doesn't guard the production case).
Assistant· claude-opus-4-8
Gap confirmed — with the regression (checking only the local hash), the existing test still passes. It doesn't guard the production scenario. Let me revert the regression and add a faithful test.
Assistant· claude-opus-4-8
Now I'll write the faithful reproduction tests using TDD. Let me add them after the existing detection tests.
Assistant· claude-opus-4-8
Now let me run the new tests against the current (fixed) code — they should pass.
Assistant· claude-opus-4-8
Both pass. Now let me verify the new tests catch the regressions. First, the "only check local hash" regression (the gap):
Assistant· claude-opus-4-8
Both new tests catch the local-only regression the existing test missed. Let me revert to the correct code and run the full reconcile suite to confirm nothing is broken.
Assistant· claude-opus-4-8
All pass. The diagnostic hint at line 373 is in pre-existing unchanged code (loadShallowHashes). Let me run fmt and lint to be sure my test additions are clean.
Assistant· claude-opus-4-8
Lint clean. Now let me verify the rest of the fix's tests (doctor deepen path, ref-scoped fetch) pass as part of the complete review.
Assistant· claude-opus-4-8
MetadataHistoryShallowBounded is exported and used by doctor to gate the deepen, but has no direct test. Let me check how it's wired and whether the doctor path is tested.
Assistant· claude-opus-4-8
The doctor wiring is sound. The core fix is now well-covered. Let me run the full strategy package test suite to confirm nothing regressed.
Assistant· claude-opus-4-8
Let me confirm my temporary edits to the source file are fully reverted (only test additions should remain).
Assistant· claude-opus-4-8
Only the test file changed; the source is back to its committed state. Here's my review.
Review summary
The fix is correct and the root-cause diagnosis matches your description. The chain was:
Checkpoint metadata (entire/checkpoints/v1) is routinely shallow — FetchMetadataTreeOnly fetches the tip with --depth=1 and nothing deepens it.
On a shallow clone, git merge-base reports "no common ancestor" whenever the real ancestor lives below the shallow boundary (git has no objects there).
isDisconnected trusted that exit code as proof of disconnection → a normal diverged-but-behind branch was misread as disconnected → the doomed full-history cherry-pick reconcile fired → collectCommitChain blew the 1000-commit cap. Exactly the Everything up-to-date + exceeded 1000 commits symptom you hit.
The fix (metadataDisconnected) suppresses a merge-base miss when the metadata history reaches a shallow boundary, and doctor deepens first (gated, --deepen-scoped) so genuine disconnections are still caught.
Did the tests confirm the problem?
I verified by reverting the fix in-place:
TestMetadataDisconnected_ShallowSuppressesFalsePositivefails when metadataDisconnected is reverted to the old isDisconnected-only behavior. ✓ It genuinely reproduces the root cause.
TestCollectCommitChain_StopsAtShallowBoundary / _DepthLimit cover the walk respecting .git/shallow and the cap.
Gap I found and closed
The existing detection test marks both the local and remote tips shallow. But the real incident is local complete/deep, only the freshly-fetched remote tip shallow-bounded — I confirmed this in a scratch repo: rev-list <localTip> never touches the boundary, so the suppression depends entirely on the remote-hash check. I proved the gap: a regression that checks only the local hash (hasReachableShallowBoundary(..., localHash)) still passed the existing test, yet would leave production broken.
I added two tests that close it (both fail under that regression, both pass with the fix):
TestMetadataDisconnected_ShallowRemoteTipDeepLocal — production-faithful detection case; asserts the local chain alone doesn't reach the boundary, isolating the remote-hash contribution.
User
I moved the new tests to the main branch as I want to run them there. Fix the build errors
Assistant· claude-opus-4-8
The tests were moved to main, which doesn't have the fix — so they reference functions that don't exist yet (metadataDisconnected, possibly hasReachableShallowBoundary). Let me see the current build errors and what symbols exist on main.
Assistant· claude-opus-4-8
metadataDisconnected and gitRunnerInDir don't exist on main (they're part of the fix). hasReachableShallowBoundary, collectCommitChain, isDisconnected, loadShallowHashes all exist. Let me read the moved tests to see exactly what needs adjusting.
Assistant· claude-opus-4-8
The moved tests reference two things that don't exist on main (they're part of the fix on the feature branch):
gitRunnerInDir — a test-only helper
metadataDisconnected — the shallow-aware suppression function, which is the fix itself
hasReachableShallowBoundary, isDisconnected, collectCommitChain, and ReconcileDisconnectedMetadataRef all already exist on main.
gitRunnerInDir is trivial to add. But metadataDisconnected is the fix, so how I make it compile changes what the tests prove on main — and that's your call.
Assistant· claude-opus-4-8
Porting the fix to main. Let me read the exact current call sites and the area where I'll add the function.
Assistant· claude-opus-4-8
Now let me add the metadataDisconnected function and wire the two call sites.
Assistant· claude-opus-4-8
The doctor.go on main also references strategy.MetadataHistoryShallowBounded and DeepenMetadataBranch. Let me check the full scope of what's actually on main vs modified in the working tree.
Assistant· claude-opus-4-8
git status shows the test file is in a merge conflict state (UU = unmerged). The doctor.go diagnostic was stale (grep finds no such reference). Let me inspect the conflict markers in the test file.
Assistant· claude-opus-4-8
No conflict markers remain (content resolved, just not git add-ed). doctor.go is unaffected — that diagnostic was stale. Now let me wire the second call site in ReconcileDisconnectedMetadataRef and add the gitRunnerInDir helper.
Assistant· claude-opus-4-8
Now add the gitRunnerInDir helper to the test file. Let me read the top of the test file to place it after the existing ref helpers.
Assistant· claude-opus-4-8
Now let me verify the build compiles for both packages.
Assistant· claude-opus-4-8
Build is clean. Now let me run the tests to confirm they pass with the ported fix.
Assistant· claude-opus-4-8
All 22 tests pass with the ported fix. Let me run fmt and lint to confirm the tree is CI-clean.
Assistant· claude-opus-4-8
Build errors fixed. Here's what I did to port the strategy-level fix to main:
Production code (cmd/entire/cli/strategy/metadata_reconcile.go):
Added metadataDisconnected(ctx, repo, repoPath, localHash, remoteHash) — the shallow-aware wrapper that suppresses a git merge-base miss when the metadata history reaches a shallow boundary.
Wired both callers to it instead of calling isDisconnected directly: IsMetadataDisconnected (warn/doctor hot path) and ReconcileDisconnectedMetadataRef (push/doctor fix path).
hasReachableShallowBoundary was already present on main (common.go), so no port needed there.
Test code (metadata_reconcile_test.go):
Added the gitRunnerInDir helper used by the four shallow-clone tests.
Verification:
go build ./cmd/entire/cli/... — clean (the earlier doctor.go diagnostic was stale; doctor.go on main doesn't reference the deepen helpers).
All 22 reconcile/disconnect tests pass, including the two I added (TestMetadataDisconnected_ShallowRemoteTipDeepLocal, TestReconcileDisconnected_ShallowCloneNoOps).
mise run fmt + mise run lint — 0 issues.
Two things to flag:
I only ported the strategy-level fix — the part the tests and build needed. The original branch also had doctor changes (DeepenMetadataBranch, MetadataHistoryShallowBounded, ref-scoped --deepen, the post-deepen repo reopen). Those aren't required for the build or these tests and main's doctor.go doesn't reference them, so I left them out. Say the word if you want the doctor-side fix on main too.
The test file is still in an unmerged state (git status shows both modified: ...metadata_reconcile_test.go — UU). Content is resolved and builds/passes, but git still considers the merge unfinished. You'll want to git add it to mark it resolved. I didn't stage or commit anything.
User
How does IsMetadataDisconnected differ from metadataDisconnected?
Assistant· claude-opus-4-8
They operate at different layers — one resolves refs, the other does the actual ancestry decision.
IsMetadataDisconnected (exported, metadata_reconcile.go:31) — the ref-resolving entry point:
Takes a repo + a remoteRefName.
Resolves the local ref from checkpoint.ResolveCommittedRefs(ctx).Primary and looks up the remote ref by name.
Handles the "nothing to compare" cases early, returning false (connected):
local ref missing → false
remote ref missing → false
both hashes equal → false
Only once it has two distinct, existing hashes does it delegate to metadataDisconnected.
metadataDisconnected (unexported, metadata_reconcile.go:212) — the decision logic on two concrete hashes:
Takes repo, repoPath, and the two hash strings directly (no ref lookup, no equality/missing checks).
Runs isDisconnected (git merge-base).
If merge-base finds an ancestor → false.
If merge-base misses, it doesn't trust that blindly: it calls hasReachableShallowBoundary. If either history reaches a .git/shallow boundary, the miss is treated as a false positive (shallow clone hiding the real ancestor) → returns false and logs a debug line. Only a miss on a non-shallow history returns true.
In short:IsMetadataDisconnected = "figure out which two commits to compare, and short-circuit the trivial cases," then hands off to metadataDisconnected = "given these two commits, are they genuinely disconnected, accounting for shallow clones."
metadataDisconnected is also called directly by ReconcileDisconnectedMetadataRef, which does its own ref resolution (with different missing-ref semantics — it returns early with nil rather than a false verdict), so the shared decision logic was factored out into metadataDisconnected rather than living inside IsMetadataDisconnected.
User
What entire commands need the commits DAG for the metadata branch? Or in other words, what commands (or actions) can be affected by this?
Assistant· claude-opus-4-8
Good question — this determines the blast radius. Let me trace which code paths actually walk the metadata DAG (merge-base, rev-list, parent-chain walks) versus just reading the tip tree, and map them back to commands.
Assistant· claude-opus-4-8
Let me map these entry points to actual commands/hooks. Let me look at the surrounding context for the less obvious ones.
Assistant· claude-opus-4-8
Let me trace the top-level command entry points for ListCheckpoints, the condensation hook, and the metadata fetch.
Assistant· claude-opus-4-8
I have the full call graph now. Here's the precise picture.
Key distinction: tip-tree reads vs. DAG walks
Almost all checkpoint reads only need the tip tree of entire/checkpoints/v1 — the sharded <id>/…/metadata.json files at the branch head. Those don't care about ancestry and aren't affected.
Only three kinds of operation walk the commit DAG (merge-base, rev-list, or first-parent chain), and those are what the shallow-clone bug hit:
Commands/actions that do real DAG work (can break)
Command / action
Trigger
DAG work
git push
pre-push hook → push_common.go
fetch → ReconcileDisconnectedMetadataRef (merge-base + collectCommitChain) → merge-base rebase of local-only commits. This is the originally reported failure.
used by resume and dispatch-local; merge-base + replay
Commands that only do the advisory merge-base check (WarnIfMetadataDisconnected)
User
I undid the changes. Create a test that can reproduce the 1000 commit limit symptom based on a shallow clone of the metadata.
Assistant· claude-opus-4-8
Let me first check the actual current state of the code — whether the fix is present or reverted — and the value of MaxCommitTraversalDepth.
Assistant· claude-opus-4-8
The fix is present and committed (git status clean); "undid the changes" meant my earlier test additions. MaxCommitTraversalDepth = 1000.
I'll write a test that reproduces the exact production symptom: a shallow metadata clone where the local branch is deeper than the traversal cap, so the buggy reconcile path walks past 1000 commits and aborts with "commit chain exceeded 1000 commits without reaching root". Let me look at the end of the test file and the existing depth-test pattern for building commits.
Assistant· claude-opus-4-8
Now I'll append the reproduction test. It builds a metadata branch deeper than the 1000-commit traversal cap, marks only the remote tip shallow (as a --depth=1 fetch does), and drives ReconcileDisconnectedMetadataRef.
Assistant· claude-opus-4-8
Now let me run the test against the current (fixed) code — it should pass.
Assistant· claude-opus-4-8
Passes against the fix. Now let me verify it genuinely reproduces the symptom by temporarily reverting the suppression and confirming the exact error appears.
Assistant· claude-opus-4-8
The test reproduces the exact production error: failed to collect local commits: commit chain exceeded 1000 commits without reaching root; aborting reconciliation. Let me revert the temporary change.
Assistant· claude-opus-4-8
Now let me confirm the source is clean and run the test plus fmt/lint.
Assistant· claude-opus-4-8
Let me confirm lint reported zero issues (the grep truncated that line).
Assistant· claude-opus-4-8
Done. The source file is unchanged (only the test file gained the new test), the test passes against the fix, and lint is clean.
What I added
TestReconcileDisconnected_ShallowClone1000CommitSymptom in metadata_reconcile_test.go (plus a small buildEmptyTreeCommit plumbing helper), reproducing the exact reported failure.
Scenario modelled (faithful to the incident):
A shared ancestor B, a remote tip C on top of B, and a local metadata branch deeper than MaxCommitTraversalDepth (1002 commits) on top of B — a normal diverged-but-behind branch.
Only the remote tip is marked shallow (.git/shallow = {C}), exactly what a --depth=1 metadata fetch (resume/explain) produces — severing C→B so git merge-base reports "no common ancestor".
Refs are published as the push hook sees them: local refs/heads/entire/checkpoints/v1 + refs/remotes/origin/entire/checkpoints/v1.
It builds the deep chain via go-git plumbing (loose objects git CLI can read), so 1002 commits cost ~0.15s rather than 1002 git commit spawns.
Verification (both directions):
Against the current fixed code → passes: metadataDisconnected recognises the merge-base miss as a shallow artifact (the remote tip reaches the boundary) and no-ops; the local ref is left untouched.
With the suppression temporarily reverted → fails with the exact production error:
code
failed to collect local commits: commit chain exceeded 1000 commits without reaching root; aborting reconciliation
So it's a true regression guard: red on the bug, green on the fix. A precondition assertion (isDisconnected returns true on the shallow clone) documents that the merge-base miss — the trigger — is genuinely present.
One note: this drives ReconcileDisconnectedMetadataRef directly (the function that emitted the failed to collect local commits wrapper in the reported log). It doesn't spin up the full pre-push hook, so it doesn't assert the surrounding [entire] Warning: couldn't sync… text — that's produced one layer up in push_common.go. If you want the symptom reproduced at that outer layer too, I can add a push-path test, but this one pins the actual point of failure.
User
What parts of the code are proactively doing a shallow clone for the metadata branch?
Assistant· claude-opus-4-8
The only proactive --depth=1 metadata fetch is FetchMetadataTreeOnly, called from one place. Let me find the enclosing function and which commands reach it.
Assistant· claude-opus-4-8
Here's the complete picture — there's exactly one code path that proactively creates a shallow boundary on the metadata branch.
Its own doc comment is explicit: "May leave .git/shallow set; FetchMetadataBranch will undo that when full ancestry is later needed." That .git/shallow entry is precisely what the merge-base false-positive (and the 1000-commit symptom) is built on.
Who triggers it
FetchMetadataTreeOnly has exactly one caller: getMetadataTree (resume.go:319), the "resolve the metadata tip cheaply" helper. It runs the tip-only fetch unconditionally ("always runs so the local lookup below doesn't return stale data"). getMetadataTree is reached from two commands:
entire session attach — via refreshCheckpointRefs (attach.go:453)
entire checkpoint explain (the export/prefix-match path) — via matchCheckpointPrefixWithRemoteFallback (explain_export.go:195)
So a --depth=1 boundary gets planted whenever someone runs entire session attach or entire checkpoint explain and the metadata tree needs resolving from origin. A later git push (or entire doctor) then trips over that boundary — matching the "attach/explain on a fresh machine, then push blows up" sequence.
What is NOT shallow
FetchMetadataBranch (git_operations.go:412) — full fetch (NoFilter: true), and its comment notes it deliberately does not--unshallow (global property → would deepen unrelated branches). resume falls back to this when the tree-only probe is insufficient.
DeepenMetadataBranch (git_operations.go) — the opposite operation: a ref-scoped --deepen that entire doctor runs to undo the shallow boundary before checking for disconnection.
The push path (push_common.go) fetches withoutShallow and explicitly refuses to --unshallow.
Bottom line: the shallow boundary originates solely from FetchMetadataTreeOnly's --depth=1, reached by entire session attach and entire checkpoint explain. Nothing else proactively shallow-fetches the metadata branch.
User
Is there any chance that different commands may be updating the shallow boundaries incorrectly? Otherwise, what could justify sometimes the merge base being completely lost and think that there are thousands of commits locally that are not in the remote?
Assistant· claude-opus-4-8
Good question — this digs past the false-positive into whether the boundary itself gets corrupted. Let me examine how the various fetch paths actually mutate .git/shallow and the local ref, starting with the full fetch implementation (whose doc claims it "undoes" shallowness).
Assistant· claude-opus-4-8
Confirmed: FetchMetadataBranch does a plain fetch (Shallow:false, Unshallow:false) — no --unshallow — yet FetchMetadataTreeOnly's doc claims it "will undo" shallowness. Let me check the deepen depth and the remote.Fetch shallow/deepen handling to complete the picture.
Assistant· claude-opus-4-8
Let me read the orphan-creation path — this is where a disconnected local root can originate.
Assistant· claude-opus-4-8
I've now traced the full picture across the fetch orchestration, the ref-advance logic, and the orphan-creation path. Here's the analysis.
Part 1: Are commands updating .git/shallow incorrectly?
The CLI never hand-edits .git/shallow in production — only git does, via the fetch flags. So the boundaries themselves aren't corrupted. But the orchestration around them has two real defects:
1. The documented "undo shallow" never happens.FetchMetadataTreeOnly's doc says "FetchMetadataBranch will undo that [shallow] when full ancestry is later needed." But FetchMetadataBranch calls fetchMetadataFromOrigin(…, {NoFilter: true}) — Shallow:false, Unshallow:false, Deepen:0. A plain git fetch on a shallow repo does not remove .git/shallow and does not backfill below the boundary. So once any attach/explain plants a --depth=1 boundary, the resume "full-fetch fallback" silently leaves it in place. Shallowness is sticky — nothing in the normal flow ever clears it. Only entire doctor extends it.
2. The only deepen is bounded to 1000.DeepenMetadataBranch uses Deepen: strategy.MaxCommitTraversalDepth (= --deepen=1000), and keeps the repo shallow. If the true fork point sits more than 1000 commits below the boundary, even doctor's deepen won't reach it, so merge-base stays missing and doctor can't authoritatively resolve. The reconcile cap is the same 1000, so the two limits are at least consistent — but both cap out.
Repeated --depth=1 fetches (one per attach/explain) re-pin the boundary to the latest tip; git keeps boundaries still required by a reachable ref, so the local chain's boundary is normally preserved. It's fragile, not actively wrong.
Part 2: What makes merge-base completely lost + thousands of local commits?
That's not the shallow false-positive — that one has a hidden shared ancestor. A complete loss with a deep local line means the two histories genuinely share no ancestor. Two code-grounded mechanisms produce exactly that:
(A) Independent roots — the empty-orphan vector.EnsurePrimaryRef (common.go:456) creates a brand-new empty orphan root whenever the local ref is missing andorigin/entire/checkpoints/v1 isn't present at that instant. The precondition is subtle: at line 462 it only reads the remote-tracking ref when , and if that ref hasn't been populated yet (no fetch, offline, or a skipped/failed bootstrap), stays → line 510 mints a fresh orphan. The user then accumulates (one per ) on that local-only root, while origin carries a root. → merge-base genuinely empty, thousands of local commits absent from remote. This is the canonical disconnection the reconcile was written for.
User
For shallow clones, what would be the impact to always only get the tip on the remote? The way checkpoints are structured it rarely has a conflict.
Assistant· claude-opus-4-8
Good design question. Before answering, let me verify the key assumption that makes "tip-only" safe — whether checkpoint reads address the tip tree only (so squashing history loses nothing) and whether the branch ever deletes entries (which breaks a naive 2-way union).
Assistant· claude-opus-4-8
Reads use the tip tree, not commit ancestry. Let me check the two spots that DO touch v1 commits (Log at 2191, CommitObject at 1772) to see if anything depends on the metadata branch's history shape.
Assistant· claude-opus-4-8
Verified the crux: all checkpoint data reads (ListCommitted → getSessionsBranchTree → WalkCheckpointShards) address the tip tree by sharded path. The commit DAG of entire/checkpoints/v1 is essentially transport, with one exception I found — getCheckpointAuthorFromRef (committed.go:2178) walks the commit log matching "Checkpoint: <id>" subjects to attribute authorship. That's the only thing that depends on commit-per-checkpoint granularity.
So your instinct is sound. Here's the impact assessment.
Why tip-only is viable
The metadata branch behaves like a content-addressed set keyed by shard path (<id[:2]>/<id[2:]>/…). Merging two states is a tree union, not a history replay. That means:
You never need merge-base → the false-positive disconnection problem disappears entirely.
You never walk the local chain → the 1000-commit cap symptom is gone; reconcile becomes O(tree size), not O(history depth).
It works uniformly on shallow and filtered (blob:none) clones: a union tree is built from tree-entry hashes (mode+hash) only — remote blobs aren't needed to construct or push it, and the --depth=1 fetch already brings the tip commit + full tree.
Mechanically it's a collapse of what the code already does: instead of cherryPickOnto applying per-commit deltas, you do oneApplyTreeChanges(remoteTipTree, localTipTree − remoteTipTree) → a single squash-merge commit parented on the remote tip. Push; on rejection, re-fetch tip and retry.
What you lose / must decide
Per-checkpoint author attribution.getCheckpointAuthorFromRef would return empty for squashed checkpoints (no "Checkpoint: <id>" subject survives). Fix: source author from the checkpoint's own metadata.json/session metadata in the tip tree rather than the commit. Worth confirming the field exists there before committing to this — it's the one real behavioral casualty.
Deletions become ambiguous. With only two tips and no base, you can't distinguish "local added X" from "remote deleted X" → a naive union resurrects anything entire clean/cleanup removed on the remote. Options: (a) accept it — a stale checkpoint reappears and gets re-cleaned next cycle (low harm for append-mostly data); or (b) keep tombstones. Given how rarely the branch deletes, (a) is probably fine but should be a conscious choice.
User
go ahead
Assistant· claude-opus-4-8
The fix is reverted (back to isDisconnected directly) — clean baseline for prototyping the alternative. Let me look at the exact helpers I'll build on (ApplyTreeChanges, TreeChange, FlattenTree).
Assistant· claude-opus-4-8
ApplyTreeChanges (full-path changes, nil Entry = delete) and FlattenTree (full-path → entry map) are exactly the primitives I need. Let me confirm FlattenTree's behavior.
Assistant· claude-opus-4-8
Everything checks out: ApplyTreeChanges keys entries by path segment (ignores Entry.Name), so feeding it FlattenTree's full-path entries is safe. I'll build a pure tree-level mergeTipTrees (no ref mutation — easy to test deterministically) plus tests covering the additive case, the disconnected/ancestry-free case (the win), and the two edge cases: delete-resurrection and same-id summary conflict.
Let me write the production file.
Assistant· claude-opus-4-8
Now the test file covering the four scenarios:
Assistant· claude-opus-4-8
Most of those diagnostics are unrelated stale-cache noise in the cli package. The relevant one is mergeTipTrees flagged unused (it's a prototype used only by tests). Let me run the new tests first.
Assistant· claude-opus-4-8
All five pass, demonstrating each behavior. Let me confirm whether the unrelated cli-package errors are pre-existing in the working tree, and lint my new files specifically.
Assistant· claude-opus-4-8
Only my two new files are untracked — the cli-package diagnostics are stale gopls cache noise (the strategy package vets clean). Let me confirm the broader tree builds and run the linter on my package to handle the unused flag.
Assistant· claude-opus-4-8
Lint is clean (0 issues); gofmt already aligned the test file. Let me run fmt + lint once more to confirm a clean final state and re-run the tests.
Assistant· claude-opus-4-8
Done. Prototype is in place, tests green, lint clean.
Pure tree-level set-union keyed by shard path. Reads only the two tip trees — never walks commit ancestry, so it's structurally immune to shallow boundaries, missing merge-bases, and deep histories.
Built on the existing FlattenTree + ApplyTreeChanges primitives (I confirmed ApplyTreeChanges keys by path segment and ignores Entry.Name, so feeding it flattened full-path entries is safe).
Resolution: remote-only kept, local-only added, identical kept, differing → local wins + recorded as conflict. The doc spells out the deletion caveat explicitly.
metadata_merge_test.go — five tests, all passing:
Test
Demonstrates
AdditiveUnion
Common case — unique shards union cleanly, zero conflicts
NoSharedAncestryStillUnions
The win — fully disconnected tips (the merge-base/1000-commit scenario) still merge, because no history is read
DeleteResurrection
Downside, pinned — a remote-deleted shard is resurrected by a base-less union
SameCheckpointConflict
Same checkpoint id on both sides: per-session files union additively; only the summary metadata.json truly conflicts (local-wins, reported)
EmptyRemoteTip
Fresh/absent remote → everything local added
What the edge cases tell us (the policy decisions)
Deletes (DeleteResurrection): a 2-way union can't tell "local added" from "remote deleted" → resurrection. Given how rarely the branch deletes (cleanup only), the cheapest policy is accept it (re-cleaned next cycle); the alternative is tombstones. This is now a conscious choice, not a surprise.
Same-id summary (SameCheckpointConflict): the only genuine same-path conflict is the per-checkpoint summary file — sessions shard out additively. Blind local-wins loses the remote's /session list, so the real implementation should do a merge of that one file (union session list, recompute counts). The list is what a caller would key off to do that.
User
Note that this branch uses linear history so delete resurrection should not really happen. Wire this up.
Assistant· claude-opus-4-8
The user accepts the resurrection trade-off (append-only linear branch). Let me wire the tip-union into the push path. First I need to see the full push flow — how reconcile and the subsequent rebase interact — to wire it correctly.
Assistant· claude-opus-4-8
Now I understand the push flow. The cleanest, lowest-risk wiring: the collectCommitChain blowup happens only in the no-merge-base branch. I'll gate the union to exactly that case — replacing the doomed reconcile while leaving the normal fast-forward/rebase paths (which work and preserve commit granularity) intact. Let me see the enclosing function signature first.
Assistant· claude-opus-4-8
Let me confirm the commit-helper signatures I'll reuse (GetGitAuthorFromRepo, SignCommitBestEffort) and that errNoMergeBase exists.
Assistant· claude-opus-4-8
Now I'll add MergeMetadataTip (union → single linear commit) to the merge file.
Assistant· claude-opus-4-8
Now wire it into the push path — replace the reconcile call and route the no-merge-base case to the union.
Assistant· claude-opus-4-8
Now let me update the stale comment near the fetch (it references the old reconcile walk) and verify the build.
Assistant· claude-opus-4-8
Build and vet are clean; ReconcileDisconnectedMetadataRef is still used by doctor (no dead code). The push-path hints are pre-existing. Now let me check for existing push-flow test coverage to extend, then add tests.
Assistant· claude-opus-4-8
There's an existing harness TestFetchAndRebase_NonBranchRefDisconnected driving the real push function. Let me read it to mirror the pattern for an end-to-end union test.
Assistant· claude-opus-4-8
The existing TestFetchAndRebase_NonBranchRefDisconnected already drives the no-merge-base path — which now routes through my union. That's good E2E coverage I can confirm. Let me check which commit-building helpers currently exist (my earlier additions were reverted) before writing tests.
Assistant· claude-opus-4-8
All existing push tests pass with the new wiring — the disconnected case now flows through the union and the diverged/fast-forward paths are unchanged. Let me add MergeMetadataTip unit tests.
Assistant· claude-opus-4-8
I introduced a comment/function name mismatch on the last test. Let me fix it.
Assistant· claude-opus-4-8
Now run the full merge test suite plus the push regression tests, then fmt/lint.
Assistant· claude-opus-4-8
All pass. Now the full strategy package suite plus fmt/lint to confirm nothing regressed.
Assistant· claude-opus-4-8
Full strategy suite green, fmt and lint clean. Since I changed the push sync path, let me run the integration tests that exercise remote/push operations to validate end-to-end.
Assistant· claude-opus-4-8
Real failures, and they're informative: the union squashes into one "Merge…" commit, but two integration tests assert the remote branch contains a per-checkpoint "Checkpoint: <id>" commit (and getCheckpointAuthorFromRef depends on those subjects too). Both clones created independent orphans → no merge-base → my union fired and squashed. Let me read the failing assertions to decide: preserve per-checkpoint commits, or is the subject just a proxy?
Assistant· claude-opus-4-8
These tests encode a real contract: the disconnected sync must produce per-checkpoint "Checkpoint: <id>" commits (also relied on by getCheckpointAuthorFromRef), not a squash. The naive single-commit union breaks that. The correct design is to derive per-checkpoint commits from the tip-tree shard diff — preserving the contract while still never walking history. Let me find the shard-path → checkpoint-id mapping.
Assistant· claude-opus-4-8
The contract is clear: per-checkpoint "Checkpoint: <id>" commits, linear. My squash was too naive. I'll rework MergeMetadataTip to emit one commit per checkpoint id, derived from the tip-tree shard diff — preserving the contract with zero history walking. Let me confirm the id package path and NewCheckpointID.
Assistant· claude-opus-4-8
The subject must be exactly Checkpoint: <fullID> and the count must stay exact. I'll rework MergeMetadataTip to emit one commit per local-only checkpoint id (derived from shard paths via id.NewCheckpointID), folding any rare root-level changes into the first commit so the count matches the old cherry-pick. Let me rewrite that part.
Assistant· claude-opus-4-8
Now rewrite MergeMetadataTip and commitMergedTree to emit per-checkpoint commits:
Assistant· claude-opus-4-8
Now mergeTipTrees/MergeTipResult are superseded by MergeMetadataTip's internal diff. Let me check references and consolidate to avoid dead/duplicate code.
TestReconcileDisconnected_ShallowCloneNoOps — exercises ReconcileDisconnectedMetadataRef end-to-end with the real push-hook ref names (entire/checkpoints/v1 local + origin remote-tracking), asserting it no-ops instead of aborting — the directly reported symptom.
All of strategy and checkpoint/remote pass; mise run fmt + mise run lint are clean (0 issues).
One untested-but-adjacent item I deliberately left alone: MetadataHistoryShallowBounded (the doctor deepen gate from the P2 review fix) has no direct unit test — its underlying helper is now exercised by the new tests, but the "unrelated shallow boundary must not trigger a deepen" path is only validated at the helper level. That's best covered as a doctor integration test if you want it; say the word and I'll add it.
These call the network-free, best-effort disconnection check (local ref vs. existing origin/… remote-tracking ref) purely to print the "branches disconnected, run entire doctor" warning — they don't reconcile. Before the fix, on a shallow clone these would emit a false warning; they wouldn't error:
entire checkpoint list / entire status → ListCheckpoints
git commit (prepare-commit-msg / post-commit condensation) — appends a commit to the branch tip; it builds the DAG but doesn't walk ancestry. (Its read helpers do call the advisory warn, so it's in the list above only for that.)
entire clean and actual checkpoint content reads — tip-tree reads via ListCommitted, no merge-base.
Bottom line
The blast radius is anything that syncs or repairs the metadata branch against origin on a shallow clone: git push (most affected — it both detected and rebased), entire doctor, and entire session resume / metadata fetch. Everything else either reads the tip tree (unaffected) or only emitted a spurious warning. Notably, resume's --depth=1 fetch is what introduces the shallow boundary that the push/doctor paths then trip over — so the bug typically manifests as: resume on a fresh machine → later git push blows up.
PrimaryFetchableFromOrigin()
remoteRef
nil
thousands of condensation commits
git commit
different
(B) Remote branch rebuilt + stale objects. If entire/checkpoints/v1 on origin is ever rebuilt to a new disconnected history (another machine hitting (A) and pushing its orphan line, or a force-push/cleanup recreating the branch), and this clone still has the OLD history materialized in its pack from a prior full fetch as its local branch, then local (old line) vs remote (new line) share no ancestor, and the old line's thousands of objects are all present locally — so collectCommitChain happily walks them. This is precisely the case the collectCommitChain doc-comment calls out: "the walk would stroll past shallow boundaries into stale objects left in the pack… when the remote branch has been rebuilt since the last full fetch, producing a phantom chain."
How shallowness compounds (but isn't the root cause)
In both (A) and (B), shallowness makes detection worse, not the divergence itself:
On a shallow clone, the warn/push paths can't distinguish a genuine disconnection from a shallow artifact, so metadataDisconnected now suppresses and defers to doctor — correct, but it means push silently stops repairing.
Doctor's --deepen=1000 can't help case (A) at all (no shared ancestor exists at any depth) and can't help (B) if the dead line is deeper than 1000. The only correct fix there is the cherry-pick reconcile — which the 1000-cap then refuses for very deep local lines. That's the dead-end loop the original report hit.
One mitigating nuance worth knowing: the fetch/resume path is already guarded — SafelyAdvanceLocalRef (common.go:152-159) refuses to walk when there's no merge-base on a shallow repo, erroring with "run entire doctor or git fetch --unshallow" instead of strolling. The unbounded walk only happens in ReconcileDisconnectedMetadataRef (push/doctor), which has no such pre-guard and relies entirely on the metadataDisconnected suppression.
Bottom line
The CLI isn't corrupting .git/shallow, but it creates shallow boundaries it can never fully clear (the FetchMetadataBranch "undo" is a no-op) and only ever deepens by a bounded 1000.
A completely lost merge-base with thousands of local commits is a genuine disconnection — overwhelmingly from EnsurePrimaryRef minting a fresh orphan root when origin's tracking ref wasn't available (A), or a rebuilt remote branch leaving a stale deep local line (B) — not from the shallow false-positive.
If you want, I can: (1) fix FetchMetadataBranch to actually deepen/unshallow when full ancestry is requested (making its contract true), and/or (2) write a focused test reproducing mechanism (A) — orphan-root divergence with a deep local line — which is the more likely real-world cause than the pure shallow false-positive.
Same-checkpoint concurrent edits. Two clones condensing the same checkpoint ID (multi-session) can produce different content at the same path. But within <id>/ sessions are themselves sharded (<id>/<n>/), so this is mostly additive too — the only true single-file conflict is the per-checkpoint summary metadata.json (e.g. session_count/session list). That needs a deterministic merge rule (union the session list, recompute counts) rather than last-writer-wins. This is the residual of your "rarely conflicts" — accurate across checkpoints, not quite zero within one.
Loss of commit-level provenance on v1 (when/by-whom each condensation landed). Mostly redundant with metadata.json, modulo #1.
Net
For the failure you've been chasing, tip-only is a strict improvement: it removes the entire class of shallow-clone merge-base bugs and the deep-walk blowup, and it matches the data model (sharded, additive). The cost is concentrated in three rare edge cases — author attribution (needs re-sourcing), deletes (need a resurrection policy), and same-id concurrent summary merges (need a union rule). None of those are hot paths, and the first is the only hard dependency I can see in the current code.
If you want to pursue it, the cleanest framing is: make reconcile a mergeTipTrees(remoteTip, localTip) set-union producing one commit, and stop calling metadataDisconnected/collectCommitChain on the push path entirely. I can prototype that as a mergeTipTrees function plus a test (including the delete-resurrection and same-id-summary cases) so we can see the edge-case behavior concretely before deciding the policies — want me to?
session_count
semantic
Conflicts
Notes / next step
I deliberately built the tree-level core only — no ref mutation, no commit creation, no push wiring — so the behavior is observable in isolation before committing to it. mergeTipTrees is unexported and currently used only by tests (lint passes regardless).
The reverted fix is untouched; these are two new untracked files (metadata_merge.go, metadata_merge_test.go). Nothing staged or committed.
If you want to take it further, the next increment is a MergeMetadataTips wrapper that creates the single squash commit on the remote tip and advances the local ref, then swapping the push path from ReconcileDisconnectedMetadataRef (merge-base + collectCommitChain) over to it — plus deciding the two policies above. Want me to do that wiring, or add the semantic summary-merge for the conflict file first?