# How the Guarded Local Branch Synchronization Service Works in no-mistakes

> Learn how the guarded local branch synchronization service fast-forwards your worktree to verified remote commits. Sync only approved code without fetches or merges.

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

---

**The guarded local branch synchronization service fast-forwards your local worktree to an exact, pre-verified remote commit without performing fetches, merges, or destructive operations, ensuring you only sync to code that has passed pipeline validation.**

The `guarded local branch synchronization` service is the core safety mechanism in the [kunchenguid/no-mistakes](https://github.com/kunchenguid/no-mistakes) repository. Located in the `internal/branchsync` package, this service ensures developers can synchronize their local worktrees with remote branches that have already been validated by CI/CD pipelines. It is invoked by the CLI commands `no-mistakes sync` and `axi sync`, as well as the TUI’s `u` action.

## Core Safety Guarantees

The service maintains five strict invariants to prevent accidental data loss or unverified code execution:

- **Fast-forward only** – The service strictly fast-forwards the worktree to the exact remote SHA that has already been verified by a pipeline run. This guarantees users never introduce un-reviewed changes while syncing.
- **No fetches** – The service never contacts the remote to obtain new commits, preventing accidental divergence by only applying a *known* good state.
- **No destructive Git operations** – The tool never stashes, merges, rebases, force-pushes, switches, or deletes branches, protecting user data from accidental loss.
- **Atomic fast-forward** – The fast-forward is performed in a single Git command (`git reset --hard <remote-sha>`), ensuring the worktree ends in a clean state even if the process crashes midway.
- **Pre-flight validation** – Before applying the fast-forward, the service re-checks the worktree’s current HEAD, the target remote SHA, the branch generation, and the fingerprint stored in the database to avoid time-of-check-to-time-of-use races.

## Step-by-Step Workflow

The synchronization process follows a strict validation pipeline defined in [`internal/branchsync/service.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/service.go):

1. **Pipeline completion** – When a pipeline run finishes, it inserts a row into the `runs` table with the target remote SHA and a monotonic *generation* identifier.

2. **Invocation** – The user runs `no-mistakes sync`, triggering the CLI handler in [`internal/cli/sync.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/cli/sync.go) to look up the most recent successful run for the current repository root.

3. **Validation** – The `SyncService.Sync` method calls the validator (located in [`internal/branchsync/validator.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/validator.go)) to verify:
   - The current worktree’s HEAD matches the SHA recorded when the run started
   - The remote SHA stored in the database is still reachable
   - The generation counter has not been invalidated by a concurrent sync

4. **Execution** – If validation passes, the service executes `git reset --hard <remote-sha>` via `internal/shellenv.ConfigureShellCommand`, wrapped in cancellation logic to allow safe aborting.

5. **Commit** – After the fast-forward succeeds, the database row’s *applied* flag is set, and the service reports success. If any step fails, the service aborts with a specific error (such as `branchsync.ErrUncommittedChanges`) explaining why the sync could not proceed.

## Integration Points

The guarded sync service interacts with several system components to maintain its safety guarantees:

- **CLI ([`internal/cli/sync.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/cli/sync.go))** – Parses command-line flags, determines the repository root, and forwards the request to the sync service.
- **TUI ([`internal/tui/sync.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/tui/sync.go))** – Provides the same synchronization functionality through the terminal UI, reusing the core service logic.
- **Database ([`internal/db/run.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/db/run.go))** – Stores run metadata including the remote SHA and generation counter that the sync service consumes to verify state.
- **Shell environment ([`internal/shellenv/shell_command.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/shellenv/shell_command.go))** – Guarantees that Git subprocesses are properly killed and reaped if the user aborts the operation, preventing orphaned processes.

## Usage Examples

Run a synchronization from the command line:

```bash
no-mistakes sync

```

Programmatically invoke the service in a custom script:

```go
package main

import (
    "log"
    
    "github.com/kunchenguid/no-mistakes/internal/branchsync"
    "github.com/kunchenguid/no-mistakes/internal/db"
)

func main() {
    // Assume ctx, logger, and dbHandle are initialized
    svc := branchsync.NewService(dbHandle, logger)
    if err := svc.Sync(ctx); err != nil {
        log.Fatalf("sync failed: %v", err)
    }
    log.Println("worktree now matches the verified remote state")
}

```

Handle specific sync errors gracefully:

```go
err := svc.Sync(ctx)
if errors.Is(err, branchsync.ErrUncommittedChanges) {
    log.Println("Please commit or stash local changes before syncing.")
} else if err != nil {
    log.Fatalf("sync failed: %v", err)
}

```

## Summary

- The guarded local branch synchronization service lives in `internal/branchsync` and ensures safe, verified updates to your local worktree.
- It performs atomic fast-forwards to specific SHAs using `git reset --hard` without fetching new commits or performing destructive operations like merge or rebase.
- Pre-flight validation in [`internal/branchsync/validator.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/validator.go) checks HEAD state, remote SHA reachability, and generation counters to prevent race conditions.
- The service is accessible via `no-mistakes sync`, `axi sync`, or the TUI `u` action, all implemented in [`internal/cli/sync.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/cli/sync.go) and [`internal/tui/sync.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/tui/sync.go).
- Database state managed in [`internal/db/run.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/db/run.go) provides the source of truth for verified commits and generation tracking.

## Frequently Asked Questions

### What happens if I have uncommitted changes when running `no-mistakes sync`?

The service detects uncommitted changes during pre-flight validation and returns `branchsync.ErrUncommittedChanges`. The sync aborts immediately without modifying your worktree. You must commit, stash, or discard your changes before attempting to sync again.

### Why does the service use `git reset --hard` instead of `git pull` or `git merge`?

According to the source code in [`internal/branchsync/service.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/branchsync/service.go), the service uses `git reset --hard <remote-sha>` to ensure an atomic, idempotent operation that moves HEAD directly to the pre-verified SHA. Unlike `pull` or `merge`, this approach never fetches new objects from the remote and never creates merge commits, ensuring the worktree matches exactly the state that passed pipeline validation.

### How does the service prevent syncing to a remote branch that has changed since the pipeline run?

The service implements a **generation** counter stored in the database ([`internal/db/run.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/db/run.go)). Before executing the fast-forward, `SyncService.Sync` validates that the generation recorded at pipeline time matches the current database state and that the target SHA is still reachable. This prevents time-of-check-to-time-of-use attacks where the remote branch advances between verification and sync execution.

### Can I use the branch sync service in my own Go applications?

Yes. Import `github.com/kunchenguid/no-mistakes/internal/branchsync` and initialize the service with `branchsync.NewService(dbHandle, logger)`, passing a valid database connection and logger. Call `svc.Sync(ctx)` to execute the synchronization workflow within your own applications, handling errors such as `ErrUncommittedChanges` or `ErrGenerationMismatch` as needed.