Skill: Branch Context Check (Branch / Worktree Intent Guard)
Type: Execution
Purpose
Prevent accidental commits on the wrong branch or into a dirty working tree
owned by another session.
This skill verifies:
- Current branch intent matches the current task
- Recent commits on the branch are related to the current work
- Dirty files are attributable to the current session or intentionally carried
forward
- The safest next step is clear before staging, committing, pushing, or
continuing work
- Post-publish branch/worktree cleanup is explicitly chosen after push, PR
creation, or PR merge
When to Use
- Before committing or pushing changes
- Before running a finalize-and-commit workflow
- When continuing work after time has passed or after switching sessions
- When the current branch name looks tied to another task, issue, PR, or agent
session
- When the working tree is dirty and file ownership is unclear
- When deciding whether to create a new branch or separate worktree
- After pushing a branch, opening a PR, or merging a PR when deciding whether
to switch back to base, delete local/remote branches, or remove worktrees
When NOT to Use
- Non-Git directories
- Read-only repository inspection with no intent to edit, stage, commit, or push
- Trivial commands that do not depend on branch state
- Repositories where the user explicitly confirms the current branch is correct
for this exact task
Inputs Required
Do not run this skill without:
Optional but recommended:
Output Format
- Branch Context Snapshot
- Intent Match Verdict (
match, ambiguous, mismatch, or blocked)
- Dirty Worktree Ownership
- Recommended Action
- User Confirmation Required
- Post-Publish Cleanup Decision, if applicable
Procedure
Gate 0 – Task Intent Capture
Summarize the current task in one sentence before inspecting Git.
Extract these intent signals when available:
- Feature, bug, documentation, or refactor scope
- Ticket/issue/PR ID
- Expected files, packages, or modules
- User-stated branch or worktree preference
- Whether the work is new, a continuation, or finalization of existing work
If intent cannot be summarized, ask the user for a short task description
before recommending any Git action.
Gate 1 – Git Context Snapshot
Collect evidence with non-destructive commands:
git status --short --branch
git branch --show-current
git diff --name-only
git diff --cached --name-only
git log --oneline --decorate -5
When useful and available, also check:
git rev-parse --abbrev-ref --symbolic-full-name @{u} for upstream branch
git status --porcelain=v1 for machine-readable dirty files
git merge-base --fork-point <base> HEAD or git merge-base <base> HEAD
when evaluating whether branch commits are tied to the expected base
Do not run commands that alter the index, working tree, branch, or stash.
Gate 2 – Branch Intent Inference
Infer the current branch's likely purpose from:
- Branch name tokens (
feature/foo, ticket IDs, user names, session IDs)
- Recent commit messages and touched areas
- Upstream branch name and ahead/behind status
- Whether the branch is a protected/shared branch such as
main, master,
develop, release/*, or hotfix/*
- Whether the branch is clean or already contains task-specific commits
Compare that inferred purpose against the current task intent from Gate 0.
Classify the result:
- match: Branch name, recent commits, and file scope clearly align with the
current task.
- ambiguous: Evidence is weak or generic; current branch may be correct but
needs user confirmation.
- mismatch: Branch appears tied to a different task, issue, PR, or previous
session.
- blocked: Dirty state or branch history makes safe continuation impossible
without a user decision.
Gate 3 – Dirty Worktree Ownership
Separate files into:
- Current-session changes: Files edited in the current conversation or
explicitly requested by the user.
- Carried-forward changes: Dirty files that existed before the current task
or are not attributable to this session.
- Staged changes: Files already staged before this skill runs.
- Unknown ownership: Files whose origin cannot be determined.
Then check overlap:
- Same file touched by current-session and carried-forward changes
- Same module or feature area touched by unrelated tasks
- Staged changes that do not belong to the current task
If overlap exists, classify the verdict as blocked unless the user explicitly
confirms the combined scope.
Gate 4 – Decision Matrix
Use this matrix to recommend the next action:
| Condition |
Verdict |
Recommended Action |
| Branch matches current task and dirty files are in-scope |
match |
Continue finalize, stage only confirmed files |
| Branch is generic or evidence is weak, but no conflicting dirty files exist |
ambiguous |
Ask user to confirm branch before commit |
| Clean branch clearly belongs to another task |
mismatch |
Create/switch to a task-appropriate branch or worktree before editing/committing |
| Dirty branch contains previous-session work unrelated to current task |
blocked |
Do not commit; ask whether to finish previous work, split via worktree, or isolate current-session patch |
| Current branch is protected/shared and task is non-trivial |
blocked |
Create a feature/fix branch before committing |
| Staged files include unknown or unrelated changes |
blocked |
Unstage only with explicit user approval; otherwise stop before commit |
| Branch is ahead of upstream with unrelated commits |
mismatch |
Do not add new task commits; create a separate branch from the correct base or ask user to confirm stacking |
When recommending a new branch, propose a concrete name derived from the task,
for example fix/login-timeout or docs/branch-guard.
When recommending a worktree, include the base branch assumption and state that
only user-confirmed changes should be moved or recreated there.
Gate 5 – Handoff
Before any staging or commit:
- Present the verdict and evidence.
- State exactly which files are safe to commit now.
- State which files must be left untouched.
- Ask for user confirmation when verdict is
ambiguous, mismatch, or
blocked.
If used inside finalize-and-commit or docs-finalize-and-commit, this gate
must complete before their Working Set Validation gate proceeds.
Gate 6 – Post-Publish Cleanup Decision
Run this gate after any commit/push/PR operation before ending the workflow.
The agent must either perform an approved cleanup or explicitly state why no
cleanup was performed.
Step 6-1: Capture publish state
Inspect:
git status --short --branch
git branch --show-current
git worktree list
git branch --format='%(refname:short) %(upstream:short)'
- Remote branch existence for the current task branch
- PR state (
OPEN, MERGED, CLOSED) and merge commit when a PR exists
Use gh pr view or equivalent repository tooling when available. If GitHub
metadata is unavailable, do not infer that a branch is merged from Git alone
when squash merge may have been used.
Step 6-2: Present cleanup choices
Offer the applicable choices instead of silently ending:
- Keep branch/worktree: keep the current branch for follow-up commits or an
open PR.
- Return to base: switch to the base branch and fast-forward pull.
- Delete local branch: delete the task branch after it is no longer needed.
- Delete remote branch: delete the remote task branch after the PR is
merged or closed intentionally.
- Remove worktree: remove a separate task worktree after confirming it is
clean and no longer needed.
- Prune metadata: run remote/worktree prune after branch or worktree
cleanup.
If the user explicitly requested cleanup, execute every eligible cleanup step
after the safety checks below pass. If the user did not request cleanup, stop
and ask which option to apply.
Step 6-3: Safety checks before deletion
Deletion is eligible only when all relevant checks pass:
- Working tree is clean in the branch/worktree being cleaned.
- The PR for the task branch is
MERGED, or the user explicitly confirms that
the branch is obsolete.
- No open PR depends on the branch.
- No stacked branch or follow-up branch uses the branch as its base, unless the
user confirms that dependency is gone.
- The branch is not the current checkout when deleting it locally.
- A worktree is not removed unless
git status inside that worktree is clean.
- Remote deletion targets only the task branch, never a base/protected branch.
Prefer git branch -d. If squash merge makes git branch -d reject a branch
whose PR is confirmed MERGED, use git branch -D only after stating that
reason and only for the task branch.
Step 6-4: Verification after cleanup
After cleanup, verify and report:
- Current branch
git status --short --branch
- Remaining local branches relevant to the task
- Remaining remote branches relevant to the task
git worktree list
Guardrails
- Do not treat the current branch as valid just because it is already checked
out.
- Do not assume a new session can be reliably detected; infer risk from branch,
commits, dirty files, and task intent.
- Do not run destructive Git commands (
reset, checkout --, restore,
clean, stash, rebase, branch deletion) without explicit user approval.
- Do not use
git add ., git add -A, or git add --all.
- Do not commit staged changes until staged ownership is confirmed.
- Do not move dirty changes across branches or worktrees automatically.
- Do not mix unrelated tasks in one commit just because they are already dirty.
- Explicitly state assumptions about base branch and branch naming.
- Do not end a commit/push/PR workflow without a cleanup decision or a clear
statement that cleanup is not applicable yet.
- Do not delete local branches, remote branches, or worktrees unless the safety
checks in Gate 6 pass.
- Do not delete a branch just because it was pushed; open PR branches normally
stay until merge or an explicit user decision.
- Do not remove the current worktree. Switch away first or remove only a
separate clean worktree path.
Failure Patterns
Common bad outputs:
- Saying "working tree clean" but ignoring that the branch itself belongs to a
previous task
- Continuing on a feature branch whose recent commits are unrelated to the
current request
- Treating dirty files as current-session changes without evidence
- Recommending
git stash as a default solution, hiding ownership instead of
clarifying it
- Creating a new branch from the wrong feature branch when the correct base
should be
main or develop
- Staging all files after warning that some files are out of scope
- Asking for generic confirmation without listing the exact branch, commits, and
files that caused the risk
- Ending after push or merge while leaving stale branches/worktrees without
mentioning cleanup choices
- Deleting a branch for an open PR or an unverified squash merge
- Removing a worktree without checking that worktree's own status
Example 1 (Clean Wrong Branch)
Input:
Current task: add billing export tests. git status --short --branch shows a
clean working tree on feature/oauth-login. Recent commits mention OAuth
callback handling.
Output:
- Branch Context Snapshot: branch
feature/oauth-login, clean tree, recent
commits are OAuth-related.
- Intent Match Verdict:
mismatch — current task is billing export tests, but
branch intent is OAuth login.
- Dirty Worktree Ownership: no dirty files.
- Recommended Action: create a new branch from the correct base, for example
test/billing-export, before making or committing billing changes.
- User Confirmation Required: yes — confirm base branch (
main assumed) and
new branch/worktree preference.
Example 2 (Dirty Previous Session)
Input:
Current task: update dashboard copy. Current branch is agent/aaa-refactor.
Working tree has modified src/auth/session.ts and src/dashboard/Home.tsx.
Conversation history only touched src/dashboard/Home.tsx. Recent commits on
the branch mention auth session refactoring.
Output:
- Branch Context Snapshot: branch
agent/aaa-refactor, dirty files in auth and
dashboard, recent commits are auth-related.
- Intent Match Verdict:
blocked — branch and one dirty file appear to belong
to a previous auth refactor session.
- Dirty Worktree Ownership:
src/dashboard/Home.tsx is current-session;
src/auth/session.ts is carried-forward/unknown.
- Recommended Action: do not commit from this state. Ask whether to finish the
auth refactor first, create a separate worktree for dashboard copy, or commit
only the confirmed dashboard file after explicit approval.
- User Confirmation Required: yes — exact commit scope must be confirmed before
staging.
Notes
This skill is intentionally conservative. Its goal is not to automate branch
management; it is to prevent accidental task mixing at the commit boundary.
1---2name: branch-context-check3description: Verify that the current Git branch, upstream state, and dirty working tree match the user's intended task before staging, committing, pushing, or continuing work from another session. Use this to detect stale branch reuse, leftover dirty files from previous sessions, unrelated commits on the current branch, cases where work should be split into a new branch or worktree, and post-publish cleanup decisions after push, PR creation, or PR merge.4license: MIT5---67# Skill: Branch Context Check (Branch / Worktree Intent Guard)89**Type:** Execution1011## Purpose1213Prevent accidental commits on the wrong branch or into a dirty working tree14owned by another session.1516This skill verifies:1718- Current branch intent matches the current task19- Recent commits on the branch are related to the current work20- Dirty files are attributable to the current session or intentionally carried21 forward22- The safest next step is clear before staging, committing, pushing, or23 continuing work24- Post-publish branch/worktree cleanup is explicitly chosen after push, PR25 creation, or PR merge2627---2829## When to Use3031- Before committing or pushing changes32- Before running a finalize-and-commit workflow33- When continuing work after time has passed or after switching sessions34- When the current branch name looks tied to another task, issue, PR, or agent35 session36- When the working tree is dirty and file ownership is unclear37- When deciding whether to create a new branch or separate worktree38- After pushing a branch, opening a PR, or merging a PR when deciding whether39 to switch back to base, delete local/remote branches, or remove worktrees4041---4243## When NOT to Use4445- Non-Git directories46- Read-only repository inspection with no intent to edit, stage, commit, or push47- Trivial commands that do not depend on branch state48- Repositories where the user explicitly confirms the current branch is correct49 for this exact task5051---5253## Inputs Required5455Do not run this skill without:5657- [ ] A Git repository58- [ ] Current task intent, summarized from the user's request or conversation59- [ ] Access to Git status, branch, diff, and recent commit history6061Optional but recommended:6263- [ ] Target base branch (e.g., `main`, `develop`, release branch)64- [ ] Intended branch name, ticket ID, PR title, or issue reference65- [ ] List of files modified by the current session66- [ ] Known previous-session work that should remain untouched67- [ ] PR URL/number and merge state when deciding post-publish cleanup6869---7071## Output Format72731. Branch Context Snapshot742. Intent Match Verdict (`match`, `ambiguous`, `mismatch`, or `blocked`)753. Dirty Worktree Ownership764. Recommended Action775. User Confirmation Required786. Post-Publish Cleanup Decision, if applicable7980---8182## Procedure8384### Gate 0 – Task Intent Capture8586Summarize the current task in one sentence before inspecting Git.8788Extract these intent signals when available:8990- Feature, bug, documentation, or refactor scope91- Ticket/issue/PR ID92- Expected files, packages, or modules93- User-stated branch or worktree preference94- Whether the work is new, a continuation, or finalization of existing work9596If intent cannot be summarized, ask the user for a short task description97before recommending any Git action.9899---100101### Gate 1 – Git Context Snapshot102103Collect evidence with non-destructive commands:104105- `git status --short --branch`106- `git branch --show-current`107- `git diff --name-only`108- `git diff --cached --name-only`109- `git log --oneline --decorate -5`110111When useful and available, also check:112113- `git rev-parse --abbrev-ref --symbolic-full-name @{u}` for upstream branch114- `git status --porcelain=v1` for machine-readable dirty files115- `git merge-base --fork-point <base> HEAD` or `git merge-base <base> HEAD`116 when evaluating whether branch commits are tied to the expected base117118Do not run commands that alter the index, working tree, branch, or stash.119120---121122### Gate 2 – Branch Intent Inference123124Infer the current branch's likely purpose from:125126- Branch name tokens (`feature/foo`, ticket IDs, user names, session IDs)127- Recent commit messages and touched areas128- Upstream branch name and ahead/behind status129- Whether the branch is a protected/shared branch such as `main`, `master`,130 `develop`, `release/*`, or `hotfix/*`131- Whether the branch is clean or already contains task-specific commits132133Compare that inferred purpose against the current task intent from Gate 0.134135Classify the result:136137- **match:** Branch name, recent commits, and file scope clearly align with the138 current task.139- **ambiguous:** Evidence is weak or generic; current branch may be correct but140 needs user confirmation.141- **mismatch:** Branch appears tied to a different task, issue, PR, or previous142 session.143- **blocked:** Dirty state or branch history makes safe continuation impossible144 without a user decision.145146---147148### Gate 3 – Dirty Worktree Ownership149150Separate files into:151152- **Current-session changes:** Files edited in the current conversation or153 explicitly requested by the user.154- **Carried-forward changes:** Dirty files that existed before the current task155 or are not attributable to this session.156- **Staged changes:** Files already staged before this skill runs.157- **Unknown ownership:** Files whose origin cannot be determined.158159Then check overlap:160161- Same file touched by current-session and carried-forward changes162- Same module or feature area touched by unrelated tasks163- Staged changes that do not belong to the current task164165If overlap exists, classify the verdict as `blocked` unless the user explicitly166confirms the combined scope.167168---169170### Gate 4 – Decision Matrix171172Use this matrix to recommend the next action:173174| Condition | Verdict | Recommended Action |175|---|---|---|176| Branch matches current task and dirty files are in-scope | match | Continue finalize, stage only confirmed files |177| Branch is generic or evidence is weak, but no conflicting dirty files exist | ambiguous | Ask user to confirm branch before commit |178| Clean branch clearly belongs to another task | mismatch | Create/switch to a task-appropriate branch or worktree before editing/committing |179| Dirty branch contains previous-session work unrelated to current task | blocked | Do not commit; ask whether to finish previous work, split via worktree, or isolate current-session patch |180| Current branch is protected/shared and task is non-trivial | blocked | Create a feature/fix branch before committing |181| Staged files include unknown or unrelated changes | blocked | Unstage only with explicit user approval; otherwise stop before commit |182| Branch is ahead of upstream with unrelated commits | mismatch | Do not add new task commits; create a separate branch from the correct base or ask user to confirm stacking |183184When recommending a new branch, propose a concrete name derived from the task,185for example `fix/login-timeout` or `docs/branch-guard`.186187When recommending a worktree, include the base branch assumption and state that188only user-confirmed changes should be moved or recreated there.189190---191192### Gate 5 – Handoff193194Before any staging or commit:195196- Present the verdict and evidence.197- State exactly which files are safe to commit now.198- State which files must be left untouched.199- Ask for user confirmation when verdict is `ambiguous`, `mismatch`, or200 `blocked`.201202If used inside `finalize-and-commit` or `docs-finalize-and-commit`, this gate203must complete before their Working Set Validation gate proceeds.204205---206207### Gate 6 – Post-Publish Cleanup Decision208209Run this gate after any commit/push/PR operation before ending the workflow.210The agent must either perform an approved cleanup or explicitly state why no211cleanup was performed.212213**Step 6-1: Capture publish state**214215Inspect:216217- `git status --short --branch`218- `git branch --show-current`219- `git worktree list`220- `git branch --format='%(refname:short) %(upstream:short)'`221- Remote branch existence for the current task branch222- PR state (`OPEN`, `MERGED`, `CLOSED`) and merge commit when a PR exists223224Use `gh pr view` or equivalent repository tooling when available. If GitHub225metadata is unavailable, do not infer that a branch is merged from Git alone226when squash merge may have been used.227228**Step 6-2: Present cleanup choices**229230Offer the applicable choices instead of silently ending:231232- **Keep branch/worktree:** keep the current branch for follow-up commits or an233 open PR.234- **Return to base:** switch to the base branch and fast-forward pull.235- **Delete local branch:** delete the task branch after it is no longer needed.236- **Delete remote branch:** delete the remote task branch after the PR is237 merged or closed intentionally.238- **Remove worktree:** remove a separate task worktree after confirming it is239 clean and no longer needed.240- **Prune metadata:** run remote/worktree prune after branch or worktree241 cleanup.242243If the user explicitly requested cleanup, execute every eligible cleanup step244after the safety checks below pass. If the user did not request cleanup, stop245and ask which option to apply.246247**Step 6-3: Safety checks before deletion**248249Deletion is eligible only when all relevant checks pass:250251- Working tree is clean in the branch/worktree being cleaned.252- The PR for the task branch is `MERGED`, or the user explicitly confirms that253 the branch is obsolete.254- No open PR depends on the branch.255- No stacked branch or follow-up branch uses the branch as its base, unless the256 user confirms that dependency is gone.257- The branch is not the current checkout when deleting it locally.258- A worktree is not removed unless `git status` inside that worktree is clean.259- Remote deletion targets only the task branch, never a base/protected branch.260261Prefer `git branch -d`. If squash merge makes `git branch -d` reject a branch262whose PR is confirmed `MERGED`, use `git branch -D` only after stating that263reason and only for the task branch.264265**Step 6-4: Verification after cleanup**266267After cleanup, verify and report:268269- Current branch270- `git status --short --branch`271- Remaining local branches relevant to the task272- Remaining remote branches relevant to the task273- `git worktree list`274275---276277## Guardrails278279- Do not treat the current branch as valid just because it is already checked280 out.281- Do not assume a new session can be reliably detected; infer risk from branch,282 commits, dirty files, and task intent.283- Do not run destructive Git commands (`reset`, `checkout --`, `restore`,284 `clean`, `stash`, rebase, branch deletion) without explicit user approval.285- Do not use `git add .`, `git add -A`, or `git add --all`.286- Do not commit staged changes until staged ownership is confirmed.287- Do not move dirty changes across branches or worktrees automatically.288- Do not mix unrelated tasks in one commit just because they are already dirty.289- Explicitly state assumptions about base branch and branch naming.290- Do not end a commit/push/PR workflow without a cleanup decision or a clear291 statement that cleanup is not applicable yet.292- Do not delete local branches, remote branches, or worktrees unless the safety293 checks in Gate 6 pass.294- Do not delete a branch just because it was pushed; open PR branches normally295 stay until merge or an explicit user decision.296- Do not remove the current worktree. Switch away first or remove only a297 separate clean worktree path.298299---300301## Failure Patterns302303Common bad outputs:304305- Saying "working tree clean" but ignoring that the branch itself belongs to a306 previous task307- Continuing on a feature branch whose recent commits are unrelated to the308 current request309- Treating dirty files as current-session changes without evidence310- Recommending `git stash` as a default solution, hiding ownership instead of311 clarifying it312- Creating a new branch from the wrong feature branch when the correct base313 should be `main` or `develop`314- Staging all files after warning that some files are out of scope315- Asking for generic confirmation without listing the exact branch, commits, and316 files that caused the risk317- Ending after push or merge while leaving stale branches/worktrees without318 mentioning cleanup choices319- Deleting a branch for an open PR or an unverified squash merge320- Removing a worktree without checking that worktree's own status321322---323324## Example 1 (Clean Wrong Branch)325326**Input:**327328Current task: add billing export tests. `git status --short --branch` shows a329clean working tree on `feature/oauth-login`. Recent commits mention OAuth330callback handling.331332**Output:**3333341. Branch Context Snapshot: branch `feature/oauth-login`, clean tree, recent335 commits are OAuth-related.3362. Intent Match Verdict: `mismatch` — current task is billing export tests, but337 branch intent is OAuth login.3383. Dirty Worktree Ownership: no dirty files.3394. Recommended Action: create a new branch from the correct base, for example340 `test/billing-export`, before making or committing billing changes.3415. User Confirmation Required: yes — confirm base branch (`main` assumed) and342 new branch/worktree preference.343344---345346## Example 2 (Dirty Previous Session)347348**Input:**349350Current task: update dashboard copy. Current branch is `agent/aaa-refactor`.351Working tree has modified `src/auth/session.ts` and `src/dashboard/Home.tsx`.352Conversation history only touched `src/dashboard/Home.tsx`. Recent commits on353the branch mention auth session refactoring.354355**Output:**3563571. Branch Context Snapshot: branch `agent/aaa-refactor`, dirty files in auth and358 dashboard, recent commits are auth-related.3592. Intent Match Verdict: `blocked` — branch and one dirty file appear to belong360 to a previous auth refactor session.3613. Dirty Worktree Ownership: `src/dashboard/Home.tsx` is current-session;362 `src/auth/session.ts` is carried-forward/unknown.3634. Recommended Action: do not commit from this state. Ask whether to finish the364 auth refactor first, create a separate worktree for dashboard copy, or commit365 only the confirmed dashboard file after explicit approval.3665. User Confirmation Required: yes — exact commit scope must be confirmed before367 staging.368369---370371## Notes372373This skill is intentionally conservative. Its goal is not to automate branch374management; it is to prevent accidental task mixing at the commit boundary.