1
---
2
name: git-workflow-and-versioning
3
description: Structures git workflow practices. Use when making any code change. Use when committing, branching, resolving conflicts, splitting uncommitted work in a messy working tree into clean atomic commits, opening or reviewing a pull request (PR), pushing to a remote, or when you need to organize work across multiple parallel streams. Use when cutting a release, choosing a semantic version bump, tagging, or writing a changelog. Use when asked to write a commit message or a changelog entry for a change, or to split a change into commits, even when the diff is pasted inline and the message seems easy to write from it.
4
---
5
6
# Git Workflow and Versioning
7
8
## Overview
9
10
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.
11
12
## When to Use
13
14
Always. Every code change flows through git.
15
16
## Core Principles
17
18
### Trunk-Based Development (Recommended)
19
20
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.
21
22
```
23
main ──●──●──●──●──●──●──●──●──●── (always deployable)
24
╲ ╱ ╲ ╱
25
●──●─╱ ●──╱ ← short-lived feature branches (1-3 days)
26
```
27
28
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.
29
30
- **Dev branches are costs.** Every day a branch lives, it accumulates merge risk.
31
- **Release branches are acceptable.** When you need to stabilize a release while main moves forward.
32
- **Feature flags > long branches.** Prefer deploying incomplete work behind flags rather than keeping it on a branch for weeks.
33
34
### 1. Commit Early, Commit Often
35
36
Each successful increment gets its own commit. Don't accumulate large uncommitted changes.
37
38
```
39
Work pattern:
40
Implement slice → Test → Verify → Commit → Next slice
41
42
Not this:
43
Implement everything → Hope it works → Giant commit
44
```
45
46
Commits are save points. If the next change breaks something, you can revert to the last known-good state instantly.
47
48
### 2. Atomic Commits
49
50
Each commit does one logical thing:
51
52
```
53
# Good: Each commit is self-contained
54
git log --oneline
55
a1b2c3d Add task creation endpoint with validation
56
d4e5f6g Add task creation form component
57
h7i8j9k Connect form to API and add loading state
58
m1n2o3p Add task creation tests (unit + integration)
59
60
# Bad: Everything mixed together
61
git log --oneline
62
x1y2z3a Add task feature, fix sidebar, update deps, refactor utils
63
```
64
65
### 3. Descriptive Messages
66
67
Commit messages explain the *why*, not just the *what*:
68
69
```
70
# Good: Explains intent
71
feat: add email validation to registration endpoint
72
73
Prevents invalid email formats from reaching the database.
74
Uses Zod schema validation at the route handler level,
75
consistent with existing validation patterns in auth.ts.
76
77
# Bad: Describes what's obvious from the diff
78
update auth.ts
79
```
80
81
**Format:**
82
```
83
<type>: <short description>
84
85
<optional body explaining why, not what>
86
```
87
88
**Types:**
89
- `feat` — New feature
90
- `fix` — Bug fix
91
- `refactor` — Code change that neither fixes a bug nor adds a feature
92
- `test` — Adding or updating tests
93
- `docs` — Documentation only
94
- `chore` — Tooling, dependencies, config
95
96
### 4. Keep Concerns Separate
97
98
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:
99
100
```
101
# Good: Separate concerns
102
git commit -m "refactor: extract validation logic to shared utility"
103
git commit -m "feat: add phone number validation to registration"
104
105
# Bad: Mixed concerns
106
git commit -m "refactor validation and add phone number field"
107
```
108
109
**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.
110
111
### 5. Size Your Changes
112
113
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.
114
115
```
116
~100 lines → Easy to review, easy to revert
117
~300 lines → Acceptable for a single logical change
118
~1000 lines → Split into smaller changes
119
```
120
121
## Branching Strategy
122
123
### Feature Branches
124
125
```
126
main (always deployable)
127
│
128
├── feature/task-creation ← One feature per branch
129
├── feature/user-settings ← Parallel work
130
└── fix/duplicate-tasks ← Bug fixes
131
```
132
133
- Branch from `main` (or the team's default branch)
134
- Keep branches short-lived (merge within 1-3 days) — long-lived branches are hidden costs
135
- Delete branches after merge
136
- Prefer feature flags over long-lived branches for incomplete features
137
138
### Branch Naming
139
140
```
141
feature/<short-description> → feature/task-creation
142
fix/<short-description> → fix/duplicate-tasks
143
chore/<short-description> → chore/update-deps
144
refactor/<short-description> → refactor/auth-module
145
```
146
147
## Working with Worktrees
148
149
For parallel AI agent work, use git worktrees to run multiple branches simultaneously:
150
151
```bash
152
# Create worktrees on new feature branches
153
git worktree add -b feature/task-creation ../project-feature-a
154
git worktree add -b feature/user-settings ../project-feature-b
155
156
# For an existing branch, pass the path first:
157
# git worktree add ../project-feature-a feature/task-creation
158
159
# Each worktree is a separate directory with its own branch
160
# Agents can work in parallel without interfering
161
ls ../
162
project/ ← main branch
163
project-feature-a/ ← task-creation branch
164
project-feature-b/ ← user-settings branch
165
166
# When done, merge and clean up
167
git worktree remove ../project-feature-a
168
```
169
170
Benefits:
171
- Multiple agents can work on different features simultaneously
172
- No branch switching needed (each directory has its own branch)
173
- If one experiment fails, delete the worktree — nothing is lost
174
- Changes are isolated until explicitly merged
175
176
## The Save Point Pattern
177
178
```
179
Agent starts work
180
│
181
├── Makes a change
182
│ ├── Test passes? → Commit → Continue
183
│ └── Test fails? → Revert to last commit → Investigate
184
│
185
├── Makes another change
186
│ ├── Test passes? → Commit → Continue
187
│ └── Test fails? → Revert to last commit → Investigate
188
│
189
└── Feature complete → All commits form a clean history
190
```
191
192
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.
193
194
## Change Summaries
195
196
After any modification, provide a structured summary. This makes review easier, documents scope discipline, and surfaces unintended changes:
197
198
```
199
CHANGES MADE:
200
- src/routes/tasks.ts: Added validation middleware to POST endpoint
201
- src/lib/validation.ts: Added TaskCreateSchema using Zod
202
203
THINGS I DIDN'T TOUCH (intentionally):
204
- src/routes/auth.ts: Has similar validation gap but out of scope
205
- src/middleware/error.ts: Error format could be improved (separate task)
206
207
POTENTIAL CONCERNS:
208
- The Zod schema is strict — rejects extra fields. Confirm this is desired.
209
- Added zod as a dependency (72KB gzipped) — already in package.json
210
```
211
212
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.
213
214
## Pre-Commit Hygiene
215
216
For machine-consumed status, diff, and history output, use the stable Git formats and safety boundary in `references/shared/agent-first-clis.md`.
217
218
Before every commit:
219
220
```bash
221
# 1. Check what you're about to commit
222
git diff --staged
223
224
# 2. Ensure no secrets (lists matching file names only — any output means review them)
225
git diff --staged -i -G'password|secret|api_key|token' --name-only
226
227
# 3. Run tests
228
npm test
229
230
# 4. Run linting
231
npm run lint
232
233
# 5. Run type checking
234
npx tsc --noEmit
235
```
236
237
Automate this with git hooks:
238
239
```json
240
// package.json (using lint-staged + husky)
241
{
242
"lint-staged": {
243
"*.{ts,tsx}": ["eslint --fix", "prettier --write"],
244
"*.{json,md}": ["prettier --write"]
245
}
246
}
247
```
248
249
## Handling Generated Files
250
251
- **Commit generated files** only if the project expects them (e.g., `package-lock.json`, Prisma migrations)
252
- **Don't commit** build output (`dist/`, `.next/`), environment files (`.env`), or IDE config (`.vscode/settings.json` unless shared)
253
- **Have a `.gitignore`** that covers: `node_modules/`, `dist/`, `.env`, `.env.local`, `*.pem`
254
255
## Using Git for Debugging
256
257
```bash
258
# Find which commit introduced a bug
259
git bisect start
260
git bisect bad HEAD
261
git bisect good <known-good-commit>
262
# Git checkouts midpoints; run your test at each to narrow down
263
264
# View what changed recently
265
git log --oneline -20
266
git diff HEAD~5..HEAD -- src/
267
268
# Find who last changed a specific line
269
git blame src/services/task.ts
270
271
# Search commit messages for a keyword
272
git log --grep="validation" --oneline
273
```
274
275
## Release & Versioning
276
277
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.
278
279
### Semantic Versioning
280
281
For anything with consumers, version `MAJOR.MINOR.PATCH` and let the number carry meaning:
282
283
```
284
MAJOR breaking change — consumers must change their code to upgrade
285
MINOR new functionality, backward-compatible — safe to upgrade
286
PATCH bug fix, backward-compatible — safe to upgrade
287
```
288
289
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.
290
291
### Tag the release, and let the tag be the source of truth
292
293
A release is an immutable point in history, not a moving branch. Tag it so it can always be reproduced:
294
295
```bash
296
git tag -a v1.4.0 -m "Release 1.4.0"
297
git push origin v1.4.0
298
```
299
300
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.
301
302
### Keep a changelog written for humans
303
304
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.
305
306
```markdown
307
## [1.4.0] - 2025-06-12
308
### Added
309
- Bulk task import via CSV
310
### Fixed
311
- Timezone drift in recurring task due dates
312
### Deprecated
313
- `GET /v1/tasks/all` — use the paginated `GET /v1/tasks` (removal in 2.0)
314
```
315
316
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.
317
318
## Common Rationalizations
319
320
| Rationalization | Reality |
321
|---|---|
322
| "I'll commit when the feature is done" | One giant commit is impossible to review, debug, or revert. Commit each slice. |
323
| "The message doesn't matter" | Messages are documentation. Future you (and future agents) will need to understand what changed and why. |
324
| "I'll squash it all later" | Squashing destroys the development narrative. Prefer clean incremental commits from the start. |
325
| "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. |
326
| "I'll split this change later" | Large changes are harder to review, riskier to deploy, and harder to revert. Split before submitting, not after. |
327
| "I don't need a .gitignore" | Until `.env` with production secrets gets committed. Set it up immediately. |
328
| "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. |
329
| "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. |
330
| "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. |
331
332
## Red Flags
333
334
- Large uncommitted changes accumulating
335
- Commit messages like "fix", "update", "misc"
336
- Formatting changes mixed with behavior changes
337
- No `.gitignore` in the project
338
- Committing `node_modules/`, `.env`, or build artifacts
339
- Long-lived branches that diverge significantly from main
340
- Force-pushing to shared branches
341
- A breaking change shipped under a minor or patch version bump
342
- A release with no tag, or a version number hand-edited out of sync with the tag
343
- A user-facing release with no changelog entry, or a changelog that's just dumped commit messages
344
345
## Verification
346
347
For every commit:
348
349
- [ ] Commit does one logical thing
350
- [ ] Message explains the why, follows type conventions
351
- [ ] Tests pass before committing
352
- [ ] No secrets in the diff
353
- [ ] No formatting-only changes mixed with behavior changes
354
- [ ] `.gitignore` covers standard exclusions
355
356
For every release (anything with consumers):
357
358
- [ ] The version bump matches the change: breaking → major, additive → minor, fix → patch
359
- [ ] The release is tagged, and the version is derived from the tag, not hand-edited out of sync
360
- [ ] The changelog has a curated, human-readable entry grouped by impact for this version
361