# How the No-Mistakes Branch Synchronization Service Ensures Guarded Local Branch Updates

> Learn how the No Mistakes branch synchronization service protects local branch mutations with layered checks for context, repo state, and cleanliness before applying changes.

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

---

**The `no-mistakes` branch-synchronization service protects every local branch mutation with a layered series of checks that verify context, repository state, remote binding, and work-tree cleanliness before any change is applied.**

The `no-mistakes` repository provides a robust branch-synchronization mechanism designed to prevent accidental data loss and race conditions during pipeline operations. At the heart of this system lies the [`internal/branchsync/sync.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go) service, which implements a comprehensive guard framework to ensure **guarded local branch updates**. Every mutation passes through an eight-layer verification process that validates the execution context, repository cleanliness, and remote binding integrity before modifying any local state.

## The Eight-Layer Guard Framework

According to the `kunchenguid/no-mistakes` source code, the service implements a **fail-safe barrier** through eight sequential verification steps. Each public entry point—`Apply`, `Refresh`, and `Recover`—executes this guard sequence to prevent unauthorized or unsafe modifications:

- **Gate-context refusal** – Validates the caller operates inside a valid gate (bare repository) at lines [311‑330](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L311-L330)
- **Repository state inspection** – Gathers local branch, HEAD, and cleanliness data without remote contact at lines [662‑795](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L662-L795)
- **Refresh pre-check** – Re-validates the push ref against remote and fetches a private copy at lines [108‑156](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L108-L156)
- **Safety classification** – Determines if fast-forward or equivalent-diverged advance is permitted at lines [998‑1055](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L998-L1055)
- **Apply guard** – Re-checks all pre-conditions before mutation at lines [332‑428](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L332-L428)
- **Strict update execution** – Performs atomic fast-forward or anchored equivalent advance at blocks [447‑452] and [453‑462](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L453-L462)
- **Recovery path** – Handles stranded branches with guarded custody-return at lines [730‑819](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L730-L819)
- **Work-tree cleanliness** – Scans for in-progress Git operations and uncommitted changes at lines [442‑466](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L442-L466)

## Core Validation Mechanisms

### Gate Context Verification

The `gateContextRefusal` function (lines [311‑330](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L311-L330)) serves as the first line of defense. It ensures the operation executes within a valid **gate context**—specifically, the bare repository that owns the pipeline. If the gate is missing or nested incorrectly, the function immediately blocks the operation, preventing accidental invocations from arbitrary directories or non-gate worktrees.

### Repository State Inspection

Before contacting the remote, the `inspect` function (lines [662‑795](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L662-L795)) gathers comprehensive local state. It captures the current branch, HEAD position, work-tree cleanliness, and associated pipeline run metadata. This **state immutability** check establishes a deterministic baseline, ensuring subsequent validation steps compare against a known-good repository condition.

### Remote Binding Validation

The `Refresh` method (lines [108‑156](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L108-L156)) eliminates "push-while-remote-changed" race conditions. It re-validates the exact push ref against the remote, fetches a private copy, and confirms the remote has not advanced or been rewritten since the last pipeline push. This **remote binding integrity** check ensures the service only proceeds when the remote reference remains stable and bound to the expected pipeline generation.

### Safety Classification and Relation Analysis

The `classifyRelation` function (lines [998‑1055](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L998-L1055)) categorizes the relationship between local and remote states into safety levels. The service permits two strict update modes:

- **SafetySafeFastForward** – Standard fast-forward when history is linear
- **SafetySafeEquivalentAdvance** – Anchored advance for equivalent-diverged histories

This classification prevents non-fast-forward merges and history rewrites, ensuring **local branches never rewrite unpublished history**.

## Executing Guarded Updates

### The Apply Method Guard Sequence

The `Apply` function (lines [332‑428](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L332-L428)) orchestrates the final mutation guard. Before executing `git merge --ff-only` or `git reset --hard`, it:

1. Re-verifies the gate context
2. Calls `Refresh` again to confirm remote state consistency
3. Validates the run's push generation fingerprint
4. Re-confirms local branch cleanliness and unchanged state

If any pre-condition fails, `Apply` returns a blocked plan without modifying the repository. When safety checks pass, the service executes either a strict fast-forward (lines [447‑452](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L447-L452)) or an **anchored equivalent-diverged advance** (lines [453‑462](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L453-L462)). The latter creates an anchor ref (`syncAnchorRef`) recording the pre-sync HEAD, verifies the equivalence proof, then resets to the pipeline head—preserving a recovery point throughout the operation.

### Work-Tree Cleanliness Verification

The `worktreeClean` helper (lines [442‑466](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L442-L466)) scans for in-progress Git operations including active merges, rebases, cherry-picks, and uncommitted changes. Any non-clean state aborts the update with a descriptive error and suggests running `git status`. This ensures a **deterministic starting point** for all fast-forward operations.

## Recovery and Custody Return

### The Recover Path

When a terminal run leaves a branch stranded, the `Recover` function (lines [730‑819](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L730-L819)) performs a **guarded custody-return**. It only fast-forwards **clean** behind branches and refuses dirty ones. For diverged or ahead branches, `Recover` never mutates the work-tree unless the user explicitly requests preservation via the `--keep-local` flag. The gate branch updates through an atomic **compare-and-swap** operation, eliminating race conditions during recovery.

## Practical Implementation Examples

The following examples demonstrate how to invoke the guarded synchronization service in Go applications.

### Performing a Guarded Sync

```go
svc, close, err := branchsync.OpenCurrent()
if err != nil { log.Fatal(err) }
defer close()

ctx := context.Background()
state := svc.Apply(ctx) // all guards run internally
if state.State != branchsync.StateSynchronized {
    fmt.Printf("Sync blocked: %s – %s\n", state.Safety, state.Error)
}

```

The `svc.Apply` call automatically executes the full guard sequence: gate context verification, remote binding refresh, work-tree cleanliness confirmation, and safety classification before applying any changes.

### Recovering Custody After Terminal Runs

```go
svc, close, _ := branchsync.OpenCurrent()
defer close()

ctx := context.Background()
recovered := svc.Recover(ctx, /*keepLocal=*/ false)
if recovered.State == branchsync.StateSynchronized {
    fmt.Println("Branch recovered and fast‑forwarded safely.")
} else {
    fmt.Printf("Recovery blocked: %s – %s\n", recovered.Safety, recovered.Error)
}

```

The `Recover` method enforces the same guard sequence as `Apply` while adding specific safety checks for diverged or dirty branches during custody return.

## Summary

The `no-mistakes` branch synchronization service ensures **guarded local branch updates** through:

- **Context safety** – Gate-context guards prevent invocation from invalid directories
- **State immutability** – Pre-mutation re-inspection guarantees no external changes occurred
- **Remote binding integrity** – Refresh validation eliminates remote-change race conditions
- **Clean work-tree requirements** – Pending operations block updates to ensure deterministic state
- **Atomic anchoring** – Equivalent-diverged advances use anchor refs to preserve pre-sync HEAD
- **Recovery guarantees** – Custody returns use compare-and-swap operations for atomicity

## Frequently Asked Questions

### What happens if the work-tree contains uncommitted changes during a sync attempt?

The service immediately blocks the operation. The `worktreeClean` function (lines [442‑466](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L442-L466)) scans for uncommitted changes and in-progress Git operations (merge, rebase, cherry-pick). If detected, `Apply` returns a blocked plan with an error suggesting `git status`, ensuring no local modifications are lost during the update.

### How does the service prevent race conditions when the remote advances during synchronization?

The `Refresh` method (lines [108‑156](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/sync.go#L108-L156)) implements a **refresh pre-check** that re-validates the exact push ref against the remote immediately before mutation. It fetches a private copy and confirms the remote has not advanced since the last pipeline push. Additionally, `Apply` calls `Refresh` again right before executing changes, creating a double-check pattern that eliminates "push-while-remote-changed" races.

### What is the difference between SafetySafeFastForward and SafetySafeEquivalentAdvance?

**SafetySafeFastForward** permits standard fast-forward merges when the local branch is strictly behind the remote. **SafetySafeEquivalentAdvance** handles diverged histories where the commits are equivalent but branches have diverged. In this case, the service creates an anchor ref to record the pre-sync HEAD, verifies the equivalence proof, then performs a hard reset to the pipeline head—ensuring the local branch never rewrites history while preserving the ability to recover the original state.

### When should I use the Recover function instead of Apply?

Use `Recover` when a terminal pipeline run leaves the local branch stranded without publishing its head. Unlike `Apply`, which performs standard synchronization, `Recover` handles **custody return** scenarios. It safely fast-forwards only clean behind branches and refuses to mutate dirty or diverged branches unless explicitly instructed with `keepLocal=true`. This makes `Recover` ideal for cleanup operations after failed or aborted pipeline runs.