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

> Discover the guarded local branch synchronization service in no-mistakes. Ensure your Git branch matches the published commit with fast-forward enforcement and race-condition protection.

- Repository: [Kun Chen/no-mistakes](https://github.com/kunchenguid/no-mistakes)
- Tags: deep-dive
- Published: 2026-07-19

---

**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`](https://github.com/kunchenguid/no-mistakes/blob/main/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](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L33-L68)) 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](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L52-L69)).

### 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](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L27-L70)), then classifies the relation between local and remote heads (lines [71-92](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L71-L92)).

### Apply: Safe Branch Advancement

The `Apply` method advances the local branch to the exact pipeline-published commit. It first calls `Refresh` (lines [14-18](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L14-L18)), 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](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L63-L77)).

### 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](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L55-L58)), then follows a decision matrix (lines [13-25](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L13-L25)) 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](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L68-L100)).

## 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](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L57-L74)) 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](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L70-L86)) 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](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L332-L345)).

### 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](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L65-L73)).

When recovering with `recoverKeepLocal` (lines [28-62](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L28-L62)), 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:

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

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

```bash
no-mistakes sync --recover

```

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

```bash
no-mistakes sync --recover --keep-local

```

For programmatic usage in Go:

```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`](https://github.com/kunchenguid/no-mistakes/blob/main/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](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L52-L69)) 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](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L332-L345)). 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](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L55-L58)) 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.