Claude Code Gitワークフロー実践ガイド: 個人開発とチーム開発を安全に進める手順
Claude CodeでGitを安全に回す実践手順。ブランチ、commit、rebase、CI、handoffまで解説。
Claude Codeで開発速度が上がるほど、Gitの運用は雑にできません。AIに実装を任せると差分が一気に増えますが、どの変更をcommitに入れるのか、どこでreviewを止めるのか、いつCIを走らせるのかを決めていないと、あとで原因調査に時間を失います。
この記事では、個人開発でもチーム開発でも使える「きれいなブランチループ」を作ります。staging、commit、rebaseの意味を初学者向けに言い換えながら、Claude Codeへ渡すCLAUDE.mdルール、pre-commit、GitHub Actions、conflict対応、safe rollback、daily handoffまで、コピペで試せる形にします。
関連して読むと理解が早い記事は、Claude CodeのGit conflict解決、GitHub Actions高度活用、review workflow checklistです。公式情報はClaude Code hooks、Claude Code headless mode、Git user manual、Git rebase、GitHub Actions workflow syntax、pre-commitを確認してください。
まずGit用語を平たく理解する
Gitのworking treeは、いま手元で編集している作業場です。Claude Codeがファイルを書き換える場所もここです。staging areaは「次のcommitに入れる予約箱」です。git addは保存ではなく、次のcommitに含めるものを選ぶ操作です。
commitは、予約箱に入った変更をひとまとまりの記録として残す操作です。後から読んだ人が「何を、なぜ変えたか」を理解できるように、小さく、名前を付けて残します。rebaseは、自分の作業commitを最新のmainの上に積み直す操作です。履歴が読みやすくなる一方、すでに共有したbranchで乱用すると他の人の履歴を壊します。
Claude Codeに任せる範囲は「差分を作る」だけではありません。差分を読む、stageするファイルを選ぶ、commit messageを提案する、conflictの意図を説明する、CI前の証拠を残す、handoffを書くところまで含めると、実務で使えるGit workflowになります。
flowchart LR
A["目的を1行で書く"] --> B["mainを更新してbranch作成"]
B --> C["Claude Codeで小さく実装"]
C --> D["diffを読みstageを選ぶ"]
D --> E["review gateとlocal CI"]
E --> F["小さなcommit"]
F --> G["rebaseまたはPR"]
G --> H["handoffとrollback情報を残す"]
Clean branch loopの基本
Claude Codeを起動する前に、作業場をきれいにします。ここでの「きれい」は、変更がゼロという意味だけではありません。今回の目的に関係ない変更が混ざっていない状態です。
git status --short
git fetch origin
git switch main
git pull --ff-only origin main
git switch -c feature/checkout-coupon-validation
git status --short
Windows PowerShellなら、日付入りbranch名を作るとdaily workの衝突を避けやすくなります。
$topic = "checkout-coupon-validation"
$date = Get-Date -Format "yyyyMMdd"
git fetch origin
git switch main
git pull --ff-only origin main
git switch -c "feature/$date-$topic"
git status --short
Claude Codeへの最初の依頼は、実装よりも範囲指定を優先します。
Goal: add coupon expiry validation to checkout.
Scope: edit only src/checkout, src/coupons, and matching tests.
Do not stage, commit, push, or edit unrelated files.
Before editing, read package.json and existing checkout tests.
After editing, show git diff --stat and the exact test commands you ran.
この一文があるだけで、Claude Codeがついでに設定ファイルや無関係な文章まで直す事故を減らせます。Masaが記事更新で何度も失敗したのは、「記事本文だけ」と言ったつもりで、実際には画像選定スクリプトや商品ページまで同じdiffに混ざったケースです。最初に対象外を明記すると、reviewの時間がかなり短くなります。
stagingと小さなcommit
初心者が最初に混乱しやすいのは、git add -Aです。これは便利ですが、AI作業では危険です。Claude Codeが生成した一時ファイル、ローカル設定、別作業の修正までまとめてstageすることがあります。
基本は、差分を見てから必要なファイルだけstageします。
git diff --stat
git diff
git add src/checkout/validateCoupon.ts
git add tests/checkout/validateCoupon.test.ts
git diff --staged --stat
git diff --staged
commit messageはConventional Commits風にすると、あとで履歴検索しやすくなります。
git commit -m "feat(checkout): validate coupon expiry before payment"
本文が必要な変更なら、複数行で残します。
git commit -m "fix(content): keep Claude Code Git workflow CTA localized" -m "Updates the localized article body, internal links, and review checklist so the Japanese canonical and translated pages follow the same Git workflow."
Claude Codeには、message作成だけ任せると安全です。
Read only the staged diff.
Propose one Conventional Commits message.
Do not run git commit.
Mention the user impact in the body if the change affects readers or customers.
CLAUDE.mdにGitルールを固定する
毎回同じ注意を入力するなら、CLAUDE.mdに入れます。CLAUDE.mdはClaude Codeが読むプロジェクト用の作業ルールです。人間のREADMEが利用者向けなら、これはAIペアプログラマ向けの運用メモです。
# Claude Code Git rules
- Start every coding task with `git status --short` and report unrelated dirty files.
- Do not run `git add -A`, `git commit`, `git push`, `git reset --hard`, or `git clean -fd` unless the user explicitly asks.
- Keep commits small: one behavior change, one test update, or one content slug at a time.
- Before proposing a commit, show `git diff --stat` and `git diff --staged --stat`.
- If a conflict appears, explain both sides before editing the conflicted file.
- Run the closest local checks before push: lint, typecheck, test, build, or article metadata checks.
- Leave a handoff note with changed files, commands run, failing checks, and rollback option.
チームで使う場合は、禁止コマンドをhooksでも止めます。Claude Codeのhooksは、tool実行の前後などに動くユーザー定義コマンドです。下の例はgitコマンドを見張り、危険なものだけ止める最低限の例です。
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"if": "Bash(git *)",
"command": "node .claude/hooks/block-dangerous-git.mjs"
}
]
}
]
}
}
// .claude/hooks/block-dangerous-git.mjs
import process from "node:process";
let raw = "";
for await (const chunk of process.stdin) raw += chunk;
const input = JSON.parse(raw || "{}");
const command = input.tool_input?.command ?? "";
const blocked = [
/git\s+reset\s+--hard\b/,
/git\s+clean\s+-[^\s]*f/,
/git\s+push\s+--force(?!-with-lease)/,
/git\s+checkout\s+--\s+\./,
/git\s+restore\s+\.\b/
];
if (blocked.some((pattern) => pattern.test(command))) {
process.stderr.write(`Blocked risky Git command: ${command}\n`);
process.exit(2);
}
hookは万能ではありません。人間がterminalで直接実行するコマンドは別ですし、プロジェクト外の設定にも影響されます。それでも、AIがうっかり危険なGit操作を提案したときに止められる保険になります。
CI before pushをローカルで作る
push前にCIを待つだけでは遅いです。Claude Codeには、local gateを先に通してもらいます。Node.jsプロジェクトなら、存在するscriptだけ実行するpreflightを置くと使い回せます。
// scripts/claude-git-preflight.mjs
import { execSync } from "node:child_process";
import { existsSync, readFileSync } from "node:fs";
const run = (command) => {
console.log(`\n$ ${command}`);
execSync(command, { stdio: "inherit", shell: true });
};
run("git diff --check");
run("git diff --cached --check");
run("git status --short");
const pkg = existsSync("package.json")
? JSON.parse(readFileSync("package.json", "utf8"))
: { scripts: {} };
for (const script of ["lint", "typecheck", "test", "build"]) {
if (pkg.scripts?.[script]) run(`npm run ${script}`);
}
実行コマンドです。
node scripts/claude-git-preflight.mjs
PythonやGoのプロジェクトなら、同じ考え方でruff check、pytest、go test ./...を並べます。大事なのは、Claude Codeの返答に「何を確認したか」を必ず残すことです。
After implementation, run the local preflight.
If a command fails, stop and explain the first failing command, likely cause, and smallest next fix.
Do not push until the preflight is green.
pre-commitとGitHub Actionsの最小例
pre-commitはcommit直前にformatやlintを走らせる仕組みです。人間にもClaude Codeにも同じゲートを当てられるので、チーム開発で効果があります。
# .pre-commit-config.yaml
repos:
- repo: local
hooks:
- id: git-diff-check
name: git diff whitespace check
entry: git diff --check
language: system
pass_filenames: false
- id: npm-test
name: npm test when available
entry: node scripts/claude-git-preflight.mjs
language: system
pass_filenames: false
python -m pip install pre-commit
pre-commit install
pre-commit run --all-files
PR側はGitHub Actionsで同じ観点を再実行します。
# .github/workflows/claude-code-pr-gate.yml
name: Claude Code PR Gate
on:
pull_request:
branches: [main]
jobs:
verify:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- run: git diff --check origin/main...HEAD
- run: npm run lint --if-present
- run: npm run typecheck --if-present
- run: npm test --if-present
- run: npm run build --if-present
これで「手元では動いた」が減ります。Claude CodeにCIログを渡すときも、全文を投げるより最初の失敗箇所と関連ファイルを渡すほうが速いです。
conflictとrebaseの扱い
conflictは、同じ場所を別の変更が触ったためGitが自動で選べない状態です。Claude Codeには「両方を残して」と雑に頼むのではなく、どちらの意図を守るかを説明させます。
git fetch origin
git rebase origin/main
git status --short
git diff --name-only --diff-filter=U
Claude Codeへの依頼です。
We are in a rebase conflict.
For each conflicted file, explain what our branch changed and what origin/main changed.
Resolve only after explaining the business intent.
After editing, run the narrowest relevant test.
Do not continue the rebase until I approve the resolved diff.
解決後の流れです。
git add src/checkout/validateCoupon.ts
npm test -- --runInBand validateCoupon
git rebase --continue
違和感があれば戻します。
git rebase --abort
公開済みbranchでrebaseした場合は、通常の--forceではなく--force-with-leaseを使います。ただし、チームでは「誰がいつ使ってよいか」をルール化してください。初学者が一番避けるべき失敗は、他人の作業が入ったremote branchへ何となくforce pushすることです。
安全なrollback
rollbackは「なかったことにする」ではなく、「戻した証拠を残す」ほうが安全です。共有済みcommitならgit revertを使います。
git log --oneline -5
git revert --no-edit HEAD
git status --short
未commitの変更だけ戻したい場合は、対象を絞ります。
git restore --staged src/checkout/validateCoupon.ts
git restore src/checkout/validateCoupon.ts
どうしても大きく戻す前は、backup branchを切ります。
$sha = git rev-parse --short HEAD
git switch -c "backup/before-rollback-$sha"
git switch -
git revert --no-edit HEAD
Claude Codeには、rollback前に選択肢を出させます。
Suggest a rollback plan.
Prefer git revert for shared commits.
Do not use reset --hard or clean -fd.
List exactly which files or commits would be affected.
3つ以上の実務ユースケース
1つ目は、個人開発の小さな機能追加です。feature/yyyyMMdd-topicを作り、Claude Codeに対象ファイルとtestを指定します。1commitは1機能に限定し、push前にlocal preflightを通します。作業が小さいので、失敗してもgit revertかbranch削除で戻せます。
2つ目は、チームのPR作成です。Claude Codeには実装者、reviewer、人間の承認者を分けて動かします。実装sessionはcommitしない。review sessionはstaged diffだけを見る。人間がPR title、CI、risk、rollbackを確認してpushする。この分担にすると、AIが書いた勢いのままmainへ近づく危険を抑えられます。
3つ目は、contentやproduct pageの更新です。ClaudeCodeLabでは記事、Gumroad導線、研修CTA、内部リンクが収益に直結します。本文だけを直すつもりでも、画像、slug、locale、商品リンクが混ざると壊れます。slug単位でbranchを切り、対象localeだけ編集し、description長、hero、CTA、mojibakeをチェックします。
4つ目は、長期refactorです。大きな設計変更は1commitで終わらせません。まず型やtestを追加するcommit、次に内部実装を変えるcommit、最後に削除commitへ分けます。Claude Codeには「今のcommitでは削除しない」「public APIを変えるなら先にtestを追加」と指示します。
失敗例と落とし穴
| 失敗 | なぜ起きるか | 防ぎ方 |
|---|---|---|
git add -Aで無関係な変更が混ざる | AIが触った一時ファイルや別作業をまとめてstageする | git diff --stat後にpath指定でaddする |
| 巨大commitになる | 実装、test、copy、設定を一度に頼む | 1commit 1目的に分ける |
| conflictを雰囲気で解く | 両branchの意図を読まない | 解決前に「ours/theirsの目的」を説明させる |
| rebase済みbranchを通常pushする | remote履歴とローカル履歴がずれる | チーム承認後に--force-with-leaseだけ使う |
| CI前にpushしてPRが赤くなる | 手元の確認がない | scripts/claude-git-preflight.mjsを走らせる |
rollbackでreset --hardを使う | 証拠が消え、復旧も説明も難しくなる | 共有済み変更はgit revertを優先する |
| hooksを過信する | hook対象外の操作や人間のterminal操作が残る | CLAUDE.md、review、CIを重ねる |
Masaが実際に痛かったのは、記事生成タスクで「10言語を直して」と頼んだあと、途中の検証メモまで同じcommit候補に入ったケースです。Git上は小さなミスですが、公開後に見ると「なぜこのファイルが変わったのか」を説明できませんでした。Claude Code作業では、差分の説明責任までcommitの一部だと考えるべきです。
daily handoffを残す
1日の最後にhandoffを残すと、翌日の自分やreviewerが迷いません。長い日報ではなく、再開に必要な証拠だけで十分です。
## Handoff: 2026-06-02
Branch: feature/20260602-checkout-coupon-validation
Goal: validate coupon expiry before payment authorization
Changed:
- src/checkout/validateCoupon.ts
- tests/checkout/validateCoupon.test.ts
Checks:
- npm run lint: passed
- npm test -- --runInBand validateCoupon: passed
- npm run build: not run, no UI/build config touched
Risk:
- Coupon timezone boundary still needs one integration test.
Rollback:
- Revert commit `abc1234` if production checkout rejects valid coupons.
Claude Codeへの締めの依頼も固定できます。
Write a daily handoff.
Include branch, goal, changed files, checks run, checks not run, risk, and rollback.
Do not claim a command passed unless it was actually run in this session.
Claude Codeを収益導線に自然につなげる
Git workflowの記事は、単なるコマンド集で終わると弱いです。読者が本当に欲しいのは「自分やチームのリポジトリで事故らず回す型」です。個人なら無料チートシートで日々の確認コマンドを手元に置くのが最初の一歩です。テンプレート、CLAUDE.md、review promptをまとめて使いたいなら教材・テンプレート一覧へ進んでください。
チームで導入する場合は、branch naming、commit粒度、CI、権限、review gate、rollback、handoffまで、実リポジトリに合わせて決める必要があります。そこまで含めて整えたい場合は、Claude Code研修・導入相談で現在の開発フローを題材に設計できます。
この記事で紹介した内容を実際に試した結果
ClaudeCodeLabの記事更新でこのGit loopを使うと、レビュー時間は「全文を読み直す」から「対象slug、locale、metadata、CTA、diff scopeを見る」へ絞れました。特にgit diff --staged --statとhandoffの組み合わせは効果が大きく、翌日の作業再開で「どこまで本当に確認したか」を思い出す時間が減ります。Claude Codeの価値は速く書くことだけではなく、確認の証拠を短く残して、次の人が安全に進める状態を作ることにあります。
無料PDF: Claude Code はじめてのチートシート
まずは無料PDFで基本コマンドと最初の使い方をまとめて確認してください。登録後はそのままテンプレート集や導入相談にも進めます。
スパムは送りません。登録情報は厳重に管理します。
Claude Codeを仕事で使える形にしませんか?
無料PDFで基礎を固めたあと、すぐ使えるテンプレート集で試し、必要なら業務自動化や導入相談まで進められます。
この記事を書いた人
Masa
Claude Codeの実務活用、導入設計、収益導線改善を検証しているエンジニア。10言語の技術メディアを運営中。
関連書籍・参考図書
この記事のテーマに関連する書籍を楽天ブックスで探せます。
※ 当サイトは楽天市場のアフィリエイトプログラムに参加しています。上記リンクから商品をご購入いただくと、運営者に紹介料が支払われる場合があります。
関連記事
Claude Code権限セーフティラダー: 初心者がallowを広げる順番
Claude Codeの権限をread-onlyからbuild、限定編集、deploy確認まで段階的に広げる安全な運用手順。
Claude Code Small PR Proof Pack: 小さなPRをレビュー可能にする証拠セット
Claude Codeの小さなPRに、差分・検証・公開URL・CTA・rollbackを添える実務チェックリスト。
Claude Codeのコミット前レビューゲート: 差分、テスト、CTAをまとめて止める型
Claude Codeでcommit前に差分をレビューする実践手順。build、公開URL、CTA、Gumroadリンク、未翻訳本文を検知します。