checkpoint/strategy: collapse duplicated mirror patterns · Entire

checkpoint/strategy: collapse duplicated mirror patterns

308d1ae→main·!

pfleidi·1mo ago·11 files·+68 added/-81 removed

New helpers absorb three duplicated patterns:

AdvanceCommittedPrimary no longer reads Primary back after writing it: the mirror path is split into MirrorCommittedMetadataRef (reads first, for callers without a hash) and setMirrorTo (writes a known hash). Saves one repo.Reference lookup per committed write.

Four sites that had a store in scope now reuse store.Refs() instead of re-running ResolveCommittedRefs(ctx) — each call hits settings.json on disk plus a git subprocess. Sites: condensation finalize, attribution finalize, transcript finalize, explain getBranchCheckpoints.

A test fixture switches from hand-built v1-only CommittedRefs to DefaultV1Refs.

Sessions

7324f71f4c46View transcript

[?
Streamline Checkpoint Version Mirroring with refs.PrimaryClaude Code·4 steps](/content/gh/entireio/cli/session/7d8b9a47-6f94-441b-adae-5402ded54425#timeline-7324f71f4c46/index.html)

Changes

11

347 unmodified lines
348
349
350
351
352
353
351
352
353
354
93 unmodified lines

448
449
450
453
454
455
451
452
453
454

347 unmodified lines

// at Primary. Reads target Primary directly, not refs.Read, because this guard
// must reflect what the next write would target.
func checkpointHasSessionMetadata(ctx context.Context, repo *git.Repository, refs cpkg.CommittedRefs, checkpointID id.CheckpointID, sessionID string) (bool, error) {
    primaryRefs := refs
    primaryRefs.Read = refs.Primary
    store := cpkg.NewGitStore(repo, primaryRefs)
    store := cpkg.NewGitStore(repo, refs.PrimaryAsRead())
summary, err := store.ReadCommitted(ctx, checkpointID)
if err != nil {
    return false, fmt.Errorf("read checkpoint summary: %w", err)
}
93 unmodified lines

if _, err := repo.Reference(refs.Primary, true); err != nil {
    return false, nil //nolint:nilerr // Missing ref is the "absent" signal, not an error.
}
primaryRefs := refs
primaryRefs.Read = refs.Primary
summary, err := cpkg.NewGitStore(repo, primaryRefs).ReadCommitted(ctx, checkpointID)
summary, err := cpkg.NewGitStore(repo, refs.PrimaryAsRead()).ReadCommitted(ctx, checkpointID)
if err != nil {
    return false, err //nolint:wrapcheck // Caller wraps with checkpoint ID context
}

Mcmd/entire/cli/attach.go+2/-6

122 unmodified lines 
123
124
125
126
127
128
129
130
131
132
126
127
128
129
465 unmodified lines

595
596
597
604
605
606
607
608
609
610
598
599
600
601
819 unmodified lines

1421
1422
1423
1436
1437
1438
1439
1440
1441
1442
1424
1425
1426
1427
112 unmodified lines

1540
1541
1542
1561
1562
1563
1564
1565
1566
1567
1543
1544
1545
1546
154 unmodified lines

1701
1702
1703
1728
1704
1705
1730
1731
1706
1707
1708
1709
17 unmodified lines

1727
1728
1729
1755
1756
1757
1758
1759
1730
1731
1732
1733

122 unmodified lines

return err
}

refName := s.refs.Primary
newRef := plumbing.NewHashReference(refName, newCommitHash)
if err := s.repo.Storer.SetReference(newRef); err != nil {
    return fmt.Errorf("failed to set branch reference: %w", err)
}

return nil
return s.setPrimaryRef(newCommitHash)

// flattenCheckpointEntries reads only the entries under a specific checkpoint path
465 unmodified lines

return err
}

return nil
return s.setPrimaryRef(newCommitHash)

func (s *GitStore) replaceSkillEvents(skillEvents []agent.SkillEvent, sessionPath string, entries map[string]object.TreeEntry) error {
154 unmodified lines

}, nil
}

// ensureSessionsBranch ensures the entire/checkpoints/v1 branch exists.
// ensureSessionsBranch ensures the primary metadata ref exists.
func (s *GitStore) ensureSessionsBranch(ctx context.Context) error {
refName := s.refs.Primary
_, err := s.repo.Reference(refName, true)
_, err := s.repo.Reference(s.refs.Primary, true)
if err == nil {
    return nil // Branch exists
}
17 unmodified lines

return err
}

newRef := plumbing.NewHashReference(refName, commitHash)
if err := s.repo.Storer.SetReference(newRef); err != nil {
    return fmt.Errorf("failed to set branch reference: %w", err)
}
return nil
return s.setPrimaryRef(commitHash)
}

func (s *GitStore) maybeMergeVercelConfig(ctx context.Context, rootTreeHash plumbing.Hash) (plumbing.Hash, error) {

Mcmd/entire/cli/checkpoint/committed.go+7/-36


47 unmodified lines
48
49
50
51
52
53
54
55
56
57
58
59

47 unmodified lines

return r.Read == r.Primary && r.PrimaryFetchableFromOrigin()
}

// PrimaryAsRead returns a copy of r with Read pinned to Primary.
func (r CommittedRefs) PrimaryAsRead() CommittedRefs {
    r.Read = r.Primary
    return r
}

// ResolveCommittedRefs returns the topology for the settings on disk, falling
// back to v1-branch-only when settings cannot be loaded.
func ResolveCommittedRefs(ctx context.Context) CommittedRefs {

Mcmd/entire/cli/checkpoint/committed_refs.go+6


1
2
3
4
5
6
7
8
37 unmodified lines

46
47
48
49
50
51
52
53
54
55

package checkpoint

import (
    "fmt"

"github.com/go-git/go-git/v6"
    "github.com/go-git/go-git/v6/plumbing"
)
37 unmodified lines

func (s *GitStore) CommittedReadRef() plumbing.ReferenceName {
    return s.refs.Read
}

func (s *GitStore) setPrimaryRef(hash plumbing.Hash) error {
    if err := s.repo.Storer.SetReference(plumbing.NewHashReference(s.refs.Primary, hash)); err != nil {
        return fmt.Errorf("set primary metadata ref %s to %s: %w", s.refs.Primary, hash, err)
    }
    return nil
}

Mcmd/entire/cli/checkpoint/store.go+9


2113 unmodified lines 
2114
2115
2116
2117
2117
2118
2119
2120

2113 unmodified lines

}

// Get temporary checkpoints from ALL shadow branches whose base commit is reachable from HEAD.
    tempPoints := getReachableTemporaryCheckpoints(ctx, repo, checkpoint.NewGitStore(repo, checkpoint.ResolveCommittedRefs(ctx)), head.Hash(), isOnDefault, limit)
tempPoints := getReachableTemporaryCheckpoints(ctx, repo, store, head.Hash(), isOnDefault, limit)
points = append(points, tempPoints...)

// Sort by date, most recent first

Mcmd/entire/cli/explain.go+1/-1


262 unmodified lines

263
264
265
266
266
267
268
269

262 unmodified lines

// Mirror the committed write to refs.Mirror when configured (best-effort;
    // failures are logged, not fatal).
    mirrorCommittedMetadataRefBestEffort(ctx, repo, cpkg.ResolveCommittedRefs(ctx))
    mirrorCommittedMetadataRefBestEffort(ctx, repo, store.Refs())

logging.Debug(logCtx, "condense timings",
        slog.String("session_id", state.SessionID),

Mcmd/entire/cli/strategy/manual_commit_condensation.go+1/-1


1156 unmodified lines

1157
1158
1159
1160
1160
1161
1162
1163
1651 unmodified lines

2815
2816
2817
2818
2818
2819
2820
2821

1156 unmodified lines

// Combined attribution is a committed write in the post-commit hook, so the
    // mirror must track it too when configured (best-effort).
    mirrorCommittedMetadataRefBestEffort(ctx, repo, checkpoint.ResolveCommittedRefs(ctx))
    mirrorCommittedMetadataRefBestEffort(ctx, repo, store.Refs())

return nil
}

1651 unmodified lines

// Mirror the finalized primary metadata to refs.Mirror when configured
    // (best-effort; failures are logged, not fatal). Once after the loop is
    // enough — it tracks Primary's final commit.
    mirrorCommittedMetadataRefBestEffort(ctx, repo, checkpoint.ResolveCommittedRefs(ctx))
    mirrorCommittedMetadataRefBestEffort(ctx, repo, store.Refs())

// Clear turn checkpoint IDs. Do NOT update CheckpointTranscriptStart here — it was
    // already set correctly by PostCommit: condenseAndUpdateState sets it to the total

Mcmd/entire/cli/strategy/manual_commit_hooks.go+2/-2


113 unmodified lines

114
115
116
117
118
119
120
117
118
119
120

113 unmodified lines

) error {
    refs := checkpoint.ResolveCommittedRefs(ctx)
    advance := func(hash plumbing.Hash) error {
        if localRefName == refs.Primary {
            return AdvanceCommittedPrimary(ctx, repo, refs, hash)
        }
        return repo.Storer.SetReference(plumbing.NewHashReference(localRefName, hash))
        return AdvanceLocalRef(ctx, repo, refs, localRefName, hash)
    }

// Check local ref

Mcmd/entire/cli/strategy/metadata_reconcile.go+1/-4


413 unmodified lines

414
415
416
417
418
419
417
418
422
423
424
425
426
427
428
429
419
420
421
422
423

413 unmodified lines

return fmt.Errorf("failed to get remote ref: %w", err)
    
    // Helper to advance ref and clean up the temp fetch ref. When ref is the
    // configured Primary, the mirror is advanced too (best-effort); otherwise
    // the mirror step is skipped because origin doesn't track this ref.
    refs := checkpoint.ResolveCommittedRefs(ctx)
    advance := func(hash plumbing.Hash) error {
        var setErr error
        if ref == refs.Primary {
            setErr = AdvanceCommittedPrimary(ctx, repo, refs, hash)
        } else {
            setErr = repo.Storer.SetReference(plumbing.NewHashReference(ref, hash))
        }
        if setErr != nil {
            return fmt.Errorf("failed to update ref %s: %w", ref, setErr)
        if err := AdvanceLocalRef(ctx, repo, refs, ref, hash); err != nil {
            return err
        }
        if usedTempRef {
            _ = repo.Storer.RemoveReference(fetchedRefName) //nolint:errcheck // cleanup is best-effort
        }

Mcmd/entire/cli/strategy/push_common.go+2/-11


19 unmodified lines

20
21
22
23
24
25
26
23
24
25
26
27
31
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
109 unmodified lines

153
154
155
147
156
157
158
1 unmodified line

160
161
162
163
164
165
156
157
166
167
168
169
159
170
171
162
172
173
174
175
166
167
168
169
170
171
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
173
191
192
193
194
195
196
197

19 unmodified lines

var ErrPrimaryMetadataMissing = errors.New("primary metadata ref missing")

// AdvanceCommittedPrimary points refs.Primary at hash and best-effort-advances
// refs.Mirror. Used by autonomous flows (hooks, push rebase, condensation,
// reconcile) where mirror failure must not abort the primary operation.
// User-foreground commands (attach, explain summary) call
// MirrorCommittedMetadataRef directly when they want to surface mirror errors.
// refs.Mirror. Mirror failure does not abort the primary operation.
func AdvanceCommittedPrimary(ctx context.Context, repo *git.Repository, refs checkpoint.CommittedRefs, hash plumbing.Hash) error {
    if err := repo.Storer.SetReference(plumbing.NewHashReference(refs.Primary, hash)); err != nil {
        return fmt.Errorf("set primary metadata ref %s to %s: %w", refs.Primary, hash, err)
    }
    mirrorCommittedMetadataRefBestEffort(ctx, repo, refs)
    setMirrorToBestEffort(ctx, repo, refs, hash)
    return nil
}

// AdvanceLocalRef points ref at hash, advancing the mirror best-effort when
// ref is refs.Primary.
func AdvanceLocalRef(ctx context.Context, repo *git.Repository, refs checkpoint.CommittedRefs, ref plumbing.ReferenceName, hash plumbing.Hash) error {
    if ref == refs.Primary {
        return AdvanceCommittedPrimary(ctx, repo, refs, hash)
    }
    if err := repo.Storer.SetReference(plumbing.NewHashReference(ref, hash)); err != nil {
        return fmt.Errorf("set ref %s to %s: %w", ref, hash, err)
    }
    return nil
}

109 unmodified lines

if !refs.HasMirror() {
        return nil
    }

primaryRef, err := repo.Reference(refs.Primary, true)
    if err != nil {
        if errors.Is(err, plumbing.ErrReferenceNotFound) {
1 unmodified line

}
    return fmt.Errorf("read primary metadata ref %s: %w", refs.Primary, err)
}
return setMirrorTo(ctx, repo, refs, primaryRef.Hash())

if err := repo.Storer.SetReference(plumbing.NewHashReference(refs.Mirror, primaryRef.Hash())); err != nil {
    return fmt.Errorf("set mirror ref %s to %s: %w", refs.Mirror, primaryRef.Hash(), err)
func setMirrorTo(ctx context.Context, repo *git.Repository, refs checkpoint.CommittedRefs, hash plumbing.Hash) error {
    if err := repo.Storer.SetReference(plumbing.NewHashReference(refs.Mirror, hash)); err != nil {
        return fmt.Errorf("set mirror ref %s to %s: %w", refs.Mirror, hash, err)
    }

logging.Debug(ctx, "committed-ref mirror updated",
        slog.String("ref", refs.Mirror.String()),
        slog.String("hash", primaryRef.Hash().String()));
        slog.String("hash", hash.String()))
    return nil
}

// mirrorCommittedMetadataRefBestEffort runs MirrorCommittedMetadataRef under a
// detached cancellation context, swallowing errors as logs. The detached
// context preserves trace/value context but prevents a near-expired parent
// deadline (e.g. the 2-minute fetch budget) from silently failing
// settings.Load and skipping the mirror with no log. The mirror itself is
// short.
func setMirrorToBestEffort(ctx context.Context, repo *git.Repository, refs checkpoint.CommittedRefs, hash plumbing.Hash) {
    if !refs.HasMirror() {
        return
    }
    // Detach cancellation so a parent deadline near expiry doesn't silently
    // drop the mirror write; the mirror itself is short.
    ctx = context.WithoutCancel(ctx)
    if err := setMirrorTo(ctx, repo, refs, hash); err != nil {
        logging.Warn(ctx, "committed-ref mirror failed",
            slog.String("ref", refs.Mirror.String()),
            slog.String("error", err.Error()))
    }
}

func mirrorCommittedMetadataRefBestEffort(ctx context.Context, repo *git.Repository, refs checkpoint.CommittedRefs) {
    ctx = context.WithoutCancel(ctx)
    if !refs.HasMirror() {
        return
    }
    ctx = context.WithoutCancel(ctx)
    if err := MirrorCommittedMetadataRef(ctx, repo, refs); err != nil {
        if errors.Is(err, ErrPrimaryMetadataMissing) {
            logging.Debug(ctx, "committed-ref mirror skipped: primary metadata ref unavailable",