All skills

Agent skill

Tidy commits

Rebuild a messy branch into clean, atomic commits, with a backup and a check that the final code hasn't changed by a single line.

Use this skill

Install it into a project with the Skills CLI, or read the files below and adapt them to your own agent.

npx skills add shan8851/agent-skills --skill tidy-commits
View source on GitHub
SKILL.mdView this file on GitHub
---
name: tidy-commits
description: Rebuild a messy branch into a few atomic, reviewable commits, one per logical change, without changing a single line of the final code. Finds the real merge base, takes a backup branch, soft-resets to the fork point, groups hunks by meaning, gets the user to approve the grouping, rebuilds the commits (writing intermediate file states where one file spans two commits), and proves the result is identical with an empty diff against the backup. Handles changesets if the repo uses them. Never force-pushes. Use when the user says "tidy the commits", "clean up the branch history", "squash this into sensible commits", "prepare this branch for review", or after a staged build left checkpoint commits.
---

# Tidy commits

Turn a branch's history into the commits a reviewer would want: one per feature, fix, refactor or chore, each making sense on its own, in dependency order. The guarantee is that **the final tree is byte-for-byte what it was**. Only the commit structure changes.

It never replays or rebases old commits (that's where conflicts come from). It flattens the branch to one diff and rebuilds from that.

## When to use

- Before opening or updating a PR, when the history is "wip", "fix", "fix again", or an agent's per-stage checkpoints.
- "Tidy the commits", "clean up the branch history", "squash this into sensible commits", "prepare this branch for review".
- After `plan-and-build`, whose stage commits follow execution order, not changelog order.

Do not use when:
- the branch is already merged, or shared and others are building on it (rewriting it breaks their work). Ask first;
- the user wants to rebase onto a newer base. That's a separate step, done after this one;
- there's one commit that's already coherent.

## Rules that matter most

1. **Reset to the fork point, never to `origin/<base>`.** If the base has moved on, resetting to its tip stages reversals of everyone else's work, and the backup diff can't catch it because the backup is missing that work too.
2. **Clean worktree, then backup, before anything destructive.** Uncommitted tracked changes would be swept into the rebuild but missing from the backup.
3. **The user approves the grouping** before any commit is made.
4. **No `git add -p`.** For a file split across commits, write each intermediate state explicitly from the backup's version. For the last commit that touches the file, restore it from the backup exactly.
5. **The integrity gate is absolute.** `git diff <backup>..HEAD` must be empty (allowing only the exclusions listed in step 8) before anything else happens: no summary, no push suggestion, no comment cleanup.
6. **Never force-push.** Tell the user the branch needs a force-push if it was already pushed; they run it.
7. **Keep the backup branch.** Never delete it in this session.

## Process

1. **Find the base.** `git fetch origin`. The base is the branch this will merge into: the PR target or upstream if there is one, otherwise the default (`git symbolic-ref --short refs/remotes/origin/HEAD`). Stacked or release branches have a different base. If unsure, ask now, before anything destructive. Then record the fork point: `FORK=$(git merge-base origin/<base> HEAD)`.
2. **Check it's safe.** `git status --porcelain --untracked-files=no` must print nothing; if it does, stop and ask the user to commit or stash. Check whether the branch is pushed (`git rev-parse --abbrev-ref @{u}`) and whether anyone else has commits on it; if so, warn that this rewrites shared history.
3. **Back up.** `git branch backup/tidy-<YYYYMMDD-HHMM>` at the current tip. Note the name.
4. **Flatten and read.** `git reset --soft $FORK`, then `git diff --cached --stat` and `git diff --cached`. Read every hunk. Also skim `git log $FORK..backup/... --format=%s%n%b` for intent the code doesn't show.
5. **Check for a plan file.** If the branch added a `plans/*.md` from `plan-and-build` (it has a Stage Index block), use its Motivation and stage file lists as hints for grouping, but group by meaning, not by stage. The diff is the truth: flag anything the plan and diff disagree on. Ask the user: **keep** the plan as a final `docs:` commit, or **drop** it from the branch (it stays in the backup)?
6. **Propose the grouping** in the output format below and wait for approval. Group by meaning, not by file: two hunks in one file can belong to different commits. Order so nothing depends on a later commit (types before their users; a refactor before the feature that needs it). Aim for each commit to build and pass tests on its own; say where that isn't achievable.
7. **Rebuild**, one unit at a time, in order:
   - `git reset` (unstage all), then `git add` the files this unit fully owns.
   - Split files: read the final version with `git show <backup>:<path>`, write a version containing only the hunks of this and earlier units, `git add` it. For the last unit that touches the file, `git checkout <backup> -- <path>` instead of hand-writing it.
   - Changesets, if `.changeset/config.json` exists: decide per commit (see `references/changesets.md`): **full** (user-visible change: write a changeset describing the final outcome), **empty** (`--empty`, only if no other commit on the branch has a real changeset and the repo requires one), or **none**. Changeset text is published: nothing internal in it.
   - Commit with a Conventional Commits message, matching the repo's style if it has one.
   - `git show --stat HEAD`: only the expected files. If wrong, `git reset --soft HEAD~1`, fix, retry.
8. **Integrity gate.** Run `git diff <backup>..HEAD`. It must print nothing. The only permitted exclusions are files this skill deliberately changed, added as pathspecs: `':(exclude).changeset/*.md'` if changesets were rewritten, `':(exclude)plans/<name>.md'` if the plan was dropped. Don't eyeball a non-empty diff and decide it's fine. If it isn't empty, find the unit that lost or duplicated a hunk, fix it (`git reset --soft` back to that commit if needed, or start again from the backup), and re-run until empty.
9. **Report** the new history (`git log --oneline $FORK..HEAD`) and the gate result. If the branch was pushed, say it needs `git push --force-with-lease` and that the user should run it. Mention the backup branch and how to restore it.

## Output format

Grouping proposal (step 6):

```markdown
**Base:** origin/main (fork point a1b2c3d). **Backup:** backup/tidy-20261202-1430. **Now:** 9 commits → **proposed:** 3

1. `refactor(sync): extract chunked() helper`
   - Files: src/util/chunk.ts (new), src/util/index.ts
   - Changeset: none
2. `fix(sync): batch inserts to stay under the rate limit`
   - Files: src/sync/writer.ts, src/sync/config.ts
   - Split file: src/sync/writer.ts (batching hunks here; retry hunk in 3)
   - Changeset: patch, "Sync now batches database writes, so large imports no longer fail with rate-limit errors."
3. `feat(sync): retry failed batches`
   - Files: src/sync/writer.ts (rest), src/sync/writer.test.ts
   - Changeset: minor

Plan file `plans/batched-sync.md`: keep as a 4th `docs:` commit, or drop?
Approve, or tell me what to change.
```

Final report (step 9):

```markdown
**Done:** 9 commits → 3. Integrity gate: `git diff backup/tidy-20261202-1430..HEAD` is empty (excluding .changeset/*.md).
[git log --oneline]
**Next:** branch was pushed, so it needs `git push --force-with-lease` (run it yourself). Restore any time with `git reset --hard backup/tidy-20261202-1430`.
```

## Adapting to your setup

- **Claude Code:** use Read and Write for intermediate file states, not shell heredocs, so edits are exact. Run on the strongest model available: the intermediate-state writing is where weaker models drop a hunk. If the repo blocks commits on hooks, let them run; never `--no-verify`.
- **Codex:** same flow; apply intermediate states as full-file writes, then re-read with `git diff --cached` before each commit.
- **OpenClaw and similar, or no shell:** produce the grouping and the exact command sequence for the user to run, including the gate. Don't claim it was done.
- **No changesets:** skip the changeset step entirely. Other release tools (release-please, semantic-release) read commit messages instead, so get the Conventional Commit type right.

## Common failure modes

- **Resetting to `origin/main`** instead of the fork point, silently reverting other people's work.
- **Starting with a dirty tree**, so the user's in-progress edits vanish into the rebuild.
- **Reconstructing a file from memory** instead of from `git show <backup>:<path>`.
- **Treating the gate as advisory:** "only a whitespace difference" is still a failed gate.
- **Grouping by file or by original commit** instead of by meaning.
- **Changesets that describe the journey** ("refactored X, then fixed Y") instead of the outcome a user sees.
- **Force-pushing**, or telling the user it's safe to without saying it rewrites shared history.

## Next step

If comments haven't been cleaned yet, run `clean-comments` before this skill, not after, so its edits land in the right commits. After tidying, the branch is ready for a PR; opening it is the user's call.

## References

- `references/worked-example.md`: a nine-commit agent-built branch rebuilt into three, including a split file and a dropped plan.
- `references/edge-cases.md`: pushed branches, merge commits in the branch, binary files, renames, failed hooks, a non-empty gate.
- `references/changesets.md`: the full / empty / none decision and what a good changeset says.
references/changesets.mdView this file on GitHub
# Changesets

Only applies if the repo uses [Changesets](https://github.com/changesets/changesets) (there's a `.changeset/config.json`). Otherwise skip this file.

## Per-commit decision

| Commit | Changeset |
|---|---|
| Changes what a package's users get: feature, fix, behaviour change, runtime dependency bump, breaking change | **Full**: a `.changeset/<name>.md` naming each affected package and its bump (`patch`, `minor`, `major`) |
| Tests, CI, docs, tooling, refactor with no visible effect, **and** no other commit on the branch has a full changeset, **and** the repo's CI requires one | **Empty**: `pnpm changeset --empty` (or the repo's equivalent), which writes a changeset with no packages |
| Same as above, but the branch already has a full changeset, or CI doesn't require one | **None** |

One full changeset per user-visible commit. Don't add empty changesets next to real ones: they're noise.

## Bump type

- `patch`: bug fix or internal change users might notice (performance, error messages).
- `minor`: new capability, backwards compatible.
- `major`: anything that breaks existing use. When unsure between minor and major, ask.
- In a monorepo, bump only the packages whose published code changed.

## Writing it

- First line is plain prose about the outcome, as it'll read in `CHANGELOG.md`: "Sync now batches database writes, so large imports no longer fail with rate-limit errors." No `fix:` prefix, no "refactored", no ticket numbers.
- Describe the final state of this commit, not how it got there.
- **It's public.** Changesets are published to the changelog and often to npm and release notes. No internal service names, private URLs, incident details, customer names or security specifics. If the only honest description would leak something, use an empty changeset and tell the user why.

## Existing changesets on the branch

The branch may already have changesets written during development. Read them, then delete and rewrite them to match the new commits. That's why the integrity gate excludes `.changeset/*.md`, and only that path: a change to `.changeset/config.json` is still caught.
references/edge-cases.mdView this file on GitHub
# Edge cases

## The branch is shared
- Someone else has commits on it, or another branch is based on it: rewriting breaks their work. Stop and ask. Offer to produce the grouping as a suggestion for the PR description instead.

## Can't tell the base
- No upstream, no PR, several candidate bases (stacked branches): ask. The whole skill depends on the fork point.

## Merge commits inside the branch
- If the user merged `main` into the branch, `git merge-base` returns the latest merged point, and the flat diff contains only the branch's own work. Good. But the backup contains the merge, so the gate still compares like with like. Mention that the rebuilt branch has no merge commit.

## Dirty worktree
- Tracked changes: stop. Untracked files are fine; nothing stages them unless they're in the diff.

## Binary files, renames, deletions, mode changes
- Binary files can't be split: assign each to one unit and `git checkout <backup> -- <path>` it.
- Renames: stage both the deletion and the addition in the same unit (`git add -A <old> <new>`).
- Mode changes (executable bit) live in the index; restoring from the backup carries them.

## A commit hook fails
- Read the error. Usually the unit isn't self-contained (a type it needs is in a later unit). Move the smallest piece forward, or merge the two units, and tell the user. Never `--no-verify`.

## The gate isn't empty
1. Don't panic: the backup is intact.
2. Read the diff. A missing hunk means a split file lost it; a duplicated hunk means two units both wrote it.
3. Fix the owning unit (soft-reset back to it and redo from there), or `git reset --hard <backup>` and repeat from step 4.
4. Re-run until empty. Never report success on a non-empty gate.

## Huge diffs
- Work through the stat first, group whole files where possible, and split only where meaning really differs. More than about eight commits is usually over-splitting.

## The user wants one commit
- That's a squash: `git reset --soft $FORK && git commit`. The gate still applies.

## The user also wants it rebased
- Finish and pass the gate first. Then rebase onto the latest base as a separate step, and re-run the tests: conflicts there are real and need the user's attention.

## A plan file that isn't from plan-and-build
- Any other doc under `plans/` is just a file in the diff. Group it like anything else.
references/worked-example.mdView this file on GitHub
# Worked example

Branch `feat/batched-sync`, built with `plan-and-build`, then `clean-comments`. The repo uses changesets. `main` has moved on by four commits since the branch was cut.

```text
$ git log --oneline origin/main..HEAD
f9e8d7c docs: trim branch comments
e8d7c6b feat(sync): S3 retry failed batches
d7c6b5a test(sync): S2 batch writer tests
c6b5a4f fix(sync): S1B batch inserts
b5a4f3e refactor(util): S1A chunk helper
a4f3e2d docs(plans): add batched-sync plan
9f8e7d6 wip
8e7d6c5 fix typo
7d6c5b4 wip
```

## 1–3. Base, safety, backup

```bash
git fetch origin
git symbolic-ref --short refs/remotes/origin/HEAD   # origin/main; no PR target yet, so base = main
FORK=$(git merge-base origin/main HEAD)             # 3c2b1a0, NOT origin/main's tip
git status --porcelain --untracked-files=no          # empty
git rev-parse --abbrev-ref @{u}                      # origin/feat/batched-sync: pushed, only my commits
git branch backup/tidy-20261202-1430
```

Note: `origin/main` is four commits ahead of `3c2b1a0`. Resetting to `origin/main` would stage reversals of those four commits.

## 4–5. Flatten, read, plan file

```bash
git reset --soft $FORK
git diff --cached --stat
#  .changeset/quick-cats-run.md |  5 +
#  plans/batched-sync.md        | 96 +
#  src/sync/config.ts           |  2 +-
#  src/sync/writer.test.ts      | 58 +
#  src/sync/writer.ts           | 41 +-
#  src/util/chunk.ts            | 14 +
#  src/util/index.ts            |  1 +
```

`plans/batched-sync.md` has a Stage Index block: it's a `plan-and-build` plan. Its stages were S1A (helper), S1B (batching), S2 (tests), S3 (retries). Tests in S2 cover both batching and retries, so stage order isn't commit order. One diff hunk (`config.ts`, `BATCH_SIZE`) isn't in the plan: flagged.

The existing changeset says "Refactored the writer and added a chunk helper, then batching" — a journey, not an outcome. It'll be rewritten.

## 6. Proposal (approved as-is, plan dropped)

```markdown
**Base:** origin/main (fork point 3c2b1a0). **Backup:** backup/tidy-20261202-1430. **Now:** 9 commits → **proposed:** 3

1. `refactor(util): add chunked() helper`
   - Files: src/util/chunk.ts (new), src/util/index.ts
   - Changeset: none
2. `fix(sync): batch inserts to stay under the rate limit`
   - Files: src/sync/config.ts
   - Split files: src/sync/writer.ts (batching only), src/sync/writer.test.ts (batching tests only)
   - Changeset: patch, "Sync now batches database writes, so large imports no longer fail with rate-limit errors."
3. `feat(sync): retry failed batches`
   - Files: rest of src/sync/writer.ts and src/sync/writer.test.ts
   - Changeset: minor, "Sync retries a failed batch up to five times before reporting an error."

Note: the BATCH_SIZE change in config.ts isn't in the plan; I've put it in commit 2.
Plan file `plans/batched-sync.md`: keep as a 4th `docs:` commit, or drop?
```

User: "drop the plan, otherwise go."

## 7. Rebuild

Commit 1: whole files.

```bash
git reset
git add src/util/chunk.ts src/util/index.ts
git commit -m "refactor(util): add chunked() helper"
git show --stat HEAD   # 2 files
```

Commit 2: `writer.ts` is split. Read `git show backup/tidy-20261202-1430:src/sync/writer.ts`, write a version with the batching loop but without the retry wrapper and `MAX_RETRIES`, same for the test file (batching `describe` block only). Delete the old changeset and write the new one.

```bash
rm .changeset/quick-cats-run.md     # never existed at the fork point, so nothing to unstage after `git reset`
# write .changeset/batched-writes.md (patch)
git reset
git add src/sync/config.ts src/sync/writer.ts src/sync/writer.test.ts .changeset/batched-writes.md
git commit -m "fix(sync): batch inserts to stay under the rate limit"
pnpm test src/sync   # passes at this commit
```

Commit 3: last unit for both split files, so restore exactly from the backup.

```bash
git checkout backup/tidy-20261202-1430 -- src/sync/writer.ts src/sync/writer.test.ts
# write .changeset/retry-batches.md (minor)
git add src/sync/writer.ts src/sync/writer.test.ts .changeset/retry-batches.md
git commit -m "feat(sync): retry failed batches"
```

Plan dropped: `rm plans/batched-sync.md` (it's only in the working tree, never staged).

## 8. Gate

```bash
git diff backup/tidy-20261202-1430..HEAD -- . ':(exclude).changeset/*.md' ':(exclude)plans/batched-sync.md'
# (no output)
```

## 9. Report

```markdown
**Done:** 9 commits → 3. Integrity gate: `git diff backup/tidy-20261202-1430..HEAD` is empty (excluding .changeset/*.md and the dropped plans/batched-sync.md).

c3d4e5f feat(sync): retry failed batches
b2c3d4e fix(sync): batch inserts to stay under the rate limit
a1b2c3d refactor(util): add chunked() helper

**Next:** the branch was already pushed, so it needs `git push --force-with-lease` (run it yourself). The plan file is still in the backup branch if you want it. Restore any time with `git reset --hard backup/tidy-20261202-1430`. Rebasing onto the latest main is a separate step, if you want it.
```