What Is the Guarded Local Branch Synchronization Service in no-mistakes?

The guarded local branch synchronization service is the core safety mechanism behind the no-mistakes sync command that ensures your local Git branch stays synchronized with the exact pipeline-published commit while preventing data loss through strict fast-forward enforcement and race-condition protection.

The no-mistakes repository provides a deterministic Git workflow that prevents developers from accidentally pushing unsafe commits or losing work. At the heart of this system lies the guarded local branch synchronization service, implemented primarily in internal/branchsync/sync.go, which orchestrates the movement of local branches to match the authoritative state published by CI/CD pipelines.

Core Public API: Four Methods That Drive the Sync Lifecycle

The service exposes four public methods that handle different stages of branch synchronization. Each method is designed to be atomic and fails safely when preconditions are not met.

InspectCached: Zero-Network State Inspection

The InspectCached method provides a read-only view of the current synchronization state without contacting any remote. It calls the private inspect helper (lines 33-68) to read the Git worktree, verify repository registration, and resolve the current branch and HEAD. This method guards against ambiguous contexts such as dirty worktrees or duplicate worktree checkouts (lines 52-69).

Refresh: Remote Validation and State Classification

The Refresh method validates the remote push target and fetches the latest pipeline-bound commit into a private ref. It performs a remote git ls-remote, fetches into refs/no-mistakes/sync/<run-id> (lines 27-70), then classifies the relation between local and remote heads (lines 71-92).

Apply: Safe Branch Advancement

The Apply method advances the local branch to the exact pipeline-published commit. It first calls Refresh (lines 14-18), then performs either a strict fast-forward (git merge --ff-only) or an equivalent-diverged fast-forward when safe. For the equivalent-diverged case, it anchors the pre-sync head and resets using git update-ref and git reset --hard (lines 63-77).

Recover: Custody Return from Terminal Runs

The Recover method handles branches stranded by terminal runs—those cancelled or failed before pushing. It validates that the run is terminal (lines 55-58), then follows a decision matrix (lines 13-25) to either fast-forward, keep the local head, or abort based on the worktree-to-preserved-head relation. The recovery logic delegates to helper methods recoverFastForward, recoverKeepLocal, and finishRecover (lines 68-100).

Internal Safety Mechanisms and State Representation

The service maintains safety through careful state tracking and conservative advancement policies.

The State Struct and Relation Classification

The State struct (lines 57-74) captures the composite view presented to the CLI, API, and TUI. It encodes the local branch (LocalState), pipeline run (PipelineState), remote target (TargetState & RemoteState), relationship (Relation), and safety tag (Safety).

The classifyRelation method (lines 70-86) determines whether the branch is equal, behind, ahead, or diverged relative to the pipeline-pushed commit. For diverged histories, it may apply the equivalent-diverged fast-forward algorithm (equivalentDivergence in lines 332-345).

Atomic Operations and Race Condition Prevention

The service enforces fast-forward only advancement when the local branch is behind. For equivalent-diverged cases, it anchors the pre-sync head using syncAnchorRef before resetting to the pipeline head (lines 65-73).

When recovering with recoverKeepLocal (lines 28-62), the service updates the gate branch via a compare-and-swap operation to prevent races with concurrent pushes.

Practical Usage: CLI and Programmatic Examples

Developers interact with the guarded local branch synchronization service through the no-mistakes sync command or by importing the package directly.

To inspect the current sync status without network calls:

no-mistakes sync --check

This returns a JSON State showing fields like "state":"behind", "relation":"behind", and "safety":"safe_fast_forward".

To bring the worktree up-to-date:

no-mistakes sync

This internally executes Refresh followed by Apply, either fast-forwarding or performing an equivalent-diverged reset.

To recover from a cancelled terminal run:

no-mistakes sync --recover

Or to keep the current local HEAD while moving only the gate branch:

no-mistakes sync --recover --keep-local

For programmatic usage in Go:

svc, close, err := branchsync.OpenCurrent()
if err != nil { 
    log.Fatalf("cannot open sync service: %v", err) 
}
defer close()

// Quick cached inspection
state := svc.InspectCached(context.Background())

// Full refresh and apply
state = svc.Apply(context.Background())

Summary

  • The guarded local branch synchronization service lives in internal/branchsync/sync.go and powers the no-mistakes sync command.
  • It provides four public methods—InspectCached, Refresh, Apply, and Recover—to handle inspection, remote validation, safe advancement, and custody recovery.
  • All operations are fast-forward only or use an equivalent-diverged proof to ensure no work is lost.
  • The State struct tracks relationships between local, remote, and pipeline states while enforcing safety invariants.
  • Recovery from terminal runs uses atomic compare-and-swap operations to prevent race conditions.

Frequently Asked Questions

What happens if my worktree has uncommitted changes when I run sync?

The service detects dirty worktrees during the inspect phase (lines 52-69) and aborts the operation before modifying any refs. It returns a detailed State with a NextAction indicating that you must stash or commit changes before proceeding.

How does the service handle diverged branches without losing local commits?

When branches have diverged, the service first attempts to prove the histories are equivalent-diverged through the equivalentDivergence algorithm (lines 332-345). If the final trees match despite different parent commits, it anchors your current HEAD before resetting, allowing you to recover the original state if needed. If the divergence is not equivalent, the operation aborts safely.

What is a "terminal run" in the context of recovery?

A terminal run refers to a pipeline execution that finished in a cancelled or failed state before pushing its commit to the remote. The Recover method validates terminal status (lines 55-58) and allows you to either fast-forward to the preserved pipeline head or retain your local changes while releasing the pipeline's custody lock.

Can I use the sync service programmatically outside the CLI?

Yes. The branchsync.OpenCurrent() function returns a service instance for the current worktree. You can call InspectCached for lightweight status checks or Apply for full synchronization, making it suitable for custom Git hooks, IDE integrations, or automated tooling.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →