Git workflow and versioning

Keeps git work in atomic commits on short-lived branches, with typed messages, a pre-commit check for secrets and tests, worktrees for parallel agents, semver bumps, tags and a human changelog. Use when committing, branching, opening a PR or cutting a release.

Git & PRsPack: Agent Skills by Addy Osmani355 linesgit-workflow-and-versioning
Author
Source
addyosmani/agent-skills/skills/git-workflow-and-versioning @ 8c99fa3
License
MIT · Copyright (c) 2025 Addy Osmani

About this skill

What it does

The skill sets git habits for agent work: trunk-based development with branches merged within one to three days, a commit after every verified slice, one logical change per commit, refactors and formatting kept apart from behaviour changes, and about 100 lines per commit or PR, with anything near 1,000 lines split. Messages follow <type>: <short description> (feat, fix, refactor, test, docs, chore) with a body that explains why.

Around that it covers git worktrees for agents working in parallel, a save-point loop (a failing test sends the agent back to the last commit), a change summary after each edit with a "didn't touch" section, and a pre-commit routine: read the staged diff, grep it for secrets, run tests, lint and type check. The release part covers semantic versioning ("when unsure whether a change is breaking, assume it is"), tags as the source of the version number, and a changelog grouped by Added, Changed, Fixed, Deprecated, Removed and Security, written in the same change. The folder holds only SKILL.md and the licence.

When to use it, and when not

The skill says "always": its description covers any code change, commits, branches, conflicts, splitting a messy working tree, pull requests, pushes, releases, version bumps and changelog entries.

Two things to know first. The commit format is the skill's own; if your repository uses another convention, tell the agent. And the save-point section suggests git reset --hard HEAD when an agent goes off the rails, which discards uncommitted work.

How to run it

The install command below puts SKILL.md and the licence in place. The agent picks the skill up by its description; to call it yourself:

  • Claude Code: /git-workflow-and-versioning, or ask for the skill by name.
  • Codex: $git-workflow-and-versioning.
  • Cursor: type / in the Agent chat and pick git-workflow-and-versioning.

Example: /git-workflow-and-versioning Split the changes in my working tree into atomic commits and tell me which version bump the next release needs.

It refers to Multi-axis code review for splitting large changes, Deprecation and migration for breaking changes and Shipping and launch for the release itself; install them for the whole path.

How it differs from similar skills

Our git-workflow pack has narrower skills that start from the repository. Commit message writer reads git log and follows the existing convention, and Changelog writer builds notes from the commits and PRs since the last tag. Release checklist gives a go/no-go report and never tags or pushes without your confirmation. Using git worktrees goes further on isolated workspaces, and Git guardrails for Claude Code blocks commands such as reset --hard with a hook. Merge conflict resolver takes conflicts, which this skill names in its description but gives no steps for: it reads both sides of each conflict and checks the result with the build and tests. Conventional commit messages from Sentry has its own commit format, with a longer type list and ref instead of refactor. This skill is the broad policy across all of these; for any single step, the narrow skill is more careful.

Install

Run one command — it saves SKILL.md and the files it uses into your agent's skills folder. Claude Code and Codex pick up a new skill without a restart; if it does not show up, restart the agent.

Claude Code — macOS, Linux
curl -fsSL --create-dirs -o ~/.claude/skills/git-workflow-and-versioning/SKILL.md https://anymodel.org/en/skills/addy-osmani/git-workflow-and-versioning/SKILL.md -o ~/.claude/skills/git-workflow-and-versioning/LICENSE https://anymodel.org/en/skills/addy-osmani/git-workflow-and-versioning/LICENSE
Codex, Cursor — macOS, Linux
curl -fsSL --create-dirs -o ~/.agents/skills/git-workflow-and-versioning/SKILL.md https://anymodel.org/en/skills/addy-osmani/git-workflow-and-versioning/SKILL.md -o ~/.agents/skills/git-workflow-and-versioning/LICENSE https://anymodel.org/en/skills/addy-osmani/git-workflow-and-versioning/LICENSE
Claude Code — Windows PowerShell
foreach ($f in 'SKILL.md','LICENSE') { $p = Join-Path "$HOME\.claude\skills\git-workflow-and-versioning" $f; New-Item -ItemType Directory -Force (Split-Path $p) | Out-Null; Invoke-WebRequest "https://anymodel.org/en/skills/addy-osmani/git-workflow-and-versioning/$f" -UseBasicParsing -OutFile $p }
Codex, Cursor — Windows PowerShell
foreach ($f in 'SKILL.md','LICENSE') { $p = Join-Path "$HOME\.agents\skills\git-workflow-and-versioning" $f; New-Item -ItemType Directory -Force (Split-Path $p) | Out-Null; Invoke-WebRequest "https://anymodel.org/en/skills/addy-osmani/git-workflow-and-versioning/$f" -UseBasicParsing -OutFile $p }

Any other agent: save the file into its skills folder, or give it the link to the file: https://anymodel.org/en/skills/addy-osmani/git-workflow-and-versioning/SKILL.md

SKILL.md

Raw

Git Workflow and Versioning

Overview

Git is your safety net. Treat commits as save points, branches as sandboxes, and history as documentation. With AI agents generating code at high speed, disciplined version control is the mechanism that keeps changes manageable, reviewable, and reversible.

When to Use

Always. Every code change flows through git.

Core Principles

Keep main always deployable. Work in short-lived feature branches that merge back within 1-3 days. Long-lived development branches are hidden costs — they diverge, create merge conflicts, and delay integration. DORA research consistently shows trunk-based development correlates with high-performing engineering teams.

main ──●──●──●──●──●──●──●──●──●──  (always deployable)
        ╲      ╱  ╲    ╱
         ●──●─╱    ●──╱    ← short-lived feature branches (1-3 days)

This is the recommended default. Teams using gitflow or long-lived branches can adapt the principles (atomic commits, small changes, descriptive messages) to their branching model — the commit discipline matters more than the specific branching strategy.

  • Dev branches are costs. Every day a branch lives, it accumulates merge risk.
  • Release branches are acceptable. When you need to stabilize a release while main moves forward.
  • Feature flags > long branches. Prefer deploying incomplete work behind flags rather than keeping it on a branch for weeks.

1. Commit Early, Commit Often

Each successful increment gets its own commit. Don't accumulate large uncommitted changes.

Work pattern:
  Implement slice → Test → Verify → Commit → Next slice

Not this:
  Implement everything → Hope it works → Giant commit

Commits are save points. If the next change breaks something, you can revert to the last known-good state instantly.

2. Atomic Commits

Each commit does one logical thing:

# Good: Each commit is self-contained
git log --oneline
a1b2c3d Add task creation endpoint with validation
d4e5f6g Add task creation form component
h7i8j9k Connect form to API and add loading state
m1n2o3p Add task creation tests (unit + integration)

# Bad: Everything mixed together
git log --oneline
x1y2z3a Add task feature, fix sidebar, update deps, refactor utils

3. Descriptive Messages

Commit messages explain the why, not just the what:

# Good: Explains intent
feat: add email validation to registration endpoint

Prevents invalid email formats from reaching the database.
Uses Zod schema validation at the route handler level,
consistent with existing validation patterns in auth.ts.

# Bad: Describes what's obvious from the diff
update auth.ts

Format:

<type>: <short description>

<optional body explaining why, not what>

Types:

  • feat — New feature
  • fix — Bug fix
  • refactor — Code change that neither fixes a bug nor adds a feature
  • test — Adding or updating tests
  • docs — Documentation only
  • chore — Tooling, dependencies, config

4. Keep Concerns Separate

Don't combine formatting changes with behavior changes. Don't combine refactors with features. Each type of change should be a separate commit — and ideally a separate PR:

# Good: Separate concerns
git commit -m "refactor: extract validation logic to shared utility"
git commit -m "feat: add phone number validation to registration"

# Bad: Mixed concerns
git commit -m "refactor validation and add phone number field"

Separate refactoring from feature work. A refactoring change and a feature change are two different changes — submit them separately. This makes each change easier to review, revert, and understand in history. Small cleanups (renaming a variable) can be included in a feature commit at reviewer discretion.

5. Size Your Changes

Target ~100 lines per commit/PR. Changes over ~1000 lines should be split. See the splitting strategies in code-review-and-quality for how to break down large changes.

~100 lines  → Easy to review, easy to revert
~300 lines  → Acceptable for a single logical change
~1000 lines → Split into smaller changes

Branching Strategy

Feature Branches

main (always deployable)
  │
  ├── feature/task-creation    ← One feature per branch
  ├── feature/user-settings    ← Parallel work
  └── fix/duplicate-tasks      ← Bug fixes
  • Branch from main (or the team's default branch)
  • Keep branches short-lived (merge within 1-3 days) — long-lived branches are hidden costs
  • Delete branches after merge
  • Prefer feature flags over long-lived branches for incomplete features

Branch Naming

feature/<short-description>   → feature/task-creation
fix/<short-description>       → fix/duplicate-tasks
chore/<short-description>     → chore/update-deps
refactor/<short-description>  → refactor/auth-module

Working with Worktrees

For parallel AI agent work, use git worktrees to run multiple branches simultaneously:

# Create a worktree for a feature branch
git worktree add ../project-feature-a feature/task-creation
git worktree add ../project-feature-b feature/user-settings

# Each worktree is a separate directory with its own branch
# Agents can work in parallel without interfering
ls ../
  project/              ← main branch
  project-feature-a/    ← task-creation branch
  project-feature-b/    ← user-settings branch

# When done, merge and clean up
git worktree remove ../project-feature-a

Benefits:

  • Multiple agents can work on different features simultaneously
  • No branch switching needed (each directory has its own branch)
  • If one experiment fails, delete the worktree — nothing is lost
  • Changes are isolated until explicitly merged

The Save Point Pattern

Agent starts work
    │
    ├── Makes a change
    │   ├── Test passes? → Commit → Continue
    │   └── Test fails? → Revert to last commit → Investigate
    │
    ├── Makes another change
    │   ├── Test passes? → Commit → Continue
    │   └── Test fails? → Revert to last commit → Investigate
    │
    └── Feature complete → All commits form a clean history

This pattern means you never lose more than one increment of work. If an agent goes off the rails, git reset --hard HEAD takes you back to the last successful state.

Change Summaries

After any modification, provide a structured summary. This makes review easier, documents scope discipline, and surfaces unintended changes:

CHANGES MADE:
- src/routes/tasks.ts: Added validation middleware to POST endpoint
- src/lib/validation.ts: Added TaskCreateSchema using Zod

THINGS I DIDN'T TOUCH (intentionally):
- src/routes/auth.ts: Has similar validation gap but out of scope
- src/middleware/error.ts: Error format could be improved (separate task)

POTENTIAL CONCERNS:
- The Zod schema is strict — rejects extra fields. Confirm this is desired.
- Added zod as a dependency (72KB gzipped) — already in package.json

This pattern catches wrong assumptions early and gives reviewers a clear map of the change. The "DIDN'T TOUCH" section is especially important — it shows you exercised scope discipline and didn't go on an unsolicited renovation.

Pre-Commit Hygiene

Before every commit:

# 1. Check what you're about to commit
git diff --staged

# 2. Ensure no secrets (lists matching file names only — any output means review them)
git diff --staged -i -G'password|secret|api_key|token' --name-only

# 3. Run tests
npm test

# 4. Run linting
npm run lint

# 5. Run type checking
npx tsc --noEmit

Automate this with git hooks:

// package.json (using lint-staged + husky)
{
  "lint-staged": {
    "*.{ts,tsx}": ["eslint --fix", "prettier --write"],
    "*.{json,md}": ["prettier --write"]
  }
}

Handling Generated Files

  • Commit generated files only if the project expects them (e.g., package-lock.json, Prisma migrations)
  • Don't commit build output (dist/, .next/), environment files (.env), or IDE config (.vscode/settings.json unless shared)
  • Have a .gitignore that covers: node_modules/, dist/, .env, .env.local, *.pem

Using Git for Debugging

# Find which commit introduced a bug
git bisect start
git bisect bad HEAD
git bisect good <known-good-commit>
# Git checkouts midpoints; run your test at each to narrow down

# View what changed recently
git log --oneline -20
git diff HEAD~5..HEAD -- src/

# Find who last changed a specific line
git blame src/services/task.ts

# Search commit messages for a keyword
git log --grep="validation" --oneline

Release & Versioning

Commits are how you track change; a version is how your consumers track it. The moment anything else depends on your code — another team, a published package, a deployed client — "latest on main" stops being a sufficient answer to "what am I running, and is it safe to upgrade?" A version number and a changelog are the contract that answers it.

Semantic Versioning

For anything with consumers, version MAJOR.MINOR.PATCH and let the number carry meaning:

  MAJOR  breaking change — consumers must change their code to upgrade
  MINOR  new functionality, backward-compatible — safe to upgrade
  PATCH  bug fix, backward-compatible — safe to upgrade

The number is a promise, so make the code match it. A "patch" that changes behavior consumers relied on is a major change wearing a disguise (Hyrum's Law — see the api-and-interface-design skill). When unsure whether a change is breaking, assume it is; a surprise major is far cheaper than a broken consumer.

Tag the release, and let the tag be the source of truth

A release is an immutable point in history, not a moving branch. Tag it so it can always be reproduced:

git tag -a v1.4.0 -m "Release 1.4.0"
git push origin v1.4.0

Derive the version from the tag rather than hand-editing it in scattered files, so the artifact, the tag, and the changelog can never disagree.

Keep a changelog written for humans

A changelog is not git log. It's the curated, consumer-facing answer to "what changed and do I care?" — grouped by Added / Changed / Fixed / Deprecated / Removed / Security, newest on top, every entry phrased around user impact, not internal mechanics.

## [1.4.0] - 2025-06-12
### Added
- Bulk task import via CSV
### Fixed
- Timezone drift in recurring task due dates
### Deprecated
- `GET /v1/tasks/all` — use the paginated `GET /v1/tasks` (removal in 2.0)

Write the entry in the same change that makes the change, while the impact is fresh — not reconstructed from commit archaeology at release time. Breaking changes get a migration note and a deprecation window (follow the deprecation-and-migration skill); shipping the actual release is the shipping-and-launch skill's job — this section is the versioning contract that feeds it.

Common Rationalizations

Rationalization Reality
"I'll commit when the feature is done" One giant commit is impossible to review, debug, or revert. Commit each slice.
"The message doesn't matter" Messages are documentation. Future you (and future agents) will need to understand what changed and why.
"I'll squash it all later" Squashing destroys the development narrative. Prefer clean incremental commits from the start.
"Branches add overhead" Short-lived branches are free and prevent conflicting work from colliding. Long-lived branches are the problem — merge within 1-3 days.
"I'll split this change later" Large changes are harder to review, riskier to deploy, and harder to revert. Split before submitting, not after.
"I don't need a .gitignore" Until .env with production secrets gets committed. Set it up immediately.
"It's just a small fix, bump the patch" Check what consumers can observe. A behavior change they relied on is a major, whatever the diff size.
"The changelog is just the commit log" Commits are for you; the changelog is for consumers, curated by impact. Generating one from raw commits buries what matters.
"We'll write the changelog at release time" By then the impact is reconstructed from memory and half of it is missing. Write the entry with the change.

Red Flags

  • Large uncommitted changes accumulating
  • Commit messages like "fix", "update", "misc"
  • Formatting changes mixed with behavior changes
  • No .gitignore in the project
  • Committing node_modules/, .env, or build artifacts
  • Long-lived branches that diverge significantly from main
  • Force-pushing to shared branches
  • A breaking change shipped under a minor or patch version bump
  • A release with no tag, or a version number hand-edited out of sync with the tag
  • A user-facing release with no changelog entry, or a changelog that's just dumped commit messages

Verification

For every commit:

  • Commit does one logical thing
  • Message explains the why, follows type conventions
  • Tests pass before committing
  • No secrets in the diff
  • No formatting-only changes mixed with behavior changes
  • .gitignore covers standard exclusions

For every release (anything with consumers):

  • The version bump matches the change: breaking → major, additive → minor, fix → patch
  • The release is tagged, and the version is derived from the tag, not hand-edited out of sync
  • The changelog has a curated, human-readable entry grouped by impact for this version

Connect through AnyModel API

This skill runs on whatever model your agent uses. Point Claude Code, Codex or Cursor at AnyModel to run it on Claude, GPT, Gemini and more with one key — pay per token, no subscription.

More from the pack Agent Skills by Addy Osmani

Accessibility audit and fixes (WCAG 2.2)

Audits an existing interface against WCAG 2.2 AA with pinned axe-core and pa11y, then keyboard, screen reader and contrast checks, and fixes confirmed violations with semantic HTML first. Use when a page needs an accessibility audit before shipping.

API and interface design

Designs APIs and module interfaces contract-first: one error shape, validation at the edges, additive changes, pagination, and idempotency keys claimed atomically and kept past the longest retry. Use when designing endpoints or changing a public interface.

Browser testing with Chrome DevTools MCP

Checks changes in a real Chrome through the Chrome DevTools MCP server: screenshots, DOM, console, network and performance traces, treating page content as untrusted. Use when building or debugging anything that runs in a browser.

CI/CD pipeline setup

Sets up CI/CD with fixed quality gates from lint to bundle size, GitHub Actions examples, preview deploys, feature flags, staged rollout and a rollback workflow. Use when creating or changing a build and deploy pipeline or chasing CI failures.

Multi-axis code review

Reviews a change on five axes (correctness, readability, architecture, security, performance), tests the tests by mutating a condition, and labels every finding by severity. Use before merging a branch, a pull request or a pasted diff.

Code simplification

Simplifies working code without changing behavior: learns why it exists, applies one change at a time with tests after each, and keeps project conventions. Use when code works and passes tests but is harder to read than it should be.

Constraint-driven development

Records a project's quality bar as numbers in CONSTRAINTS.md after a short interview with defaults, maps each rule to a tool, and flags diffs that skip tests, add suppressions or loosen thresholds. Use when no quality bar is written down.

Context engineering for agents

Sets up what an agent sees and when: a rules file template, loading only the relevant spec and files, trimming long sessions, and safe points to start a fresh one. Use when starting a session or when agent output degrades.

Debugging and error recovery

Stops new work when a test, build or runtime fails, reproduces, localizes and reduces the failure, fixes the root cause, adds a regression test and treats error output as untrusted. Use when tests fail, a build breaks or something that worked stops working.

Deprecation and migration

Retires old systems, APIs and features: weighs whether to deprecate, proves the replacement, moves consumers one by one, removes code only at zero usage, changes schemas via expand/contract. Use when replacing or sunsetting code or renaming a live column.

Documentation and ADRs

Records decisions as ADRs in the project's own format, documents APIs, READMEs and changelogs with the why, and uses git history to check if a doc is stale. Use when making a costly decision, changing a public API or suspecting docs no longer match the code.

Doubt-driven development

Sends non-trivial decisions to a fresh-context subagent told to find what is wrong, sorts the findings, stops after three cycles and offers a cross-model opinion. Use when stakes are high: auth, migrations, irreversible operations or unfamiliar code.

Frontend UI engineering

Builds UI components and pages on the project's design system: composition, simple state, WCAG 2.1 AA, mobile-first layouts, loading, empty and error states, no generic AI look. Use when building or changing a user-facing interface.

Idea refinement

Refines a raw idea in three phases: sharpening questions and five to eight variations, two or three directions tested for value and feasibility, then a one-pager with MVP scope and a Not Doing list. Use when an idea is vague or a plan needs stress-testing.

Incremental implementation

Builds changes in thin vertical, contract-first or risk-first slices, each tested, verified and committed before the next, with strict scope, feature flags and revertable steps. Use when a change spans several files or a task is too big to land in one step.

Interview me

Interviews the user one question at a time, each with a guessed answer and a confidence number, until the agent can predict the next replies, then confirms a statement of intent before any spec or code. Use when a request leaves who, why or success unclear.

Observability and instrumentation

Instruments a feature with structured JSON logs and request IDs, RED and USE metrics with bounded labels, OpenTelemetry traces and symptom-based alerts with runbooks, then tests the telemetry. Use when a feature, job or integration is headed for production.

Performance optimization

Optimizes by measurement: takes a baseline, fixes the one proven bottleneck, re-measures against noise and reverts neutral changes, with worked fixes for N+1 queries, indexes, caching and bundles. Use when something is slow or misses a performance budget.

Planning and task breakdown

Breaks a spec into small vertical-slice tasks with acceptance criteria, verification steps, sizes, dependency order and checkpoints, saved to tasks/todo.md or a named tracker. Use when a spec is ready but the work is too big to start in one go.

Security hardening

Hardens code with a short threat model, always, ask-first and never rules, and patterns for injection, XSS, access control, SSRF, secrets, dependencies, personal data and LLM output. Use when code handles user input, auth, sensitive data or outside services.

Shipping and launch

Prepares a production launch with a pre-launch checklist, a feature-flag rollout from 5% to 100%, thresholds for advancing or rolling back, an error-budget gate, a rollback plan and first-hour checks. Use when a feature or major change is about to ship.

Source-driven development

Grounds framework code in official docs: reads exact versions from the dependency file, fetches the relevant page, follows the documented API and cites full URLs, flagging anything unverified. Use when framework-specific code must match the version in use.

Spec-driven development

Writes a spec before code, surfacing assumptions and covering objective, commands, structure, style, tests and boundaries, then gates plan, tasks and code on approval, with capability maps and delta specs. Use when new work has vague requirements.

Test-driven development, red-green-refactor

Drives changes with red-green-refactor: finds the repository's own test commands, writes the failing test first, reproduces each bug with a test before fixing it, and sets rules on mocks and naming. Use when adding logic, fixing a bug or changing behavior.