# How `lastSeenSHA` Prevents Discarding Unseen Commits During Force Pushes in no‑mistakes

> Learn how kunchenguid/no-mistakes uses lastSeenSHA to prevent discarding unseen commits during force pushes. It anchors pushes to the last observed commit, aborting if new commits are detected.

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

---

**The `lastSeenSHA` value acts as a lease that anchors force‑pushes to the exact commit the pipeline last observed, triggering a patch‑id comparison that aborts the push if the remote contains commits the pipeline never incorporated.**

The `no‑mistakes` repository implements a defensive force‑push mechanism to prevent CI/CD pipelines from accidentally overwriting commits pushed by other contributors. At the core of this protection is the **`lastSeenSHA`** value, which stores the exact state of the remote branch when the pipeline last fetched it. By comparing the current remote SHA against this stored lease, the system determines whether a force‑push is safe or if it would discard unseen work.

## The Lease Concept Behind `lastSeenSHA`

The `lastSeenSHA` serves as a **lease** that anchors the pipeline’s push operation to a specific point in history. This value represents the commit SHA that the pipeline last observed on the remote branch, ensuring that any rewrite operation only affects history the pipeline itself created.

### What `lastSeenSHA` Represents

In the **push step**, `lastSeenSHA` is the SHA of the remote‑tracking ref that the rebase step fetched immediately before the push. This is the exact commit the branch was last rebased onto, as noted in the comments within [`internal/pipeline/steps/forcepush.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/pipeline/steps/forcepush.go).

In the **CI step**, the same protection applies using the HEAD SHA that the run last pushed, typically stored in `Run.HeadSHA`. Both contexts use this value to establish a baseline for safe history rewriting.

## The Decision Flow in `resolveForcePushDecision`

The core logic resides in `resolveForcePushDecision` within [`internal/pipeline/steps/forcepush.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/pipeline/steps/forcepush.go). This function implements a five‑step validation process that decides whether to allow a standard push, skip as up‑to‑date, or proceed with a guarded force‑push.

### Fast‑Path Safety Check

When the remote tip matches the stored lease, the pipeline can skip expensive diff operations:

1. Read the live remote SHA (`lsRemoteSHA`).
2. If the remote ref does not exist, treat as a new branch requiring a regular push.
3. If the remote SHA equals the new head, the branch is already up‑to‑date.
4. **Lease check**: If `lastSeenSHA` is non‑empty and equals the current remote SHA, the remote has not moved since the pipeline last observed it. This fast‑path allows an immediate safe force‑push because the remote is anchored to the lease.

### Handling Remote Divergence

If the remote has moved (`current != lastSeenSHA`), the pipeline must verify it will not discard any commits added by other contributors:

- The function calls `remoteCommitsNotIncorporated`, which fetches the remote tip and compares commit sets using `git rev‑list --cherry‑pick --right‑only` with patch‑id comparison.
- The comparison excludes commits reachable from `baseSHA` (the run’s known base) to focus only on new remote work.
- If the set of dropped commits is empty, the push proceeds.
- If unseen commits exist, the function returns a **`forcePushWouldDiscardError`**, aborting the operation with an explicit warning message.

## Code Implementation

### Obtaining the Lease in Push Steps

In [`internal/pipeline/steps/push.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/pipeline/steps/push.go), the push step retrieves the stored lease before calling the decision routine:

```go
lastSeen := lastFetchedBranchTip(ctx, sctx.WorkDir, branch, usingFork)
gitRun := func(args ...string) (string, error) {
    return git.Run(ctx, sctx.WorkDir, args...)
}
decision, err := resolveForcePushDecision(gitRun, pushURL, ref,
    headBeingPushed, lastSeen, sctx.Run.BaseSHA)
if err != nil {
    return nil, fmt.Errorf("push to %s: %w", pushTarget, err)
}
switch {
case decision.newBranch:
    // Execute plain push
case decision.upToDate:
    // Nothing to do
default:
    // Execute force‑push with lease anchored to decision.remoteSHA
    git.Push(ctx, sctx.WorkDir, pushURL, ref, decision.remoteSHA, true)
}

```

### Core Validation Logic

The lease check and safety validation in [`internal/pipeline/steps/forcepush.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/pipeline/steps/forcepush.go) look like this:

```go
if lastSeenSHA != "" && current == lastSeenSHA {
    // Remote unchanged since we last observed it → safe force‑push.
    return forcePushDecision{remoteSHA: current}, nil
}
// Remote moved; verify we are not discarding unseen commits.
dropped, err := remoteCommitsNotIncorporated(gitRun, pushURL, ref,
    newHeadSHA, current, baseSHA)
if len(dropped) == 0 {
    return forcePushDecision{remoteSHA: current}, nil
}
return forcePushDecision{}, &forcePushWouldDiscardError{/* ... */}

```

### Detecting Unseen Commits

The `remoteCommitsNotIncorporated` function uses patch‑id comparison to detect commits present on the remote but absent from the local rewrite:

```go
args := []string{"rev-list", "--cherry-pick", "--right-only",
    newHeadSHA + "..." + remoteSHA}
if baseSHA != "" && !git.IsZeroSHA(baseSHA) {
    args = append(args, "^"+baseSHA) // Exclude known base history
}
out, err := gitRun(args...)

```

## Consistent Protection Across CI and Push Steps

The same `resolveForcePushDecision` logic protects both manual push steps and CI auto‑fix operations. The [`internal/pipeline/steps/ci_fix.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/pipeline/steps/ci_fix.go) file re‑uses this decision routine for CI‑driven force‑pushes, ensuring identical safety guarantees across all code paths. Whether triggered by a developer command or an automated fix, the **`lastSeenSHA`** lease prevents the pipeline from silently clobbering out‑of‑band commits.

## Summary

- **`lastSeenSHA`** acts as a lease anchoring force‑pushes to the last observed remote state.
- When the remote SHA matches the lease, the push proceeds immediately via a fast‑path safety check.
- If the remote diverges, `remoteCommitsNotIncorporated` verifies no unseen commits are discarded using `git rev-list --cherry-pick`.
- The **`forcePushWouldDiscardError`** aborts operations that would lose remote work, forcing re‑base or manual intervention.
- Both [`push.go`](https://github.com/kunchenguid/no-mistakes/blob/main/push.go) and [`ci_fix.go`](https://github.com/kunchenguid/no-mistakes/blob/main/ci_fix.go) use identical logic in [`internal/pipeline/steps/forcepush.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/pipeline/steps/forcepush.go) to maintain consistent protection.

## Frequently Asked Questions

### What happens if `lastSeenSHA` is empty?

If `lastSeenSHA` is empty, the lease check is skipped and the pipeline treats the operation as a standard force‑push. However, the `remoteCommitsNotIncorporated` check still runs if the remote exists, ensuring the pipeline does not discard commits unless it can prove they are already incorporated in the new head.

### How does no‑mistakes detect unseen commits?

The system executes `git rev-list --cherry-pick --right-only` comparing the new local head against the remote tip, while excluding the base SHA. This generates a list of commits present on the remote but missing from the local rewrite, using patch‑id comparison to detect equivalent changes across different histories.

### What error is returned when a force push would discard changes?

The system returns a **`forcePushWouldDiscardError`** defined in [`internal/pipeline/steps/forcepush.go`](https://github.com/kunchenguid/no-mistakes/blob/main/internal/pipeline/steps/forcepush.go). This error includes explicit messaging about the commits that would be lost, aborting the push operation and preventing silent data loss.

### Can this protection be bypassed?

The protection is integral to the push step implementation and cannot be bypassed through configuration without modifying the source code. The `resolveForcePushDecision` function is the sole gatekeeper for all push operations in the pipeline, ensuring the lease check or the diff validation always executes before a force‑push is allowed.