Skip to content

Version Control as a Safety Net

Summary

Teaches git and GitHub as an undo button for agent work: commits as save points, branches, pull requests, reviewing a diff, rollback and branch hygiene.

Concepts Covered

This chapter covers the following 26 concepts from the learning graph:

Concept Concept Impact Score
Version Control 243
Git 242
Repository 241
Commit 170
Commit Message 1
Save Point 13
Small Steps 12
Agent Scope Creep 10
Diff 10
Reviewing a Diff 9
Git History 19
Branch 49
Main Branch 3
Feature Branch 21
Merge 22
Merge Conflict 1
GitHub 34
Private Repository 1
Push and Pull 1
Pull Request 20
Code Review 8
Revert a Commit 12
Rollback with Git 11
Branch Hygiene 2
Stale Branch 1
Gitignore File 14

Prerequisites

This chapter builds on concepts from:


The Campfire Before the Cave

Watch a twelve-year-old play a video game for an hour and you will see a habit no one had to teach. Before the hard part, the kid walks the character to a campfire, or a glowing book, or a bench, and presses a button. The game saves. Then the character walks into the cave.

The cave goes badly. A monster wins, the screen goes dark, and the character wakes up at the campfire with everything they had when they saved. The kid groans and tries again. Five tries later, they get through.

Now picture a younger sibling who skipped the campfire. The same monster wins, and the character wakes up at the start of the level, an hour back. Nobody has to explain the lesson. The next time, the sibling saves before the cave.

Save Before the Cave

Sawyer waving welcome This is the chapter that lets you stop worrying about what the agent might break. By the end you'll save before every risky request, read a diff for the one file that matters, and undo a bad change without losing the good ones. And each time the agent hands back a change, you'll ask one question of every file it touched: gate or wall?

That campfire teaches two things. The kid didn't save because they expected to fail. They saved because failing was cheap once they had. And the save let them take risks they would never take otherwise. A player with no save point creeps through the cave. A player with one charges in.

Building an app with an AI agent is a long game with a lot of caves. The agent will sometimes break something that worked. It will sometimes change five files when you asked about one. It will sometimes be confidently wrong, as Chapter 4 explained. You can't stop all of that. What you can do is save before every cave, so that a bad afternoon costs you ten minutes instead of a week. The tool for that is called version control, and this chapter teaches the parts of it that a builder who directs an agent needs.

Version Control, Git and the Repository

Version control is a system that records every saved change to a set of files, with who made it and when. It lets you see how the files got to their current state and return to any earlier state. You have used a small version of this if you have ever opened the version history of a shared document and restored Tuesday's copy. Version control for code does the same thing with more care. It keeps every version of every file, it remembers which changes belong together, and it lets several people, or several agents, work on the same files without overwriting each other.

The version control system almost everyone uses for code is Git. Git is a free program that runs on your computer and keeps the full history of a project in a hidden folder inside it. Linus Torvalds wrote it in 2005 to manage the code of the Linux operating system. Your AI coding agent already knows Git well. Claude Code, Cursor and Replit all run Git commands, and most of them will commit your work if you ask.

The project Git keeps track of is called a repository, or repo for short. A repository is a folder of project files plus the complete recorded history of every change to them. When people say "the repo," they mean both at once: the code as it is now, and every earlier version of it. The dating-safety app lives in one repository. Its React screens, Express server, database migrations, adapters for the eight checks and project instruction file are all files in that folder. Git has a record of how each one changed.

The point of a repository, for a builder working with an agent, is reversibility. Chapter 1 described reversibility as how cheaply and completely a decision can be undone, and said much of engineering is the work of turning one-way doors into two-way doors. Version control is the most important tool for that job. Without it, every change the agent makes to your code is a one-way door. With it, almost every code change becomes a two-way door.

Here is what changes when an app has a repository and uses it well.

Situation Without version control With version control
The agent breaks the sign-in page You try to remember what it changed, or ask it to "undo," and hope You return the code to the last version where sign-in worked
You want to know why a line is there Nobody knows The history shows when it was added, by which change, with a note
You want to try a risky idea You try it on the only copy You try it on a separate line of work and throw it away if it fails
Two agents work at once They overwrite each other's files Each works on its own copy, and Git combines them
Your laptop dies The code may be gone A copy of the whole history is on GitHub

In the first row, "ask the agent to undo it" is the habit many builders start with, and it fails more often than it works. The agent's memory of what it changed is only as good as its context window, which Chapter 4 explained can drift or run out. Git's memory doesn't drift, because it recorded every byte.

Version control does have limits, and they matter. It protects code, not data. If the agent runs a migration that drops a column in the live database, Git can bring back the migration file but not the rows that were deleted. Chapter 11 covers backups for that. And Git remembers everything, including the things you wish it didn't. A secret key committed once stays in the history after you delete the file, which is why Chapter 6 says to rotate a leaked key rather than just remove it.

Tell your agent

"Check whether this project is a Git repository. If it is, tell me how many commits it has, when the last one was, and whether there are any changed files that haven't been committed. If it isn't, set one up, but don't commit anything yet. First show me the list of files that would go into the first commit, and make sure no .env file and no node_modules folder is on it (the section on the gitignore file below explains why)."

Commits Are Save Points

A commit is a saved snapshot of the repository at one moment, recorded with a short message, an author and a time, and linked to the commit that came before it. When you or your agent commit, Git looks at every file you've chosen to include and stores exactly how each one looks right now. Each commit gets a long ID, a string of letters and numbers, usually shortened to its first seven characters, such as a3f9c21.

Commits are what make Git an undo button. A save point is a commit made at a moment when the app works, so that you can return to that exact state later if something goes wrong. Every save point is a commit, but not every commit is a good save point. A commit made halfway through a change, when the server won't start, saves your place but gives you nothing you'd want to return to. A save point is a commit you would be glad to land on.

The campfire rule from the opening scene becomes a working habit. Before you ask the agent for anything risky, make sure the current working state is committed. Then if the agent's change goes badly, you return to the save point and lose nothing but the bad change.

One Afternoon of Save Points

Here is how an afternoon of agent work on the dating-safety app looks when the builder commits at each working step. The builder wants to add a "not checked" label for the photo check when the image-search vendor times out, a change that protects the no-false-all-clear rule from Chapter 1.

  1. Before starting, the builder asks the agent to commit the current working app. Save point one.
  2. The agent adds a 10-second timeout to the image-search adapter. The builder runs the app, uploads a test photo, and the check still works. Save point two.
  3. The agent changes the adapter so a timeout returns "not checked" instead of throwing an error. The test with the vendor turned off now shows "not checked." Save point three.
  4. The agent updates the results page to show the label. The builder looks at it on a phone. It overlaps the score. The builder asks for a fix, and the agent rewrites half the page's layout. Now the score circle is gone.
  5. The builder returns the code to save point three and asks the agent again, this time for a smaller change to the label alone. It works. Save point four.

Step four is the cave. Without save point three, the builder would have had to ask the agent to rebuild the old layout from memory. That means the score circle, the check list and every style rule. With save point three, getting back took one command and about ten seconds. The good work from steps two and three was never at risk.

Commit Messages

Each commit carries a note. A commit message is the short text written with a commit that says what changed and why, so that someone reading the history later can understand the change without opening every file. The first line is a summary of about fifty characters or fewer. A blank line and a longer explanation can follow.

Agents write commit messages if you let them, and their first attempts are often too vague. Compare these.

Weak message Useful message
Update files Image-search adapter: return "not checked" on timeout
Fix bug Scoring: count timed-out checks as not checked, never passed
Changes Results page: show "not checked" label under the photo check
WIP Add 10-second timeout to image-search vendor call

A useful message names the part of the app and says what it does now. When you're reading the history three months from now, trying to find the change that broke scoring, the right-hand column tells you where to look. The left-hand column tells you nothing.

Tell your agent

"From now on, before you start any change I ask for, commit the current working state if anything is uncommitted. After each step that works, commit again. Write each commit message as one line that names the part of the app and says what it does now. If a step leaves the app broken, tell me before you commit it."

Small Steps

The afternoon in the worked example went well because each step was small. Small steps is the habit of breaking work into changes small enough that each one can be finished, checked and committed on its own. Any one of them can then be reviewed in a few minutes and undone without touching the others. It is the same idea as Hora's stable subassemblies from Chapter 1, applied to commits. Each small commit is a finished unit. When the phone rings, or the agent goes wrong, you lose at most one step.

Small steps pay off in three places.

  • Reviewing. A commit that changes twenty lines in one file can be read in two minutes. A commit that changes nine hundred lines in thirty files can't be read at all, so in practice nobody reads it.
  • Undoing. If step four breaks the page, you can undo step four alone. If steps two through five went in as one commit, undoing the bad part means undoing the good parts too.
  • Finding the cause. When something breaks and you don't know which change did it, a history of small commits lets you test them one at a time until you find the culprit. A history of large commits leaves you with one big suspect and no way to narrow it down.

Agents don't take small steps on their own. Asked to "add the not-checked label everywhere it's needed," an agent will often work for twenty minutes across a dozen files and present the whole thing at once. That isn't a flaw you can prompt away entirely. It is how the tools are built: they try to finish the whole task in one run. The fix is in how you ask. Give one small task, ask for a commit when it works, then give the next.

Here is the same request phrased two ways.

One large request The same work in small steps
"Make every check show 'not checked' when its vendor fails, and update the score and the results page to match." 1. "Change the image-search adapter so a timeout returns 'not checked.' Commit."
2. "Do the same for the people-search adapter. Commit."
3. "Make the score count 'not checked' as neither pass nor fail. Add a test with every vendor down that expects 50. Commit."
4. "Show the 'not checked' label on the results page. Commit."

The right-hand column takes a few more minutes of the builder's time. It also produces four commits that can each be read, tested and undone on their own. If step three's test fails, steps one and two are already safe.

Tell your agent

"Before you start this feature, break it into steps that each change one part of the app and can be tested on their own. Show me the list. Then do only the first step, run the tests, commit, and stop so I can look before you go on."

Diffs: Seeing What Changed

To review a step, you need to see what it changed. A diff is a listing of the exact differences between two versions of a set of files: which lines were removed, which were added, and which file each change is in. The name is short for "difference." If you've ever reviewed a document with Track Changes turned on, where deleted words show crossed out in red and new ones show underlined, you have read a diff.

Git shows diffs in a standard layout. Each file starts with its name. Lines that begin with a minus sign were removed. Lines that begin with a plus sign were added. Lines with neither are unchanged context, shown so you can tell where in the file the change happened. GitHub and most code editors color removed lines red and added lines green.

Here is a small diff from the dating-safety app, illustrative but built on a real kind of bug from the dating-safety app. A scheduled job sends reminder texts and then marks the reminder as sent. The agent was asked to make the job faster.

--- a/server/jobs/sendReminders.ts
+++ b/server/jobs/sendReminders.ts
@@ -18,7 +18,7 @@ export async function sendReminder(reminder: Reminder) {
   await sms.send(reminder.phone, reminder.text);
   await db
     .update(reminders)
     .set({ sentAt: new Date() })
-    .where(eq(reminders.id, reminder.id));
+    .where(lte(reminders.id, reminder.id));
 }

Before you read the change, here is what the two words mean. In this database library, eq means "equal to" and lte means "less than or equal to." The old line marked one reminder as sent. The new line marks this reminder and every one with a smaller ID as sent, including ones that never went out.

The whole change is one short word. The dating-safety app had a bug of this exact shape in its scheduler. It crashed nothing and showed no error, which is why the diff is the best place to catch it: the old line and the new line sit next to each other. Chapter 10 writes the test that stops this bug coming back, and Chapter 11 shows what it does to the rows in the database.

Tell your agent

"Show me the diff of every change you made in this session, file by file. For each file, write one sentence above it saying what the change does and why it was needed. If any change isn't needed for the task I gave you, list it separately at the end."

Agent Scope Creep

Diffs often show more than you asked for. Agent scope creep is the habit AI coding agents have of changing things beyond the task they were given. They reformat files, rename variables, upgrade packages, rewrite nearby code they decided to improve, or add features nobody asked for. Each extra change may look reasonable on its own. Together they make the change larger, harder to review, and more likely to break something the builder wasn't thinking about.

Chapter 4 named scope creep as one of the ways agents fail. It has a few common causes. Agents are trained to be helpful, and tidying nearby code looks helpful. They see the whole file while they work, and they notice things. And when a task is vague, the agent fills the gap with its own guess about what you meant.

Here is what scope creep looks like in a diff. The builder asked for one thing: "Show 'not checked' under the photo check on the results page when the check didn't run." The agent's diff touched five files.

File changed What the change did Asked for?
ResultsPage.tsx Adds the "not checked" label under the photo check Yes
ResultsPage.tsx Changes the score circle's color from blue to green No, harmless
CheckList.tsx Renames a variable from items to checkItems in forty places No, harmless but noisy
package.json Upgrades the charting package to a new major version, the kind of upgrade that is allowed to break things No, risky
scoring.ts "Simplifies" the score function by treating a missing result as a pass No, breaks a must-be-right rule
README.md Adds a paragraph about the results page No, harmless

Only the first row was the task. Three rows are harmless: a color, a renamed variable and a paragraph in the README. The package upgrade could break the charts in ways nobody will test today. The change to scoring.ts is the dangerous one, and it's the easiest to miss. It sits in a file the builder had no reason to open, inside a diff that's mostly color changes and renamed variables, and it quietly reverses the no-false-all-clear rule.

Small steps and scope creep are two sides of one habit. A small task leaves the agent less room to wander, and a small diff makes any wandering easy to spot. When a diff for a one-line request touches five files, that alone tells you to slow down.

Tell your agent

"Change only what this task needs. Don't reformat, rename, upgrade packages or improve nearby code unless I ask. If you notice something else that should change, write it in a list at the end of your reply instead of changing it."

Reviewing a Diff You Didn't Write

The scope-creep table above only exists because someone read the diff. Reviewing a diff is the practice of reading every change in a diff before accepting it. You check that each change is needed for the task, that nothing touches a must-be-right part by accident, and that the change does what it claims. When an agent writes the code, reviewing the diff is the main way a builder stays in charge of the app.

You don't need to read code fluently to review a diff usefully. Most of what goes wrong in agent work shows up in questions anyone can answer. Here is a review checklist that works for a builder who reads code but doesn't write it line by line.

  1. Which files changed? Read the list of file names before anything else. If the task was about the results page and the list includes the scoring file, the sign-in code or a migration, stop and ask why.
  2. How big is it? Git reports how many lines were added and removed. A one-line request that produced four hundred changed lines needs a reason.
  3. Does any change touch a must-be-right part? Keep your must-be-right list from Chapter 1 next to you. Sign-in, access checks, scoring, the no-locate rule, payments, secrets and migrations all deserve a slow read.
  4. Was anything deleted? Removed lines are easy to skim past. A deleted access check or a deleted test is more dangerous than most added code.
  5. Did any secret or private file appear? An API key in a code file, or a new .env file in the list, is a stop sign. Chapter 6 covers what to do.
  6. Ask the agent to explain anything you don't follow. "What does this line do, and what would happen if it were wrong?" is a fair question about any line.

A good working pattern is to make the agent review its own work in a fresh session. The agent that wrote the code has a context full of its own reasons for writing it. A second session that sees only the diff and your must-be-right list has no such stake, and it often catches what the first one talked itself into.

A Worked Review

Go back to the five-file diff from the scope creep section. Here is how the checklist plays out on it.

The file list comes first, and it already raises a flag: scoring.ts and package.json changed for a task about a label on a page. The size is next: about a hundred lines changed, most of them the renamed variable. Question three sends the reviewer straight to scoring.ts, because scoring is on the must-be-right list. There, a removed line and an added line tell the story:

-  if (result.status === "not_checked") return { counted: false };
+  if (!result.status) return { counted: true, passed: true };

Even without reading TypeScript, the words carry the meaning. The old line said a check that wasn't run is not counted. The new line says a check with no status counts as passed. That is a false all-clear in two lines. The reviewer rejects the change to scoring.ts, asks the agent to back out the package upgrade and the renaming, and keeps the label and the color. The whole review took about ten minutes, and most of that was the one file that mattered.

Diffs Get Easier

Sawyer cheering you on If a diff still looks like a foreign language, that's normal for the first few. You already did the part that counts here: you read the file list and asked what scoring had to do with a label. Start every diff with that question, and the code lines get easier each time.

Try the same review yourself in the simulation below.

Diagram: Read the Diff

Run the Read the Diff MicroSim Fullscreen

Read the Diff

Type: microsim sim-id: read-the-diff
Library: p5.js
Status: Specified
Bloom Level: Analyze
Bloom Verb: differentiate
Learning Objective: The learner will differentiate, in an agent's eight-change diff for a one-line request, the change that was asked for from harmless scope creep and from scope creep that breaks a must-be-right rule, with all eight changes classified correctly.

Prerequisites: diff, agent scope creep, reviewing a diff, must-be-right parts, no false all-clear, no-locate rule (all defined in Chapter 1 and in the sections "Diffs: Seeing What Changed," "Agent Scope Creep" and "Reviewing a Diff You Didn't Write" above).

Evidence of Mastery: The learner marks each of eight diff changes as "Asked for," "Scope creep, harmless" or "Scope creep, risky" and presses Check. A mark is correct when it matches the Correct mark column in Content. Mastery is 8 of 8 correct on the first attempt, or 7 of 8 with both risky changes marked "Scope creep, risky." Expanding a change to read its explanation is exploration, not evidence.

Misconceptions: (1) Small changes are safe. (2) Changes in files you didn't ask about are cosmetic. (3) A large diff is dangerous in proportion to its size, so the biggest change is the riskiest. (4) If the app still runs, the diff is fine.

Instructional Rationale: Differentiating is an Analyze skill: the learner must separate changes that look alike in a diff by testing each one against the task and the must-be-right rules. Putting the risky changes in small hunks beside large harmless ones forces the learner to judge by consequence, not size.

Content:

The task shown at the top: "Show 'not checked' under the photo check on the results page when the check didn't run."

The diff summary shown above the changes: "7 files changed, 64 lines added, 44 lines removed." (Lines changed in the table below count added plus removed lines; they sum to 108.)

# File Change shown to the learner (removed line, then added line) Lines changed Correct mark Why (feedback)
1 ResultsPage.tsx Added: {photo.status === "not_checked" && <Label>Not checked</Label>} 3 Asked for This is the label the task asked for.
2 ResultsPage.tsx Removed: color="blue" Added: color="green" on the score circle 2 Scope creep, harmless A cosmetic change nobody asked for. It's a two-way door.
3 CheckList.tsx Renames items to checkItems throughout the file 80 Scope creep, harmless Noisy and unasked for, but it changes no behavior.
4 package.json Removed: "chart-lib": "^3.9.1" Added: "chart-lib": "^4.0.0" 2 Scope creep, risky A major version upgrade can break the charts, and nothing in this task tests them.
5 scoring.ts Removed: if (result.status === "not_checked") return { counted: false }; Added: if (!result.status) return { counted: true, passed: true }; 2 Scope creep, risky A check with no result now counts as passed. That is a false all-clear.
6 README.md Adds a paragraph describing the results page 6 Scope creep, harmless Documentation nobody asked for. Harmless.
7 peopleSearch.ts Removed: delete record.address; 1 Scope creep, risky Deleting this line lets a match's home address reach the report, which breaks the no-locate rule.
8 ResultsPage.test.tsx Adds a test that the "not checked" label appears when the photo check didn't run 12 Asked for A test for the requested label is part of doing the task well.

Provenance: The task and changes 1 to 6 match the section "Agent Scope Creep." The false all-clear in change 5 and the no-locate rule in change 7 come from the product rules in research/seed-notes.md. File names, line counts and code lines are illustrative and must be labeled "illustrative."

Rules: A change is "Asked for" when it is needed to do the task or to test it. A change is "Scope creep, risky" when it touches a must-be-right part (scoring, location data, sign-in, payments, secrets) or upgrades a dependency by a major version. Every other unasked change is "Scope creep, harmless." Two changes are Asked for (1, 8), three are harmless (2, 3, 6), and three are risky (4, 5, 7).

Learner Activity:

  1. The learner reads the task and the diff summary.
  2. The learner sees the eight changes as diff hunks, each with removed lines marked with a minus sign and added lines marked with a plus sign, in the order 1 to 8.
  3. The learner marks each change with one of the three labels. Marks can be changed until Check.
  4. The learner presses Check. Each change shows whether its mark is correct and its Why text.
  5. The learner should notice that change 3 is the largest and harmless, while changes 5 and 7 are among the smallest and risky.

Feedback: Eight changes, fixed order, one attempt. Correct: "Right. " followed by the Why text. Incorrect: "This one is [correct mark]. " followed by the Why text. If the learner marked change 3 as risky, add: "Size isn't risk. Look at what a change touches." If the learner missed change 5 or 7, add: "The risky changes were small and in files the task didn't mention." The count "n of 8 correct" is shown after Check, with "Mastery reached" when the mastery rule is met.

Starting State: The task, the diff summary and eight unmarked changes. The prompt reads "The agent was asked for one label. Which of these changes should you accept?"

Chapter Anchors: The task is to show "not checked" under the photo check on the results page. The chapter's diff touched five files and changed about a hundred lines (95 in the sim's counts), most of them a renamed variable. The sim's diff adds two more changes (7 and 8) in two more files, so it touches seven files. The dangerous change is in scoring.ts and treats a missing result as passed. The review took about ten minutes.

Tell your agent

"Start a fresh session and act as a reviewer. Here is the task I gave and the diff that came back. Here is my list of must-be-right parts. For each changed file, tell me whether the change was needed for the task, and flag anything that touches a must-be-right part, deletes a check or a test, or upgrades a package. Don't fix anything. Just report."

Git History

Every commit points to the one before it, so the commits form a chain. Git history is that chain: the full ordered record of every commit in a repository, each with its ID, author, time, message and changes, which you can read, search and return to. It answers questions no one remembers the answer to. When did scoring start treating timeouts this way? Which change added the no-locate test? What did the results page look like before the redesign?

A short view of the history is one command away. Asked to "show me the last eight commits, one line each," an agent will run git log --oneline and return something like this illustrative listing, newest at the top.

e41b7d2 Results page: show "not checked" label under photo check
57d2e8a People-search adapter: return "not checked" on timeout
9c03a5f Scoring: count not-checked checks as neither pass nor fail
b2a6f10 Image-search adapter: return "not checked" on timeout
3f88c19 Add 10-second timeout to image-search vendor call
c7d4e02 Stripe webhook: record payment before sending receipt
a09e3b1 Sign-in: expire magic links after 15 minutes
5e12f77 Add test: member cannot open another member's scan

With useful messages, this reads like a diary of the app. Each line points to a diff you can open. With messages like "update" and "fix," the same listing tells you nothing, which is the payoff of the commit message habit from earlier.

History also tells you which change broke something. Say the scoring test passed last week and fails today. You can step back through the commits one at a time, run the test at each, and find the first commit where it fails. Git has a command called git bisect that does this search by halves, so even a hundred commits take about seven tests. Your agent can run it for you. It works far better on a history of small commits, because the commit it lands on is small enough to read.

Tell your agent

"Show me the Git history for the scoring code: every commit that changed it, with its date and message. For the three most recent ones, show me the diff and tell me in one sentence what each changed about how the score is calculated."

Branches

So far every commit has gone in a single line, one after another. That works until you want to try something you might throw away, or have two pieces of work going at once. A branch is a separate, named line of commits that starts from some point in the history and grows on its own, so work on it doesn't affect any other branch until you choose to combine them. Making a branch costs nothing. Git doesn't copy the files. It just starts a new line of commits from where you are.

The Main Branch

Every repository has one branch that everything else is measured against. The main branch is the branch that holds the trusted, working version of the code, usually named main (older projects call it master), and is the version that gets deployed to users. The rule that keeps the main branch trustworthy is simple: work that isn't finished and checked doesn't go on it. If main always works, you always have a known-good place to come back to, and a deploy from main is always a deploy of something you looked at.

Feature Branches

Unfinished work goes somewhere else. A feature branch is a short-lived branch made for one task, such as a feature, a fix or an experiment. It starts from the main branch and is combined back into it when the work is finished and checked, or deleted if the work is abandoned. Names usually describe the task: not-checked-label, fix-reminder-job, try-new-image-vendor.

Feature branches turn a whole piece of work into a two-way door. Say the builder wants to try a second image-search vendor. On a feature branch, the agent can rewrite the adapter, change the scoring weights, and add new settings. If the new vendor turns out worse, the builder deletes the branch, and main never knew it existed. That is the set-based design idea from Chapter 1 made cheap. You can have the agent build two versions of the results page on two branches, look at both, and keep one.

Main Is the Finished Shelf

Sawyer thinking it over Think of main as the shelf you'd show a customer, and every branch as the workbench. You can cut, glue and scrap on the bench all day. Nothing reaches the shelf until you've looked at it.

Feature branches also let agents work in parallel without colliding. One agent session can work on the reminder job on one branch while another adds a test on a second branch. Several agent tools now do this for you by giving each session its own working copy of the repository, called a worktree, on its own branch.

Here is how the three kinds of line fit together for the dating-safety app on a typical week.

Branch Started from Holds Goes where when done
main The first commit The working app that is deployed Stays. Everything else comes back to it
not-checked-label main, Monday The label work from the worked example Combined into main after review, then deleted
try-new-image-vendor main, Tuesday An experiment with a second vendor Deleted if the vendor is worse, combined if better
fix-reminder-job main, Wednesday The one-line fix to the reminder job, plus a test Combined into main the same day

Tell your agent

"Before you start this task, make a new branch from main with a short name that describes the task. Do all the work and all the commits on that branch. Don't commit to main directly. When you're done, tell me the branch name and how many commits are on it."

Merging and Merge Conflicts

A feature branch is only useful if its work can come back. A merge is the step that combines the commits from one branch into another, usually a feature branch into the main branch, so the finished work becomes part of the trusted version. When the feature branch changed files that main didn't touch in the meantime, Git does the merge on its own in a second.

Sometimes main moved while the feature branch was open. Maybe the reminder fix went into main on Wednesday while the label work was still in progress. Git handles that too, as long as the two branches changed different lines. It takes the reminder fix from one side and the label from the other and combines them.

The trouble comes when both branches changed the same lines. A merge conflict is what happens when two branches have each changed the same part of the same file in different ways. Git can't decide which version to keep, so it stops the merge until a person, or an agent, chooses. Git marks the conflict in the file with both versions side by side between lines of <<<<<<<, ======= and >>>>>>>.

Here is a conflict the dating-safety app could produce. Two agent sessions, on two branches, both edited the line in the scoring code that sets the score when no checks ran.

<<<<<<< main
  if (checksRun === 0) return 50;  // neutral when nothing ran
=======
  if (checksRun === 0) return null;  // show "no score" instead
>>>>>>> score-display-experiment

Each side made sense to the session that wrote it. Only one can be kept, and this one touches a must-be-right rule, so the builder should make the call rather than let an agent pick. The lesson in that is general. An agent can resolve most conflicts well, especially in code that is good enough for now. A conflict inside a must-be-right part deserves a person's eyes, because choosing the wrong side quietly changes a product rule.

The cheapest conflicts are the ones that never happen. Short-lived branches and small steps both keep conflicts rare. A branch that lives for an afternoon has little time to drift from main. A branch that lives for a month will conflict on something almost every time.

Tell your agent

"Merge main into this branch now, before we go further. If there are any conflicts, don't resolve them yet. List each one with the file name and both versions, and tell me which ones touch scoring, sign-in, payments or the no-locate rule."

GitHub: Your Repository Off Your Laptop

Git runs on your computer. If your laptop is stolen, every commit goes with it. GitHub is a website, owned by Microsoft, that stores copies of Git repositories online and adds tools for working on them: pull requests, code review, automated checks and access control. It isn't the only service of its kind. GitLab and Bitbucket do similar work. GitHub is the one most agent tools and hosting platforms connect to by default, so this book uses it.

Push and Pull

The copy on GitHub and the copy on your computer don't stay in step by themselves. Push and pull are the two Git commands that move commits between your computer and GitHub. Push sends your new commits up to GitHub. Pull brings down commits that are on GitHub but not yet on your computer. Commits you haven't pushed exist only on your laptop. If you work with an agent in a cloud tool such as Replit, or with a second person, pull before you start so you're building on the latest work.

A good habit is to push at the end of every working session, so GitHub's copy is never more than a day behind. Many hosting platforms, such as Vercel and Railway, watch a GitHub repository and deploy automatically when main changes. Chapter 14 covers that. It means a push to main can be a deploy, which is one more reason main should only get checked work.

Private Repositories

Every GitHub repository is either public, which anyone on the internet can read, or private. A private repository is a repository that only the owner and the people they invite can see. For an app like the dating-safety app, private is the right default. The code shows how the checks work, which a scammer would find useful. It names every vendor the app uses. And if a secret was ever committed, a public repository hands it to anyone who looks. Automated programs scan public GitHub for leaked keys around the clock, and they find them within minutes.

Making a repository public is a one-way door. Flipping it back to private doesn't recall the copies that were already downloaded, forked or indexed. Start private, and make anything public later on purpose, one repository at a time.

Tell your agent

"Check whether this repository is connected to a repository on GitHub. If it is, tell me whether the GitHub repository is public or private, and whether every commit on main has been pushed. If it isn't connected yet, tell me the name you'd give a new private GitHub repository and wait for my OK. Then create it as private and push main. Never create a public one."

Pull Requests and Code Review

Merging a feature branch straight into main works, but it skips a step. A pull request, or PR, is a GitHub page that proposes merging one branch into another so the change can be reviewed first. It shows the full diff, the list of commits, a description of the change and any automated check results, with a place for comments. The name comes from asking the owner of main to "pull" your changes in.

A pull request gathers everything a reviewer needs in one place: what the change is for, every line it changed, and whether the tests passed. It also leaves a permanent record. Six months later you can open the PR for the scoring change and read why it was made and what was discussed.

Code review is the practice of having someone other than the author read a change, usually in a pull request, and approve it or ask for changes before it is merged. In a company, a second engineer does this. A builder working alone with an agent has three reviewers available, and the good-enough approach is to use them according to what the change touches.

What the PR touches Good-enough review
Good-enough-for-now parts only: layout, wording, colors The builder skims the file list and the diff, and merges
Anything on the must-be-right list The builder reads the diff with the checklist, and a fresh agent session reviews it against the must-be-right list
Sign-in, payments, personal data or migrations, before launch or after a big change All of the above, plus a review by an outside engineer when one can be found

That middle row is where most of the value is. An agent session that didn't write the code, given the diff and the rules, is a fast and cheap second reader. It doesn't replace an experienced engineer, and Chapter 18 covers when you need one. It does catch a lot of scope creep and a fair number of plain mistakes.

Here is how the pieces from this chapter fit into one flow, from starting a branch to merging it, and what to do if a merged change turns out wrong. Click each step to see what happens there.

Diagram: From Branch to Main and Back

Run the From Branch to Main and Back MicroSim Fullscreen

From Branch to Main and Back

Type: workflow sim-id: branch-to-main-workflow
Library: Mermaid
Status: Specified
Bloom Level: Understand
Bloom Verb: explain
Learning Objective: The learner will explain which step in the branch, pull request and merge workflow protects against each of five problems, by choosing the right step for each problem with at least four of five correct.

Prerequisites: commit, save point, branch, main branch, feature branch, diff, reviewing a diff, push and pull, pull request, code review, merge, revert a commit (each defined in the sections above, except revert, which is defined in "Revert and Rollback" below; the infobox for that step defines it).

Evidence of Mastery: After exploring the steps, the learner answers five questions. Each question names a problem, and the learner answers by clicking the step that guards against it. An answer is correct when the clicked step matches the Correct step column. Mastery is 4 of 5 correct on the first attempt. Clicking steps to read their infoboxes before the questions is exploration, not evidence.

Misconceptions: (1) Branches are only for teams. (2) A pull request is only useful when someone else reviews it. (3) Once a change is merged it can't be undone. (4) Committing and pushing are the same step.

Instructional Rationale: Explaining the workflow means linking each step to what it protects against. Asking the learner to pick the step for a named problem, after clicking through the steps, checks that link directly rather than the order of the boxes.

Content:

Steps, in order, as nodes in a left-to-right flow, each with a click infobox:

# Step Infobox text
1 Start from main Pull the latest main so you begin from the trusted, working version.
2 Make a feature branch A new branch for this one task. Nothing on it affects main until you merge.
3 Small step and commit The agent makes one small change. It works, so you commit: a save point. Repeat for each step.
4 Push to GitHub Send the branch's commits to GitHub so they're off your laptop.
5 Open a pull request GitHub shows the full diff, the commits and the test results on one page.
6 Review the diff You, and a fresh agent session, read every change against the task and the must-be-right list.
7 Merge into main The reviewed work becomes part of the trusted version. The feature branch can now be deleted.
8 Revert if it goes wrong If the merged change turns out to be wrong, a revert commit undoes it on main and keeps the history.

Edges: 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8. A second edge from 3 back to 3 labeled "next small step." A second edge from 6 back to 3 labeled "changes requested."

Questions, in this order:

# Problem Correct step Why (feedback)
1 The agent rewrote half a page and broke it. You want the version from ten minutes ago. 3. Small step and commit The commit after the last working step is the save point you return to.
2 An experiment with a new vendor might be worse, and you don't want it near the live app. 2. Make a feature branch Work on a branch doesn't touch main until you merge it.
3 Your laptop is stolen. 4. Push to GitHub Pushed commits have a copy on GitHub.
4 The agent quietly changed the scoring code while fixing a label. 6. Review the diff Reading the diff is where scope creep gets caught.
5 A change merged last week turns out to mark timed-out checks as passed. 8. Revert if it goes wrong A revert undoes that one change on main without losing later work.

Provenance: Steps and infobox text summarize the sections of this chapter. Question 4 is from the section "Agent Scope Creep." Question 5 uses the no-false-all-clear rule from research/seed-notes.md. Questions 1 to 3 are illustrative.

Rules: Each question has exactly one correct step. Every node has a click directive that opens its infobox. Edges are not clickable.

Learner Activity:

  1. The learner sees the eight steps as a flow from left to right.
  2. The learner clicks each step to read its infobox, in any order.
  3. The learner presses "Test yourself." Question 1 appears above the flow.
  4. The learner clicks the step that guards against the problem. Feedback appears, and the next question follows.
  5. After question 5, a summary shows which questions were correct.

Feedback: Five questions, fixed order, one attempt each. Correct: "Right. " followed by the Why text. Incorrect: "Not quite. The step that guards against this is [correct step]. " followed by the Why text. The correct step is highlighted after each attempt. A count "n of 5 correct" is shown, with "Mastery reached" at 4 or more.

Starting State: The eight-step flow with no step selected. The prompt reads "Click each step to see what it protects you from."

Chapter Anchors: none

Tell your agent

"When this branch is ready, push it and open a pull request into main. In the description, write what the change does, which must-be-right parts it touches if any, and how you tested it. Don't merge it. I'll review the diff first."

Revert and Rollback

Sooner or later a change that looked fine gets merged and turns out wrong. Git gives two ways back, and the difference between them matters.

Reverting a Commit

To revert a commit is to add a new commit that does the exact opposite of an earlier one. It removes the lines the earlier commit added and puts back the lines it removed, so the change is undone while the history keeps a record of both. The bad commit stays in the history, followed by a commit whose message says "Revert" and names it. Nothing is erased.

Revert is the safe undo, for three reasons. It undoes one change and leaves every later commit in place. It works on main even after the change has been pushed and deployed. And it leaves a trail: anyone reading the history can see that the change was made, that it was undone, and when.

Rolling Back with Git

Sometimes the problem isn't one commit. Several changes went in together, and you aren't sure which one did the damage, or they depend on each other. Rollback with Git means returning the code to the state of an earlier, known-good commit. You can do it by reverting every commit since that point or by moving the branch back to that commit. It's the "go back to the campfire" move: everything after the save point is set aside.

There are two ways to roll back, and they are different kinds of door.

Method What it does Door When to use it
Revert each commit since the save point Adds new commits that undo each one; history keeps everything Two-way. You can revert the reverts Almost always, and always on main once it's pushed
Reset the branch to the save point Moves the branch back and drops the later commits from it One-way if those commits were never pushed or branched. They can become hard or impossible to recover Only on your own unpushed work, when you want to throw it away

Add or Erase

Sawyer thinking it over Notice the pattern in that table. Revert adds a new record, and reset erases old ones. A Git command that adds is a gate, and one that erases is a wall.

The second method is the one to watch for. An agent asked to "go back to how it was an hour ago" may run git reset --hard. That command moves the branch back and also throws away every uncommitted change to the files Git tracks. On a feature branch with nothing worth keeping, that's fine. On main, after a push, it rewrites history that GitHub and your hosting platform already have, and the next push needs a "force push" that overwrites the copy on GitHub. Treat any command with --hard or --force in it as a one-way door from Chapter 1: stop, read the plan, and agree to it before it runs.

Rolling back the code is also not the same as rolling back a deploy. Your hosting platform may let you switch the live site back to an earlier build in one click, without touching Git at all. Chapter 14 covers deploy rollbacks. The two work together: roll back the deploy to stop the harm now, then revert in Git so the next deploy doesn't bring the bad change back.

A Worked Rollback

Here is how this plays out on the dating-safety app, using the history listing from the Git history section. A week after these commits were merged, the builder runs the test that turns off every vendor. It expects a score of 50 and gets 100.

The builder asks the agent to find the first commit where the test fails. The agent runs git bisect across the eight commits and stops at 9c03a5f, "Scoring: count not-checked checks as neither pass nor fail." That commit was meant to protect the rule. Its diff shows that it counted "not checked" correctly but also counted an empty result as passed.

The builder now has to choose. Resetting main to the commit before 9c03a5f would drop the scoring change. It would also drop the two working commits after it: the people-search adapter fix and the results page label. Reverting 9c03a5f alone undoes only the scoring change. The builder reverts it, the vendor-off test passes again, and the agent then writes the scoring change a second time, in a small step with the test running.

The Message Is a Claim

Sawyer pointing out a pitfall Watch out for trusting a commit message over its diff. 9c03a5f said it protected the rule, because the message describes what the agent meant to do, not what it did. For any commit that touches a wall, read the diff, and treat the message as a label for finding it.

You can practice the same decision in the simulation below.

Diagram: Find the Bad Commit

Run the Find the Bad Commit MicroSim Fullscreen

Find the Bad Commit

Type: microsim sim-id: find-the-bad-commit
Library: p5.js
Status: Specified
Bloom Level: Apply
Bloom Verb: use
Learning Objective: The learner will use test runs on a history of eight commits to find the first commit that broke a test, in four or fewer runs, and choose the undo that removes only that commit.

Prerequisites: commit, save point, Git history, revert a commit, rollback with Git, one-way door decision (defined in Chapter 1 and in the sections "Commits Are Save Points," "Git History" and "Revert and Rollback" above).

Evidence of Mastery: The learner runs the vendor-off test on chosen commits, then names the first bad commit and picks one of three undo options. The search is correct when the named commit is commit 6 (9c03a5f). The undo is correct when the learner picks "Revert 9c03a5f." Mastery is the correct commit found in 4 or fewer test runs and the correct undo chosen on the first attempt.

Misconceptions: (1) The newest commit is the one that broke things. (2) Going back to an old commit is always the safe fix. (3) Testing every commit one by one is the only way to find the bad one.

Instructional Rationale: Applying the save-point idea means using the history as a tool: testing commits, narrowing the search, and choosing an undo that keeps good work. A limited budget of test runs rewards splitting the history in halves, which is the idea behind git bisect.

Content:

Commits, oldest first, as a row of eight boxes with their IDs and messages:

# ID Message Vendor-off test result at this commit
1 5e12f77 Add test: member cannot open another member's scan Pass (score 50)
2 a09e3b1 Sign-in: expire magic links after 15 minutes Pass (score 50)
3 c7d4e02 Stripe webhook: record payment before sending receipt Pass (score 50)
4 3f88c19 Add 10-second timeout to image-search vendor call Pass (score 50)
5 b2a6f10 Image-search adapter: return "not checked" on timeout Pass (score 50)
6 9c03a5f Scoring: count not-checked checks as neither pass nor fail Fail (score 100)
7 57d2e8a People-search adapter: return "not checked" on timeout Fail (score 100)
8 e41b7d2 Results page: show "not checked" label under photo check Fail (score 100)

Undo options, shown after the learner names a commit:

Option Correct? Why (feedback)
Revert 9c03a5f Yes It undoes only the scoring change. Commits 7 and 8 work and stay.
Reset main to 5 (b2a6f10) No It also drops commits 7 and 8, which work, and rewrites history that is already pushed.
Revert e41b7d2, the newest commit No The newest commit didn't cause the failure. The test would still fail.

Provenance: Commit IDs and messages match the illustrative listing in the section "Git History." The expected score of 50 when every vendor is off is from research/seed-notes.md. The failure at commit 6 is the illustrative scenario in "A Worked Rollback."

Rules: Running the test on a commit shows its result from the Content table and counts as one run. The learner may run the test on any commit, in any order. The first bad commit is the lowest-numbered commit whose result is Fail. A search with 4 or fewer runs meets the budget. A learner who names the wrong commit is told whether the named commit passes or fails and may name again, but the attempt does not count toward mastery.

Learner Activity:

  1. The learner sees eight commits in a row, oldest on the left, and the note "Today, the vendor-off test fails at commit 8."
  2. The learner clicks a commit and presses "Run test." The commit turns green with "Pass" or red with "Fail," and the run counter goes up by one.
  3. The learner repeats until confident, then presses "This one broke it" on a commit.
  4. The learner chooses one of the three undo options.
  5. The sim shows the history after the chosen undo and runs the test on the new newest commit.

Feedback: One search and one undo choice. Correct commit: "Right. Commit 6 is the first one that fails. You found it in [n] runs." If n > 4, add: "Try testing the middle commit first, then the middle of the half that's left." Wrong commit: "Commit [k] [passes / fails]. Keep looking." Undo feedback is the Why text for the chosen option. The correct undo is revealed after the choice.

Starting State: Eight gray commit boxes and a run counter at 0. The prompt reads "The scoring test fails today. Which commit broke it?"

Chapter Anchors: Eight commits. The bad commit is 9c03a5f, "Scoring: count not-checked checks as neither pass nor fail." The vendor-off test expects 50 and gets 100. Resetting would drop the two working commits after it. A hundred commits take about seven tests by halves.

Tell your agent

"Something broke between yesterday and today. Find the first commit where the tests fail, using git bisect if that's fastest. Show me that commit's diff. Then propose a fix using git revert on that commit only. Don't run git reset, and don't force push, without asking me first."

The Gitignore File

Some files in your project folder should never go into the repository. A gitignore file is a plain text file named .gitignore, kept at the top of a repository. It lists files and folders Git should never track or commit, such as secret settings files, installed packages and build output. Git checks it whenever it looks for new files to add, and skips anything that matches.

Three kinds of file belong in it. The first is secrets. The .env file holds the app's API keys and database password, as Chapter 6 explains, and it must never be committed. The second is anything the computer can rebuild, such as the node_modules folder, which holds every installed package and can run to hundreds of megabytes. The third is personal and generated clutter: logs, test output, editor settings and the build folder.

Here is a starting .gitignore for an app with the dating-safety app's stack. Each line is a pattern, and a line starting with # is a comment.

# Secrets: never commit these
.env
.env.*
!.env.example

# Installed packages: rebuilt by npm install
node_modules/

# Build output: rebuilt by the build step
dist/
build/

# Logs and test output
*.log
coverage/

# Editor and system clutter
.DS_Store
.vscode/

The line !.env.example is worth a note. The exclamation mark means "except this one." An example file with the names of the settings but none of the values is useful to have in the repository, and Chapter 6 covers it.

The dating-safety app had gaps here: a whole .env file was committed, and so was a live token. A .gitignore line for .env would have stopped the first one. It would not stop the second, because a token pasted straight into a code file isn't in an ignored file. That takes a secret scanner, which Chapter 6 and Chapter 17 cover. A .gitignore also only works going forward. If .env was committed before the line was added, it stays in the history until someone removes it and rotates every key in it.

Tell your agent

"Check this repository's .gitignore. Make sure it ignores .env and every .env variant except .env.example, node_modules, build output, logs and editor files. Then check whether any of those files are already tracked by Git or appear anywhere in the history. Report what you find before you remove anything."

Branch Hygiene

Agents are generous with branches. Ask for an experiment and you get a branch. Run three sessions in parallel and you get three more. Several agent tools make a new branch for every session by default. A month later the repository can hold dozens of branches, and nobody remembers which are finished, which were abandoned, and which hold the only copy of something useful.

A stale branch is a branch that hasn't had a new commit in a long time and hasn't been merged, so its work is neither in main nor clearly thrown away. A stale branch is a small risk on its own. A pile of them is a bigger one. Useful work gets lost in the pile. Someone merges an old branch by mistake and brings back a bug that was fixed months ago. An agent asked to "finish the vendor work" picks the wrong branch.

Branch hygiene is the habit of keeping a repository's branches few and clear. You delete branches once they're merged, decide the fate of stale ones on a regular schedule, and name branches so their purpose is obvious. It takes a few minutes a week.

Here is an illustrative branch list from the dating-safety app after a busy month, with the decision for each.

Branch Last commit Merged into main? Decision
not-checked-label 3 weeks ago Yes Delete. The work is in main
fix-reminder-job 3 weeks ago Yes Delete
try-new-image-vendor 5 weeks ago No The vendor was worse. Write one line about why in the project notes, then delete
session-7f2a 6 weeks ago No Name tells you nothing. Ask the agent to summarize its diff against main, then decide
results-page-v2 4 days ago No Active work. Keep
results-page-v3 4 days ago No The other half of a set-based design trial. Keep until one is picked, then delete the loser
old-scoring 4 months ago No Its scoring rule is out of date. Merging it would undo the not-checked rule. Delete

The last row is the dangerous kind. A four-month-old branch carries four-month-old rules, and merging it can quietly undo work done since. Deleting a merged branch loses nothing, because its commits are in main. Deleting an unmerged branch is more of a one-way door, so read its diff first. Git does keep deleted commits for a while, and GitHub can restore a recently deleted branch, but don't count on either.

Tell your agent

"List every branch in this repository, local and on GitHub, with the date of its last commit and whether it's been merged into main. Mark the ones that are fully merged as safe to delete, and for each unmerged branch older than two weeks, show me a one-line summary of its diff against main. Wait for my OK before you delete any branch."

Putting It Together: A Working Session

Every habit in this chapter fits in one session with an agent. Here is the whole loop, written as the steps a builder takes for one feature.

  1. Pull main. Start from the latest trusted version.
  2. Branch. One feature branch for this one task.
  3. Plan small steps. Have the agent list them before it writes code.
  4. One step, review the diff, commit. Check the file list, look for scope creep, and commit when it works.
  5. Push. Get the commits off your laptop.
  6. Open a pull request. Review the whole diff against the must-be-right list, with a fresh agent session for anything risky.
  7. Merge, then delete the branch.
  8. If something breaks later, find the commit and revert it.

None of these steps takes long. Most take less than a minute once the habit is set, and your agent does the typing. Together they make almost every code change a two-way door. Chapter 1 said that's what lets you move fast on the parts that only need to be good enough, and slow down only where it counts.

Tell your agent

"Add a section called 'How we use Git' to this project's instruction file. It should say: always work on a feature branch, never commit to main directly; take small steps and commit after each one that works; write one-line commit messages that name the part of the app; change only what the task needs and list other ideas instead of making them; never commit .env files; never run git reset --hard or force push without asking; open a pull request for every merge into main and don't merge it yourself. Show me the section before you save it."

Back to the Campfire

The kid at the campfire never thought about version control. They knew a save before the cave let them try the cave five times. A builder with an agent has more caves, and an agent that is wrong can be wrong across five files at once. With a commit before each risky request, a bad afternoon costs ten minutes, and you can let the agent charge in.

Your Undo Button Works

Sawyer celebrating You now have the whole loop: branch, small steps, a commit at each working one, a diff read for scope creep, a pull request, and a revert when something slips through. That turns almost every code change in your app into a gate. Good enough for now, and you know why.

Chapter 6 turns to the one thing Git can't undo for you: a secret that has already leaked.

Key Takeaways

  • Commit whenever the app works, and always before a risky request. Each commit is a save point.
  • Give the agent small tasks, and read the file list in every diff before you accept it. Slow down when a one-line request touches five files.
  • Work on a feature branch, push to a private repository on GitHub, and merge through a pull request.
  • To undo a merged change, revert it. Treat reset --hard and force push as one-way doors.
  • Keep .env and node_modules out of the repository with a gitignore file, and delete branches once they're merged.

See Annotated References