Git Safety Net
Prevent losing work in a tangle of branches/stashes/rebases, and recover it forensically
when something already went sideways. The commands here are all non-destructive or additive
until a step is explicitly labeled destructive — recovery must never make the loss worse.
Outcome contract — keep the safety net subordinate to the user's job
Before Mode B/E or any command that writes a ref or backup, state the following in the conversation
(do not create another file):
- Outcome: the user-visible end state, in the user's words.
- Current phase: what is authorized now. "Later" work is not authorized in this phase.
- Authorized targets: named objects this phase may inspect, plus the subset it may change.
- Stop condition: observable facts that end the task.
Then enforce these boundaries:
- Evidence scope is not action scope. A read-only audit may discover another clone, ref,
repository, or dangling object. That discovery may widen the report; it does not authorize
preserving, uploading, merging, deleting, or otherwise changing the newly found object.
- Authorization is object-specific, not repository-wide by implication. "Take over",
"continue", or "finish the cleanup" applies only to the checkout/ref/PR the user identified.
A collaborator-owned worktree, branch, or PR discovered later stays report-only until the user
names it as a change target. If the user says to leave it alone, record that exclusion and do
not inspect its working-tree contents, back it up, merge it, unlock/remove it, or mutate its refs.
- Resolve authority from the current request and applicable standing user instructions.
Authority for any action under this Skill is the current request read together with the standing
user instructions that apply to this task (for example, a standing instruction that a task ends
with checks, commit, publication, readback, and retiring that task's own temporary
branches/worktrees). Later user restrictions still control. Splitting the work into phases alone
does not revoke authority the task already carries: when the task already includes retiring its exact temporary resources, complete Mode E
within that same task — a new task or fresh confirmation solely for entering retirement is a
re-ask, not a gate. Mode E's evidence, preservation, and readback gates still apply in full.
A merge alone still does not authorize extra targets, and targets the task's authority does not
name stay report-only until separately authorized.
- Preserve the smallest set threatened by the next authorized destructive action. If the
current phase is only commit/push/verify and no deletion, reset, gc, history rewrite, or
worktree removal is authorized, do not create an all-refs bundle or pin every dangler.
- Classify an artifact before choosing its transport. Durable project source follows the
repository's normal Git/LFS policy. A temporary recovery artifact (bundle, working-tree diff,
snapshot, transport chunk) belongs in a repository-external backup directory. Do not stage,
commit, push, or route it through Git LFS merely to make the backup remote; Git LFS is for
durable versioned project binaries, not a fallback transport for temporary recovery material.
- Keep preservation and retirement as separate phases. A verified recovery artifact proves
recoverability; it does not prove the business code landed. Keep it through the destructive
action and the content-level postconditions. Retire an exact task-owned temporary artifact only
when every payload is landed or proven superseded and the artifact itself has explicit cleanup
authorization. Keep backup-only, unresolved, and mixed artifacts.
- Treat a new storage or execution surface as a scope change. A second repository, new
remote, cloud upload, Git LFS, or full-history export requires re-planning and explicit authority
when the stated outcome actually depends on it. Do not solve a transport problem the user did
not ask to create.
- Prove completion in the user's world. A remote containing the intended commit, preserved
WIP, and the requested branch/worktree state are outcomes. Bundle counts, checksums, upload
receipts, and audit breadth are supporting evidence, never substitutes for that outcome. Stop
when the contract is satisfied; record unrelated findings separately without acting on them.
Before withholding otherwise authorized commits or pushes because a handover says
"do not upload", verify the original restriction's object, action and destination.
Use the convergence authority check;
an assistant-authored restriction is a lookup lead, not a new user decision.
Entry router — pick the mode from what the user is worried about
| The user says / needs… |
Go to |
Local snapshots are blocked by an index.lock or commit-hook refusal |
Blocked local snapshots — preserve the lock and staged state; diagnose both layers before an authorized recovery |
| "I think I lost a commit / branch / stash", "recover the deleted X", "git reflog" |
Mode A — Recover |
| "did I lose anything?", "what worktrees/stashes/branches remain?", after a messy session |
Mode B — Audit & preserve |
| "is everything merged?", "what's still not on main?", before deleting old branches |
Mode C — Verify merged |
| "so this never happens again", starting parallel/multi-branch work |
Mode D — Prevent |
| "clean up worktrees/stashes/branches", "converge everything onto main", "only keep one main branch" |
Mode E — Retire safely |
| "an audit already said it's clean, but is anything else lost?", "check again" |
Mode B, starting at Step 0 — a repeat request usually means the first pass had the wrong scope, not that it looked carelessly |
When in doubt, run the smallest read-only probe that selects a mode. Use Mode B Step 0's
machine-wide discovery only when the outcome is an exhaustive loss audit or the target checkout is
unknown. A named repository/branch/worktree task stays named; findings outside that target are
report-only until the user expands the authorized targets.
Load-bearing rules (internalize these; the modes apply them)
- Get the EVIDENCE SCOPE right before you trust any verdict, without silently expanding the
work scope: every instrument here only sees the repository it runs in.
git worktree list,
git branch -a, git fsck, git stash list,
git log --not --remotes — all of them are structurally blind to an independent clone of
the same repository elsewhere on the machine. A linked worktree (git worktree add) has a
gitlink file pointing home, so it shows up; a second git clone has its own complete .git
and no back-reference, so it shows up in nothing. Run git_find_all_checkouts.sh first only
for an exhaustive audit or unknown target; otherwise audit the named target. Real incident: a
repository audited clean, every branch pushed, while 440 lines of a working feature sat as
untracked files in a sibling clone one rm -rf from gone.
Scope has a second axis: TIME. Every origin/* ref is a cached snapshot from your last
fetch, not the remote — so git fetch --all --prune before you trust any verdict that depends
on one. Read a stale cache in the right direction: for "what would be lost" it errs safe
(it can over-report unpushed work, never hide it), which is why the scripts here still run
offline. For "is this already upstream?" it fails the other way — work the remote already
has reads as unique, so you re-ship it, and if the remote improved it meanwhile your "restore"
silently reverts those improvements while looking like a rescue. Real incident: a
comparison base one day old made an already-merged change look unshipped; the rescue PR would
have reverted three fixes a later review added on top, one of them a security fix.
Scope has a third axis: the REF SET itself moves. A branch inventory and a verified bundle
prove what existed at one instant; they do not authorize deletion five minutes later. Immediately
before deleting, re-enumerate local refs and hosting-service branches, then require every target
ref to still equal its frozen manifest SHA (and bundle head when export was required).
A new branch, a moved tip, or a new parallel
PR reopens classification and the preservation decision; rebuild a required recovery export,
or revalidate the retained carrier for an exact-object exemption. Do not delete against a stale inventory.
Scope has a fourth axis: OWNERSHIP. Repository visibility does not make every visible object
part of this task. Partition discovered refs/worktrees/PRs into change-authorized, inspect-only,
and explicitly excluded sets before acting; compute cleanup success over the authorized set.
- Run
git_loss_audit.sh for the authoritative "what would be lost" check within a
checkout. It compares the current HEAD, every linked-worktree HEAD, local branches, tags,
and every other commit-holding local ref against every remote, then inspects each worktree for
tracked/untracked changes plus stashes, reflog-only and dangling commits. Reflog-only work
includes every linked-worktree HEAD log; it stays advisory but prevents a zero-risk verdict.
Failed content scans or Git
diagnostics make the audit incomplete (exit 1); they never establish a clean result.
Non-commit refs are listed for manual object-preservation review and suppress the zero-risk
verdict without raising the commit-risk exit code. The shorter
git log HEAD --branches --tags --not --remotes misses a detached
HEAD in a different worktree, commits pinned only by non-branch/tag refs, and all uncommitted
files. Ahead/behind counts do not answer
this. Run it in the named checkout, and in additional Step 0 checkouts only after each is
explicitly change-authorized. Run this repository-wide script only when every surface it
enumerates—linked worktrees, local refs/tags, reflogs, stashes, and dangling commits—is inside the
declared evidence scope. It has no exclusion flags. Otherwise limit the claim to the authorized
checkout/ref and use its own status, HEAD, upstream/remote identity, and git log HEAD --not --remotes as scoped evidence; report the other surfaces as not audited.
git reflog is the first move for "I lost a commit," not fsck. Reflog records every
HEAD position (commits, checkouts, resets, rebases) for ~90 days and the lost commit is
usually in its top few lines. git fsck is the deeper net for commits reflog can't reach.
- Preserve before you clean up — and know which backup tool can actually reach the work.
Pin at-risk/dangling commits somewhere garbage collection can't reach them before deleting a
branch, running
gc, or force-pushing. Cleanup is reversible only while a ref (or the reflog
window) still points at the work. Critical asymmetry: bundle, archive, and format-patch
can only reach objects git already knows about. An untracked file that was never git added
and never stash -ued is invisible to those formats — the copy on disk is the only copy, so
preserving it means literally copying the file out. Backing up "the repository" and believing
untracked work came along is how a clean-looking backup silently omits the only thing at risk.
When the backup is a branch pushed into an already-existing repository rather than this one's
own remote, verify shared history before the push (Mode B Step 2) — a similar name proves
nothing.
- Verify "merged" by CONTENT, never by commit count — and know that most content checks are
also unsound. After a squash-merge,
main..branch shows the branch's original commits as
"unmerged" even though their content is on main — often 100+ phantom commits. But swapping
counts for the nearest content check is not enough: in one audit, successive
"surely this is content-level now" instruments each returned a wrong answer — git cherry
(squash rewrites patch-ids → false UNMERGED), a three-dot diff base...ref used to ask
"what does base lack" (three-dot answers a different question and under-reported missing
files), and a file-level existence check (a file present on base can still be missing
the ref's lines). Only the trial merge (git merge-tree, what git_verify_branch_merged.sh
runs) was right every time. Diff-form and rung-by-rung reliability: references/merge_verification.md.
- For a high-stakes exhaustive "is everything merged?" call that will authorize deletion,
verify adversarially. One independent reviewer is the default. Use multiple reviewers only
when distinct repositories or evidence axes cannot be covered by one pass and the user has
authorized that fan-out. Make one pass try to falsify the declared evidence scope (rule 1), but
keep any newly found target report-only under the Outcome contract.
Mode A — Recover lost work
A commit/branch/stash that "disappeared" is almost always still in the object store for ~90 days —
why that is true, and what ends it, is references/recovery_playbook.md § Mental model: nothing is gone
until gc runs. The ladder there is indexed by symptom, so go straight to your rung —
§ Ladder step 1 — git reflog (where most recoveries end),
§ Ladder step 2 — dropped stashes,
§ Ladder step 3 — detached-HEAD work,
§ Ladder step 4 — git fsck for true orphans. The 30-second version:
git reflog --date=iso | head -40 # find the lost HEAD position (most recoveries are here)
git show <sha> # CONFIRM it's the right commit before acting
git switch -c rescue/<name> <sha> # recover onto a NEW branch — never reset onto live work
If reflog doesn't show it, fall through by symptom rather than reaching for fsck first: a
dropped stash has its own recovery route (references/recovery_playbook.md § Ladder step 2), work
abandoned on a detached HEAD has another (§ Ladder step 3), and only a true orphan — from a rebase, say —
needs git fsck --dangling (§ Ladder step 4).
Mode B — Audit what's at risk, then preserve it
Step 0 — establish the evidence scope (rule 1). What "at risk" covers, and the checkout kinds
that hide it, are references/recovery_playbook.md § The authoritative "is anything at risk" check and
§ Linked worktrees and detached worktree HEADs.
Run machine-wide checkout discovery only when
the Outcome contract calls for an exhaustive audit or the target checkout is unknown. For a named
target, record that checkout and continue to Step 1 without turning an unrelated clone into work.
When exhaustive discovery is warranted, find every checkout of this repository on the machine,
including the independent clones no in-repo command can see:
scripts/git_find_all_checkouts.sh # defaults to this repo's parent + grandparent
DEPTH=6 scripts/git_find_all_checkouts.sh ~ # widen when clones live far from each other
It matches sibling checkouts by normalized remote URL (so the SSH and HTTPS forms of one
repository compare equal), falling back to any shared commit history whenever either the current
or a candidate checkout has no origin. That history check works for shallow clones that cannot
see the repository's true root. It never matches by directory name, because an independent clone
is usually named differently from the original (repo vs repo-hotfix), which is exactly when
name matching fails. It canonicalizes path aliases before identifying the current checkout,
disables repository-provided fsmonitor commands while inspecting candidates, and treats commits
reachable from any locally known remote-tracking ref as pushed even when a branch has no upstream.
Exit is 1 when any other checkout holds uncommitted, untracked, unpushed, or uninspectable work.
For an inspect-only checkout, stop at discovery: Step 1 fetches and changes its remote-tracking
refs. Run Step 1 only after that checkout is change-authorized; apply Step 2 only to authorized
items. A "nothing at risk" claim covers only the checkouts actually audited.
Maintainer verification
Run the isolated regression suite after changing checkout discovery:
uv run python -m unittest discover -s tests -p 'test_*.py'
Step 1 — audit (non-destructive). What, if anything, is at risk of loss right now:
When every worktree/ref/tag/reflog/stash/dangler the script enumerates is inside the declared evidence
scope:
scripts/git_loss_audit.sh # defaults to remote "origin"; pass a remote name to override
When any surface listed above is excluded, skip that script and collect only checkout/ref-scoped
evidence:
git status --porcelain=v1 --untracked-files=all
git rev-parse HEAD
git log --oneline HEAD --not --remotes
git ls-remote --exit-code <remote> refs/heads/<branch> # 0 present · 2 absent · 128 probe failed
Both the --exit-code and the fully-qualified refs/heads/ prefix are load-bearing here, not
style: a bare git ls-remote <remote> <branch> reports an unreachable remote and an absent ref
identically (each prints nothing), and a bare branch name also matches a same-named tag. The trap
is measured in both directions under Troubleshooting § "A 'did that branch get deleted?' probe
says it still exists".
For the full audit, expected output is every worktree with branch/detached state and cleanliness,
plus counts of
local-only commits, dirty/unavailable worktrees, stashes, reflog-only commits, and
dangling commits, with non-commit refs listed for manual review.
Exit is 1 when commits exist on no remote, a worktree is dirty/uninspectable, or a content scan is
incomplete. Stashes, reflog-only/dangling commits and non-commit refs remain advisory but prevent
the zero-risk verdict. Exit 0 is therefore not permission to delete reported work: triage or
preserve every reported item. Do not claim cleanup is
safe until the named worktree is clean and its HEAD is proven contained or deliberately preserved.
The scoped path proves only the authorized checkout/ref; it says nothing about excluded worktrees,
other local refs, reflogs, stashes, or danglers, which must remain listed as not audited.
Step 2 — preserve only what the next authorized destructive action threatens (additive,
gc-proof). A finding alone does not need a backup. If deletion, gc, or history rewriting can make
a reported commit unreachable, preserve that exact commit before the action. Use the whole-set
helper only when every reported dangler is actually in the authorized target set:
For reflog-only work, use the targeted pin in the linked preservation procedure; this whole-set
helper does not enumerate reflog-only commits.
scripts/git_preserve_danglers.sh --patch-dir ~/git-danglers # pin + export patches
Why pinning survives gc, and the targeted single-ref form when the whole set is not in scope:
references/recovery_playbook.md § Preserve: pin authorized danglers so gc can never take them.
This pins every dangling commit under refs/dangling-backup/<sha> (garbage collection can never
reach a referenced commit) without cluttering git branch, and optionally writes a .patch per
non-stash commit. For a specific important commit, also give it the full treatment — local
branch and a pushed remote branch and a git format-patch file — so a single disk or a
single git gc can't take it. Details + why triple-backup: references/recovery_playbook.md
§ Triple-backup a critical commit.
Before pushing that preservation branch into an already-existing repository, verify shared
history first — a similar name is not evidence of the right repository. Fetch the candidate
repository's default branch (git fetch <candidate-url> <default-branch>) and run
git merge-base <that-default-branch> <ref>; a local
merge-base exiting 1, or the hosting service's own compare view reporting no common ancestor,
means the two share no history and the target is a different project. Push the branch back to this
work's own remote first; if none exists, create a new repository; if neither applies or the correct
home is unclear, ask the user — but never push anyway because the name matched. Keep the merge-base
check as the test whenever the right home is not obvious: only a repository that already shares
this work's history can host the branch without being a different project. Real incident: a
deployment source's backup branch was pushed to an unrelated private repository chosen by name
resemblance alone. If a push already landed and a
later readback finds no common ancestor, treat the branch as misplaced: move its content to the
correct home, then delete it from the wrong one, rather than leaving it there as "already backed
up somewhere."
Untracked files need a different tool — plain copying (rule 4). Put <backup> outside the
target repository and every checkout being retired. Everything above moves git
objects; a file git was never told about is not one. Preserve those explicitly, and keep the
channels separate so a later reader knows what each restores:
git -C <checkout> status --porcelain | grep '^??' # what is untracked
cp <each-untracked-path> <backup>/ # the ONLY copy — plain cp
git -C <checkout> diff > <backup>/uncommitted.diff # tracked-but-uncommitted
git -C <checkout> bundle create <backup>/history.bundle origin/main..HEAD # unpushed commits
git bundle verify <backup>/history.bundle # prove it restores
Write a one-paragraph README beside them saying where they came from, which branch, and when the
session stopped. A backup nobody can interpret six weeks later is only slightly better than none —
and the person reading it will not be the person who made it.
Mode C — Verify everything is merged (without being fooled by counts)
The trap: a stale branch shows "173 commits ahead of main" yet every line is already on main
(squash-merge artifact) — the mechanism is references/merge_verification.md § Why commit counts lie.
Never conclude "unmerged" from counts. Per-branch content check (procedure and output reading:
§ Per-branch verdict procedure):
scripts/git_verify_branch_merged.sh <branch> [<base>] # base defaults to origin/main
This mode is the one direction where a stale base is unsafe (rule 1): judged against yesterday's
origin/main, a branch whose content landed hours ago still reads UNMERGED, and "rescuing" it
re-applies an older version over whatever was built on top. The script fetches first for exactly
that reason. Because fetch moves remote-tracking refs, run it only after existing coordination has
quiesced every checkout writer and transferred exclusive ownership. If that cannot happen, stay
read-only and report that the merge verdict is unavailable. If the fetch itself fails after
ownership transfer, the script falls back to cached refs and says so on stderr only.
Treat that line as a blocker, not a footnote: rerun once the network is back before acting on the
verdict. Comparing by hand (git diff origin/main <branch>, git log origin/main..<branch>) has
no such safety net at all — the sole writer must refresh authority first, and two-dot vs three-dot
answers different questions (references/merge_verification.md § Pick the diff FORM from the question
you're asking). Signals that may inform a human but must never auto-decide are fenced off in
§ Manual-only investigation hints.
It reports MERGED (ancestor) or MERGED (content contained) — content-safe for a separately
authorized Mode E deletion gate — versus
UNMERGED / NEEDS REVIEW, listing the files the branch would still change. The verdict is sound,
not heuristic: it does a trial 3-way merge of the branch into the base with git merge-tree
(without checkout) and only reports content containment when that merge changes nothing — so a
squash-merged branch reads MERGED despite a nonzero commit count, while a revert/edit/new-file the
base lacks reads UNMERGED. It is safety-biased: anything it can't prove contained is reported
for review, because a false "merged" loses work while a false "unmerged" only costs a look
(references/merge_verification.md
§ Why safety-biased). Why the trial merge is sound rather than a
heuristic, and why --find-object/blob comparison is not: § The sound content check. When base has
changed the SAME lines again since a squash-merge (not just any later edit — an unrelated file or
unrelated lines still leave the current-base trial merge sound) and it now conflicts instead of
reproducing base's tree, --merge-commit <sha> proves containment at that historical merge commit
instead — a different, narrower question than "does base have it now" (§ The
historical-merge-commit rung). For a whole
repo of branches against one frozen base, scripts/git_classify_refs.sh --base <sha> [--pr-map <json>] runs this same ladder — including the merge-commit rung, via --pr-map — in one offline
pass instead of one invocation per branch. For a whole
repo of branches, the verification fan-out pattern — one agent per batch, each told to falsify
"everything is merged," every finding independently re-checked — is
§ Adversarial multi-agent verification, with the constraints those agents must be given in
§ Rules for the verification agents.
Mode D — Prevent the disaster
The habits that keep a branch tangle from ever stranding work:
references/prevention_practices.md. Each bullet below carries the § name of its full
treatment there — follow the one that matches your situation rather than reading the whole file.
The load-bearing few:
- Read the current collaboration contract before prescribing topology. An explicit user or
project decision about shared checkouts, worktrees, branches, or contribution flow outranks this
generic guidance. Do not turn one messy audit into a permanent "one worktree per session" rule.
(§ Choose topology from current authority.)
- One physical checkout gets one writer; parallel agents and sessions stay read-only. A topic
branch inside the same checkout does not isolate the shared working files, current branch, or
index. Writer ownership comes from the repository's task/coordination contract, not a guessed
file list. If ownership is unclear or another writer is active, do not mutate the checkout.
(§ Shared checkout and concurrent sessions: one writer — also governs the "parallel session"
bullets below and covers finding an unidentified writer by process evidence rather
than a guessed name.)
- Commit before switching and push WIP early. Prefer a remote-backed commit over stash
juggling, but preserve a higher-authority narrow stash exception; never use an unscoped stash
to make a dirty checkout look ready.
(§ Parallel / multi-branch work; § Push work-in-progress branches early.)
- Failed fast-forward or partially synchronized checkout: follow
Guarded checkout recovery.
- Worktrees are explicitly authorized, named exceptions — not the standing default. They
isolate working files,
HEAD, and index but still share refs, stashes, object storage, config,
and hooks, and do not copy ignored dependencies. When approved, a linked worktree is safer than
an invisible independent clone but remains a separately audited retirement target.
(§ Audit every authorized worktree before retirement.)
- Handoff and merge by exact commit, then finish with an AND gate. Record branch, local
HEAD,
and fresh remote tip; require them to equal the handoff SHA. Direct merges name that SHA, not the
branch. Hosted merges use an expected-head-SHA precondition when available, or an immediately
preceding hosted head readback that must still equal the handoff SHA. Every session-owned byte
must be in that remote-backed commit, and every residual path must be enumerated and attributed.
- A process snapshot is not a lock, and a merge is not cleanup authority. Any scheduler that
can write this checkout counts as a writer even when its paths are disjoint. Before Git mutation,
the project's existing coordination must prove it quiescent and transfer exclusive ownership;
without that mechanism, stay read-only and report the gap. Do not stop, reconfigure, or invent a
lease for automation under this generic Skill. Retire refs or checkouts only through Mode E
evidence, with authority resolved per the authority definition in the Outcome contract above.
(§ Known automated writers are not session-owned WIP.)
- Confirm the current branch before committing (
git branch --show-current) — a fix committed
onto the wrong feature branch is invisible to its real PR and easy to lose on cleanup.
(§ Confirm the branch before every commit — including why removal from the wrong branch waits
for Mode E.)
- Never race another writer with checkout-relative mutation. If another writer is active, stop
until the repository's coordination system transfers exclusive write ownership. After transfer,
name the exact ref and object when repairing or advancing state; do not rely on whichever branch
happens to be checked out.
reset --hard, merge, and rebase all act on whatever is checked
out at the instant they run. Use checkout-independent forms for ref repair when they match the
authorized outcome:git branch -f <branch> <target> # instead of: switch <branch> && reset --hard <target>
git fetch origin <branch>:<branch> # fast-forward a branch you are not on
git push origin <sha>:refs/heads/<branch>
Real incident: a reset --hard origin/main issued while another session still owned the checkout
landed on that session's feature branch and moved it back two commits. The correct first action is
to stop and transfer ownership; once transferred, an explicitly targeted ref repair avoids making
checkout position part of the operation.
- If a parallel session previously switched the shared tree and stranded your uncommitted work,
do not mutate it until that session is quiescent and exclusive ownership has transferred. Then
follow the incident-only relocation procedure in § Recover stranded work after a parallel session
switched the shared tree: prove your files match
across bases, commit only explicit paths, and restore the prior branch before handing ownership
back. Branch deletion remains a Mode E action, with authority resolved per the authority
definition in the Outcome contract above; a merge or handoff does not itself authorize it.
- The inverse case: another session's commit lands on your branch, and every check you already
run stays green. In a shared checkout, a commit a sibling session makes while
HEAD sits on
your branch becomes a parent of yours and ships inside your PR. git branch --show-current names
your branch, the tree is clean, and git diff --cached --name-status shows exactly your paths —
all true, all blind, because their work left the index the moment they committed. It appears only
in the branch's cumulative range against the base you branched from. Detection is read-only, so
run it before every push and before opening any PR:base=<the base SHA you recorded when you created the branch>
git rev-parse --verify "$base^{commit}" # must print a SHA — see below before trusting the rest
git log --oneline "$base"..HEAD # every commit here must be yours
git diff --name-only "$base" HEAD # every path here must be yours
The verify line is load-bearing. An empty $base turns "$base"..HEAD into HEAD..HEAD:
no output at exit 0, indistinguishable from "no foreign commits". That silent case is the one the
guard exists for; § A foreign commit adopted onto your branch has it and the louder one measured.
And "yours" is not derivable from Git: in a shared checkout both sessions write the same
author and committer, so no flag separates them. It comes from the SHAs you recorded as you
committed. If you cannot say which commits are yours, stop and ask — the repair deletes a commit,
so a guess here is the loss this skill exists to prevent.
Record that base SHA when you branch — deriving it later reads a cached remote ref, and the fetch
that would refresh it is itself ownership-gated § A foreign commit adopted onto your branch.
A foreign commit in that range is evidence another writer was in this checkout, so repair is
not yours to start. Stop; the ownership rules above apply unchanged. Once ownership has
transferred, repair is a history rewrite of your branch — git rebase --onto checks out the
branch it rewrites — so it runs the existing sequence rather than a shortcut: the applicable Mode B
evidence path, then git branch backup/pre-rewrite <your-branch> (Snapshot before any history rewrite
— this is what makes the rebase reversible), then git branch rescue/foreign-<short-sha> <foreign-sha>
(this preserves their work, a separate obligation and a different ref), then
git rebase --onto "<foreign-sha>^" "<foreign-sha>" <your-branch> — onto the foreign commit's
parent, never onto the base, because --onto "$base" discards everything before the foreign
commit, your own earlier commits included, and exits 0. Then re-run the detection above: the
rebase's exit code does not tell you whether it took something of yours with it. Retiring either
ref afterwards requires Mode C/E deletion-grade evidence, not a guess. Full procedure,
and why the "did their work survive?" probes return the wrong answer, in A foreign
commit adopted onto your branch in
references/prevention_practices.md. Real incident: a
sibling session committed while HEAD sat on a freshly created branch; the PR carried that
session's in-progress work, and the only signal was a repo validator reporting two changed
components when the author had touched one.
- If a parallel session is actively writing the shared tree, all repository mutation stops.
Do not
switch, add, reset, create commits with a temporary index, update refs, or push. Use
the repository's coordination system to quiesce that writer and transfer exclusive ownership; if
none exists, report the gap and preserve the current evidence. Once you are the sole writer, an
object-store-only commit can keep attributable foreign WIP out of the shared index and working
tree. Freeze every candidate as the exact Git entry tuple (mode, object ID, path) — bytes alone
are insufficient because 100755, 120000, and 160000 carry executable, symlink, and gitlink
behavior. The safest source is an immutable candidate commit:candidate_ref=<immutable-candidate-commit-oid>
candidate_path=path/to/file
candidate_entry=$(git ls-tree "$candidate_ref" -- "$candidate_path")
candidate_mode=$(printf '%s\n' "$candidate_entry" | awk 'NR == 1 { print $1 }')
candidate_oid=$(printf '%s\n' "$candidate_entry" | awk 'NR == 1 { print $3 }')
test -n "$candidate_mode" && test -n "$candidate_oid" || exit 1
candidate_index=$(mktemp /tmp/git_safety_candidate_index.XXXXXX)
export GIT_INDEX_FILE="$candidate_index" # the tree's real index is untouched
git read-tree origin/main # start from the pushed base, not the dirty tree
git update-index --add --cacheinfo "$candidate_mode,$candidate_oid,$candidate_path"
tree=$(git write-tree)
commit=$(git commit-tree "$tree" -p origin/main -m "…") # HEAD does not move
unset GIT_INDEX_FILE
rm "$candidate_index"
git push origin "$commit":refs/heads/<branch> # open the PR from here
For an owned temporary regular file that is not yet in an immutable commit, derive its intended
mode explicitly (100755 when executable, otherwise 100644) and hash its bytes; fail instead of
applying that route to a symlink or submodule. For those entry types, first freeze an immutable
candidate commit and copy its mode/object tuple as above. Never source an entry from a shared path
that another session is editing. The sequence reads and writes only the object store and a
throwaway index, so git status in the shared tree is byte-for-byte unchanged. It is a
sole-writer preservation technique, not permission to mutate while someone else owns the repo.
commit-tree
does not run the normal git commit hook path: execute the repository's exact pre-commit/security
gates against the candidate before push, and still let pre-push run. Use it only after ownership
transfer, when preserved foreign WIP makes checkout switching or shared-index staging unsuitable.
- A bare
git commit snapshots the whole index, not just what you staged — and a commit that
bypassed the index leaves a trap in it. Moving the current branch without updating the
shared index advances HEAD while the index stays on its old baseline — via commit-tree +
update-ref on that branch, or a git commit through a temporary GIT_INDEX_FILE. (The
sole-writer push-to-another-branch path above moves no local ref, so it leaves no drift.) Every
file the new commit introduced then shows as a staged deletion (git status prints D
lines plus matching ?? untracked entries). git commit -- <path> neither creates nor repairs
this drift — it only updates its own paths. The drift detonates on anyone's next bare
git commit: that commit snapshots the entire index, turning the phantom deletions real —
delivered files vanish from HEAD while the working tree looks untouched. Real incident:
a 24-file delivered directory sat in that window after a temporary-index commit; one bare commit
by a parallel session would have deleted it from the branch tip, and the only sign anywhere was
D lines in git status. Whoever advanced the branch past the index
re-syncs immediately — git diff --cached --name-status, then git restore --staged -- <the paths the commit touched> until those paths no longer appear in the diff (a parallel
session's own staged entries are theirs, not yours to clear). And before any bare commit on a
shared tree, read that same diff as your blast radius — every entry, D lines included, must
be one you intended; an entry you don't recognize means stop, not commit.
(§ Commit-scope hygiene.)
- Before any rebase or branch-delete, run the applicable Mode B evidence path. Use the full
loss audit only when every worktree/ref/tag/reflog/stash/dangler it enumerates is in evidence scope;
otherwise use the authorized checkout/ref's scoped checks and limit the safety claim accordingly.
- Before bumping a shared version/lockfile, check the base's current value so two parallel
branches don't both claim the same bump (a silent collision that blocks the later change from
shipping). (§ Version / lockfile collisions between parallel branches.)
Mode E — Retire worktrees, stashes, and branches safely
The opposite worry from Mode A: not "I lost something" but "these l
…(truncated)
1---2name: git-safety-net3description: >-4 Audits, preserves and recovers local Git state before cleanup: unpushed or wrong-branch commits,5 dirty worktrees, duplicate clones, stashes, dangling commits, squash-merge uncertainty. Use when6 the user fears lost work, wants to recover a commit, asks if a branch is actually merged, asks7 whether a branch, worktree or clone is safe to delete, or wants one clean main (误删分支 / 还有没有丢的东西).8 Not for GitHub PR operations.9metadata:10 source: https://skillmd.com/skills/daymade/git-safety-net11---1213# Git Safety Net1415Prevent losing work in a tangle of branches/stashes/rebases, and recover it forensically16when something already went sideways. The commands here are all **non-destructive or additive**17until a step is explicitly labeled destructive — recovery must never make the loss worse.1819## Outcome contract — keep the safety net subordinate to the user's job2021Before Mode B/E or any command that writes a ref or backup, state the following in the conversation22(do not create another file):2324- **Outcome:** the user-visible end state, in the user's words.25- **Current phase:** what is authorized now. "Later" work is not authorized in this phase.26- **Authorized targets:** named objects this phase may inspect, plus the subset it may change.27- **Stop condition:** observable facts that end the task.2829Then enforce these boundaries:3031- **Evidence scope is not action scope.** A read-only audit may discover another clone, ref,32 repository, or dangling object. That discovery may widen the report; it does not authorize33 preserving, uploading, merging, deleting, or otherwise changing the newly found object.34- **Authorization is object-specific, not repository-wide by implication.** "Take over",35 "continue", or "finish the cleanup" applies only to the checkout/ref/PR the user identified.36 A collaborator-owned worktree, branch, or PR discovered later stays report-only until the user37 names it as a change target. If the user says to leave it alone, record that exclusion and do38 not inspect its working-tree contents, back it up, merge it, unlock/remove it, or mutate its refs.39- **Resolve authority from the current request and applicable standing user instructions.**40 Authority for any action under this Skill is the current request read together with the standing41 user instructions that apply to this task (for example, a standing instruction that a task ends42 with checks, commit, publication, readback, and retiring that task's own temporary43 branches/worktrees). Later user restrictions still control. Splitting the work into phases alone44 does not revoke authority the task already carries: when the task already includes retiring its exact temporary resources, complete Mode E45 within that same task — a new task or fresh confirmation solely for entering retirement is a46 re-ask, not a gate. Mode E's evidence, preservation, and readback gates still apply in full.47 A merge alone still does not authorize extra targets, and targets the task's authority does not48 name stay report-only until separately authorized.49- **Preserve the smallest set threatened by the next authorized destructive action.** If the50 current phase is only commit/push/verify and no deletion, reset, gc, history rewrite, or51 worktree removal is authorized, do not create an all-refs bundle or pin every dangler.52- **Classify an artifact before choosing its transport.** Durable project source follows the53 repository's normal Git/LFS policy. A temporary recovery artifact (bundle, working-tree diff,54 snapshot, transport chunk) belongs in a repository-external backup directory. Do not stage,55 commit, push, or route it through Git LFS merely to make the backup remote; Git LFS is for56 durable versioned project binaries, not a fallback transport for temporary recovery material.57- **Keep preservation and retirement as separate phases.** A verified recovery artifact proves58 recoverability; it does not prove the business code landed. Keep it through the destructive59 action and the content-level postconditions. Retire an exact task-owned temporary artifact only60 when every payload is landed or proven superseded and the artifact itself has explicit cleanup61 authorization. Keep backup-only, unresolved, and mixed artifacts.62- **Treat a new storage or execution surface as a scope change.** A second repository, new63 remote, cloud upload, Git LFS, or full-history export requires re-planning and explicit authority64 when the stated outcome actually depends on it. Do not solve a transport problem the user did65 not ask to create.66- **Prove completion in the user's world.** A remote containing the intended commit, preserved67 WIP, and the requested branch/worktree state are outcomes. Bundle counts, checksums, upload68 receipts, and audit breadth are supporting evidence, never substitutes for that outcome. Stop69 when the contract is satisfied; record unrelated findings separately without acting on them.7071Before withholding otherwise authorized commits or pushes because a handover says72"do not upload", verify the original restriction's object, action and destination.73Use [the convergence authority check](references/merge_verification.md#1-freeze-the-outcome-and-the-first-ref-snapshot);74an assistant-authored restriction is a lookup lead, not a new user decision.7576## Entry router — pick the mode from what the user is worried about7778| The user says / needs… | Go to |79|---|---|80| Local snapshots are blocked by an `index.lock` or commit-hook refusal | [Blocked local snapshots](references/recovery_playbook.md#blocked-local-snapshots) — preserve the lock and staged state; diagnose both layers before an authorized recovery |81| "I think I lost a commit / branch / stash", "recover the deleted X", "git reflog" | **Mode A — Recover** |82| "did I lose anything?", "what worktrees/stashes/branches remain?", after a messy session | **Mode B — Audit & preserve** |83| "is everything merged?", "what's still not on main?", before deleting old branches | **Mode C — Verify merged** |84| "so this never happens again", starting parallel/multi-branch work | **Mode D — Prevent** |85| "clean up worktrees/stashes/branches", "converge everything onto main", "only keep one main branch" | **Mode E — Retire safely** |86| "an audit already said it's clean, but is anything *else* lost?", "check again" | **Mode B, starting at Step 0** — a repeat request usually means the first pass had the wrong scope, not that it looked carelessly |8788When in doubt, run the **smallest read-only probe that selects a mode**. Use Mode B Step 0's89machine-wide discovery only when the outcome is an exhaustive loss audit or the target checkout is90unknown. A named repository/branch/worktree task stays named; findings outside that target are91report-only until the user expands the authorized targets.9293## Load-bearing rules (internalize these; the modes apply them)94951. **Get the EVIDENCE SCOPE right before you trust any verdict, without silently expanding the96 work scope: every instrument here only sees the repository it runs in.** `git worktree list`,97 `git branch -a`, `git fsck`, `git stash list`,98 `git log --not --remotes` — all of them are structurally blind to an **independent clone** of99 the same repository elsewhere on the machine. A linked worktree (`git worktree add`) has a100 gitlink *file* pointing home, so it shows up; a second `git clone` has its own complete `.git`101 and no back-reference, so it shows up in **nothing**. Run `git_find_all_checkouts.sh` first only102 for an exhaustive audit or unknown target; otherwise audit the named target. Real incident: a103 repository audited clean, every branch pushed, while 440 lines of a working feature sat as104 untracked files in a sibling clone one `rm -rf` from gone.105 **Scope has a second axis: TIME.** Every `origin/*` ref is a cached snapshot from your last106 fetch, not the remote — so `git fetch --all --prune` before you trust any verdict that depends107 on one. Read a stale cache in the right direction: for *"what would be lost"* it errs safe108 (it can over-report unpushed work, never hide it), which is why the scripts here still run109 offline. For *"is this already upstream?"* it fails the other way — work the remote already110 has reads as unique, so you re-ship it, and if the remote improved it meanwhile your "restore"111 silently **reverts** those improvements while looking like a rescue. Real incident: a112 comparison base one day old made an already-merged change look unshipped; the rescue PR would113 have reverted three fixes a later review added on top, one of them a security fix.114 **Scope has a third axis: the REF SET itself moves.** A branch inventory and a verified bundle115 prove what existed at one instant; they do not authorize deletion five minutes later. Immediately116 before deleting, re-enumerate local refs and hosting-service branches, then require every target117 ref to still equal its frozen manifest SHA (and bundle head when export was required).118 A new branch, a moved tip, or a new parallel119 PR reopens classification and the preservation decision; rebuild a required recovery export,120 or revalidate the retained carrier for an exact-object exemption. Do not delete against a stale inventory.121 **Scope has a fourth axis: OWNERSHIP.** Repository visibility does not make every visible object122 part of this task. Partition discovered refs/worktrees/PRs into change-authorized, inspect-only,123 and explicitly excluded sets before acting; compute cleanup success over the authorized set.1242. **Run `git_loss_audit.sh` for the authoritative "what would be lost" check *within a125 checkout*.** It compares the current HEAD, every linked-worktree HEAD, local branches, tags,126 and every other commit-holding local ref against every remote, then inspects each worktree for127 tracked/untracked changes plus stashes, reflog-only and dangling commits. Reflog-only work128 includes every linked-worktree HEAD log; it stays advisory but prevents a zero-risk verdict.129 Failed content scans or Git130 diagnostics make the audit incomplete (exit 1); they never establish a clean result.131 Non-commit refs are listed for manual object-preservation review and suppress the zero-risk132 verdict without raising the commit-risk exit code. The shorter133 `git log HEAD --branches --tags --not --remotes` misses a detached134 HEAD in a different worktree, commits pinned only by non-branch/tag refs, and all uncommitted135 files. Ahead/behind counts do **not** answer136 this. Run it in the named checkout, and in additional Step 0 checkouts only after each is137 explicitly change-authorized. Run this repository-wide script only when every surface it138 enumerates—linked worktrees, local refs/tags, reflogs, stashes, and dangling commits—is inside the139 declared evidence scope. It has no exclusion flags. Otherwise limit the claim to the authorized140 checkout/ref and use its own `status`, `HEAD`, upstream/remote identity, and `git log HEAD --not141 --remotes` as scoped evidence; report the other surfaces as not audited.1423. **`git reflog` is the first move for "I lost a commit," not `fsck`.** Reflog records every143 HEAD position (commits, checkouts, resets, rebases) for ~90 days and the lost commit is144 usually in its top few lines. `git fsck` is the deeper net for commits reflog can't reach.1454. **Preserve before you clean up — and know which backup tool can actually reach the work.**146 Pin at-risk/dangling commits somewhere garbage collection can't reach them *before* deleting a147 branch, running `gc`, or force-pushing. Cleanup is reversible only while a ref (or the reflog148 window) still points at the work. **Critical asymmetry: `bundle`, `archive`, and `format-patch`149 can only reach objects git already knows about.** An untracked file that was never `git add`ed150 and never `stash -u`ed is invisible to those formats — the copy on disk is the only copy, so151 preserving it means literally copying the file out. Backing up "the repository" and believing152 untracked work came along is how a clean-looking backup silently omits the only thing at risk.153 When the backup is a branch pushed into an already-existing repository rather than this one's154 own remote, verify shared history before the push (Mode B Step 2) — a similar name proves155 nothing.1565. **Verify "merged" by CONTENT, never by commit count — and know that most content checks are157 also unsound.** After a squash-merge, `main..branch` shows the branch's original commits as158 "unmerged" even though their content is on main — often 100+ phantom commits. But swapping159 counts for the *nearest* content check is not enough: in one audit, successive160 "surely this is content-level now" instruments each returned a wrong answer — `git cherry`161 (squash rewrites patch-ids → false UNMERGED), a **three-dot** `diff base...ref` used to ask162 "what does base lack" (three-dot answers a different question and **under-reported missing163 files**), and a file-level existence check (a file present on base can still be missing164 the ref's lines). Only the trial merge (`git merge-tree`, what `git_verify_branch_merged.sh`165 runs) was right every time. Diff-form and rung-by-rung reliability: **[references/merge_verification.md](references/merge_verification.md)**.1666. **For a high-stakes exhaustive "is everything merged?" call that will authorize deletion,167 verify adversarially.** One independent reviewer is the default. Use multiple reviewers only168 when distinct repositories or evidence axes cannot be covered by one pass and the user has169 authorized that fan-out. Make one pass try to falsify the declared evidence scope (rule 1), but170 keep any newly found target report-only under the Outcome contract.171172## Mode A — Recover lost work173174A commit/branch/stash that "disappeared" is almost always still in the object store for ~90 days —175why that is true, and what ends it, is **[references/recovery_playbook.md](references/recovery_playbook.md)** § Mental model: nothing is gone176until gc runs. The ladder there is indexed by symptom, so go straight to your rung —177§ Ladder step 1 — `git reflog` (where most recoveries end),178§ Ladder step 2 — dropped stashes,179§ Ladder step 3 — detached-HEAD work,180§ Ladder step 4 — `git fsck` for true orphans. The 30-second version:181182```bash183git reflog --date=iso | head -40 # find the lost HEAD position (most recoveries are here)184git show <sha> # CONFIRM it's the right commit before acting185git switch -c rescue/<name> <sha> # recover onto a NEW branch — never reset onto live work186```187188If reflog doesn't show it, fall through by symptom rather than reaching for `fsck` first: a189dropped stash has its own recovery route (**[references/recovery_playbook.md](references/recovery_playbook.md)** § Ladder step 2), work190abandoned on a detached HEAD has another (§ Ladder step 3), and only a true orphan — from a rebase, say —191needs `git fsck --dangling` (§ Ladder step 4).192193## Mode B — Audit what's at risk, then preserve it194195**Step 0 — establish the evidence scope (rule 1).** What "at risk" covers, and the checkout kinds196that hide it, are **[references/recovery_playbook.md](references/recovery_playbook.md)** § The authoritative "is anything at risk" check and197§ Linked worktrees and detached worktree HEADs.198Run machine-wide checkout discovery only when199the Outcome contract calls for an exhaustive audit or the target checkout is unknown. For a named200target, record that checkout and continue to Step 1 without turning an unrelated clone into work.201When exhaustive discovery is warranted, find every checkout of this repository on the machine,202including the independent clones no in-repo command can see:203204```bash205scripts/git_find_all_checkouts.sh # defaults to this repo's parent + grandparent206DEPTH=6 scripts/git_find_all_checkouts.sh ~ # widen when clones live far from each other207```208209It matches sibling checkouts by normalized remote URL (so the SSH and HTTPS forms of one210repository compare equal), falling back to **any shared commit history** whenever either the current211or a candidate checkout has no `origin`. That history check works for shallow clones that cannot212see the repository's true root. It never matches by directory name, because an independent clone213is usually named differently from the original (`repo` vs `repo-hotfix`), which is exactly when214name matching fails. It canonicalizes path aliases before identifying the current checkout,215disables repository-provided fsmonitor commands while inspecting candidates, and treats commits216reachable from any locally known remote-tracking ref as pushed even when a branch has no upstream.217Exit is 1 when any *other* checkout holds uncommitted, untracked, unpushed, or uninspectable work.218For an inspect-only checkout, stop at discovery: Step 1 fetches and changes its remote-tracking219refs. Run Step 1 only after that checkout is change-authorized; apply Step 2 only to authorized220items. A "nothing at risk" claim covers only the checkouts actually audited.221222### Maintainer verification223224Run the isolated regression suite after changing checkout discovery:225226```bash227uv run python -m unittest discover -s tests -p 'test_*.py'228```229230**Step 1 — audit (non-destructive).** What, if anything, is at risk of loss right now:231232When every worktree/ref/tag/reflog/stash/dangler the script enumerates is inside the declared evidence233scope:234235```bash236scripts/git_loss_audit.sh # defaults to remote "origin"; pass a remote name to override237```238239When any surface listed above is excluded, skip that script and collect only checkout/ref-scoped240evidence:241242```bash243git status --porcelain=v1 --untracked-files=all244git rev-parse HEAD245git log --oneline HEAD --not --remotes246git ls-remote --exit-code <remote> refs/heads/<branch> # 0 present · 2 absent · 128 probe failed247```248249Both the `--exit-code` and the fully-qualified `refs/heads/` prefix are load-bearing here, not250style: a bare `git ls-remote <remote> <branch>` reports an unreachable remote and an absent ref251*identically* (each prints nothing), and a bare branch name also matches a same-named tag. The trap252is measured in both directions under **Troubleshooting** § "A 'did that branch get deleted?' probe253says it still exists".254255For the full audit, expected output is every worktree with branch/detached state and cleanliness,256plus counts of257**local-only commits**, **dirty/unavailable worktrees**, **stashes**, **reflog-only commits**, and258**dangling commits**, with non-commit refs listed for manual review.259Exit is 1 when commits exist on no remote, a worktree is dirty/uninspectable, or a content scan is260incomplete. Stashes, reflog-only/dangling commits and non-commit refs remain advisory but prevent261the zero-risk verdict. Exit 0 is therefore not permission to delete reported work: triage or262preserve every reported item. Do not claim cleanup is263safe until the named worktree is clean and its HEAD is proven contained or deliberately preserved.264The scoped path proves only the authorized checkout/ref; it says nothing about excluded worktrees,265other local refs, reflogs, stashes, or danglers, which must remain listed as not audited.266267**Step 2 — preserve only what the next authorized destructive action threatens (additive,268gc-proof).** A finding alone does not need a backup. If deletion, gc, or history rewriting can make269a reported commit unreachable, preserve that exact commit before the action. Use the whole-set270helper only when every reported dangler is actually in the authorized target set:271272For reflog-only work, use the targeted pin in the linked preservation procedure; this whole-set273helper does not enumerate reflog-only commits.274275```bash276scripts/git_preserve_danglers.sh --patch-dir ~/git-danglers # pin + export patches277```278279Why pinning survives `gc`, and the targeted single-ref form when the whole set is not in scope:280**[references/recovery_playbook.md](references/recovery_playbook.md)** § Preserve: pin authorized danglers so gc can never take them.281282This pins every dangling commit under `refs/dangling-backup/<sha>` (garbage collection can never283reach a referenced commit) without cluttering `git branch`, and optionally writes a `.patch` per284non-stash commit. For a *specific* important commit, also give it the full treatment — local285branch **and** a pushed remote branch **and** a `git format-patch` file — so a single disk or a286single `git gc` can't take it. Details + why triple-backup: **[references/recovery_playbook.md](references/recovery_playbook.md)**287§ Triple-backup a critical commit.288289**Before pushing that preservation branch into an already-existing repository, verify shared290history first — a similar name is not evidence of the right repository.** Fetch the candidate291repository's default branch (`git fetch <candidate-url> <default-branch>`) and run292`git merge-base <that-default-branch> <ref>`; a local293`merge-base` exiting 1, or the hosting service's own compare view reporting no common ancestor,294means the two share no history and the target is a different project. Push the branch back to this295work's own remote first; if none exists, create a new repository; if neither applies or the correct296home is unclear, ask the user — but never push anyway because the name matched. Keep the merge-base297check as the test whenever the right home is not obvious: only a repository that already shares298this work's history can host the branch without being a different project. Real incident: a299deployment source's backup branch was pushed to an unrelated private repository chosen by name300resemblance alone. If a push already landed and a301later readback finds no common ancestor, treat the branch as misplaced: move its content to the302correct home, then delete it from the wrong one, rather than leaving it there as "already backed303up somewhere."304305**Untracked files need a different tool — plain copying (rule 4).** Put `<backup>` outside the306target repository and every checkout being retired. Everything above moves *git307objects*; a file git was never told about is not one. Preserve those explicitly, and keep the308channels separate so a later reader knows what each restores:309310```bash311git -C <checkout> status --porcelain | grep '^??' # what is untracked312cp <each-untracked-path> <backup>/ # the ONLY copy — plain cp313git -C <checkout> diff > <backup>/uncommitted.diff # tracked-but-uncommitted314git -C <checkout> bundle create <backup>/history.bundle origin/main..HEAD # unpushed commits315git bundle verify <backup>/history.bundle # prove it restores316```317318Write a one-paragraph `README` beside them saying where they came from, which branch, and when the319session stopped. A backup nobody can interpret six weeks later is only slightly better than none —320and the person reading it will not be the person who made it.321322## Mode C — Verify everything is merged (without being fooled by counts)323324The trap: a stale branch shows "173 commits ahead of main" yet every line is already on main325(squash-merge artifact) — the mechanism is **[references/merge_verification.md](references/merge_verification.md)** § Why commit counts lie.326Never conclude "unmerged" from counts. Per-branch content check (procedure and output reading:327§ Per-branch verdict procedure):328329```bash330scripts/git_verify_branch_merged.sh <branch> [<base>] # base defaults to origin/main331```332333This mode is the one direction where a stale base is *unsafe* (rule 1): judged against yesterday's334`origin/main`, a branch whose content landed hours ago still reads UNMERGED, and "rescuing" it335re-applies an older version over whatever was built on top. The script fetches first for exactly336that reason. Because fetch moves remote-tracking refs, run it only after existing coordination has337quiesced every checkout writer and transferred exclusive ownership. If that cannot happen, stay338read-only and report that the merge verdict is unavailable. If the fetch itself fails after339ownership transfer, the script falls back to cached refs and says so **on stderr only**.340Treat that line as a blocker, not a footnote: rerun once the network is back before acting on the341verdict. Comparing by hand (`git diff origin/main <branch>`, `git log origin/main..<branch>`) has342no such safety net at all — the sole writer must refresh authority first, and two-dot vs three-dot343answers different questions (**[references/merge_verification.md](references/merge_verification.md)** § Pick the diff FORM from the question344you're asking). Signals that may inform a human but must never auto-decide are fenced off in345§ Manual-only investigation hints.346347It reports **MERGED (ancestor)** or **MERGED (content contained)** — content-safe for a separately348authorized Mode E deletion gate — versus349**UNMERGED / NEEDS REVIEW**, listing the files the branch would still change. The verdict is sound,350not heuristic: it does a trial 3-way merge of the branch *into* the base with `git merge-tree`351(without checkout) and only reports content containment when that merge changes nothing — so a352squash-merged branch reads MERGED despite a nonzero commit count, while a revert/edit/new-file the353base lacks reads UNMERGED. It is **safety-biased**: anything it can't prove contained is reported354for review, because a false "merged" loses work while a false "unmerged" only costs a look355(**[references/merge_verification.md](references/merge_verification.md)**356§ Why safety-biased). Why the trial merge is sound rather than a357heuristic, and why `--find-object`/blob comparison is not: § The sound content check. When base has358changed the SAME lines again since a squash-merge (not just any later edit — an unrelated file or359unrelated lines still leave the current-base trial merge sound) and it now conflicts instead of360reproducing base's tree, `--merge-commit <sha>` proves containment at that historical merge commit361instead — a different, narrower question than "does base have it *now*" (§ The362historical-merge-commit rung). For a whole363repo of branches against one frozen base, `scripts/git_classify_refs.sh --base <sha> [--pr-map364<json>]` runs this same ladder — including the merge-commit rung, via `--pr-map` — in one offline365pass instead of one invocation per branch. For a whole366repo of branches, the verification fan-out pattern — one agent per batch, each told to *falsify*367"everything is merged," every finding independently re-checked — is368§ Adversarial multi-agent verification, with the constraints those agents must be given in369§ Rules for the verification agents.370371## Mode D — Prevent the disaster372373The habits that keep a branch tangle from ever stranding work:374**[references/prevention_practices.md](references/prevention_practices.md)**. Each bullet below carries the `§` name of its full375treatment there — follow the one that matches your situation rather than reading the whole file.376The load-bearing few:377378- **Read the current collaboration contract before prescribing topology.** An explicit user or379 project decision about shared checkouts, worktrees, branches, or contribution flow outranks this380 generic guidance. Do not turn one messy audit into a permanent "one worktree per session" rule.381 (§ Choose topology from current authority.)382- **One physical checkout gets one writer; parallel agents and sessions stay read-only.** A topic383 branch inside the same checkout does not isolate the shared working files, current branch, or384 index. Writer ownership comes from the repository's task/coordination contract, not a guessed385 file list. If ownership is unclear or another writer is active, do not mutate the checkout.386 (§ Shared checkout and concurrent sessions: one writer — also governs the "parallel session"387 bullets below and covers finding an unidentified writer by process evidence rather388 than a guessed name.)389- **Commit before switching and push WIP early.** Prefer a remote-backed commit over stash390 juggling, but preserve a higher-authority narrow stash exception; never use an unscoped stash391 to make a dirty checkout look ready.392 (§ Parallel / multi-branch work; § Push work-in-progress branches early.)393- **Failed fast-forward or partially synchronized checkout:** follow394 [Guarded checkout recovery](references/prevention_practices.md#guarded-checkout-recovery).395- **Worktrees are explicitly authorized, named exceptions — not the standing default.** They396 isolate working files, `HEAD`, and index but still share refs, stashes, object storage, config,397 and hooks, and do not copy ignored dependencies. When approved, a linked worktree is safer than398 an invisible independent clone but remains a separately audited retirement target.399 (§ Audit every authorized worktree before retirement.)400- **Handoff and merge by exact commit, then finish with an AND gate.** Record branch, local `HEAD`,401 and fresh remote tip; require them to equal the handoff SHA. Direct merges name that SHA, not the402 branch. Hosted merges use an expected-head-SHA precondition when available, or an immediately403 preceding hosted head readback that must still equal the handoff SHA. Every session-owned byte404 must be in that remote-backed commit, and every residual path must be enumerated and attributed.405- **A process snapshot is not a lock, and a merge is not cleanup authority.** Any scheduler that406 can write this checkout counts as a writer even when its paths are disjoint. Before Git mutation,407 the project's existing coordination must prove it quiescent and transfer exclusive ownership;408 without that mechanism, stay read-only and report the gap. Do not stop, reconfigure, or invent a409 lease for automation under this generic Skill. Retire refs or checkouts only through Mode E410 evidence, with authority resolved per the authority definition in the Outcome contract above.411 (§ Known automated writers are not session-owned WIP.)412- **Confirm the current branch before committing** (`git branch --show-current`) — a fix committed413 onto the wrong feature branch is invisible to its real PR and easy to lose on cleanup.414 (§ Confirm the branch before every commit — including why removal from the wrong branch waits415 for Mode E.)416- **Never race another writer with checkout-relative mutation.** If another writer is active, stop417 until the repository's coordination system transfers exclusive write ownership. After transfer,418 name the exact ref and object when repairing or advancing state; do not rely on whichever branch419 happens to be checked out. `reset --hard`, `merge`, and `rebase` all act on *whatever is checked420 out at the instant they run*. Use checkout-independent forms for ref repair when they match the421 authorized outcome:422 ```bash423 git branch -f <branch> <target> # instead of: switch <branch> && reset --hard <target>424 git fetch origin <branch>:<branch> # fast-forward a branch you are not on425 git push origin <sha>:refs/heads/<branch>426 ```427 Real incident: a `reset --hard origin/main` issued while another session still owned the checkout428 landed on that session's feature branch and moved it back two commits. The correct first action is429 to stop and transfer ownership; once transferred, an explicitly targeted ref repair avoids making430 checkout position part of the operation.431- **If a parallel session previously switched the shared tree and stranded your uncommitted work,**432 do not mutate it until that session is quiescent and exclusive ownership has transferred. Then433 follow the incident-only relocation procedure in § Recover stranded work after a parallel session434 switched the shared tree: prove your files match435 across bases, commit only explicit paths, and restore the prior branch before handing ownership436 back. Branch deletion remains a Mode E action, with authority resolved per the authority437 definition in the Outcome contract above; a merge or handoff does not itself authorize it.438- **The inverse case: another session's *commit* lands on your branch, and every check you already439 run stays green.** In a shared checkout, a commit a sibling session makes while `HEAD` sits on440 your branch becomes a parent of yours and ships inside your PR. `git branch --show-current` names441 your branch, the tree is clean, and `git diff --cached --name-status` shows exactly your paths —442 all true, all blind, because their work left the index the moment they committed. It appears only443 in the branch's cumulative range against the base you branched from. Detection is read-only, so444 run it before every push and before opening any PR:445 ```bash446 base=<the base SHA you recorded when you created the branch>447 git rev-parse --verify "$base^{commit}" # must print a SHA — see below before trusting the rest448 git log --oneline "$base"..HEAD # every commit here must be yours449 git diff --name-only "$base" HEAD # every path here must be yours450 ```451 **The verify line is load-bearing.** An **empty** `$base` turns `"$base"..HEAD` into `HEAD..HEAD`:452 no output at exit 0, indistinguishable from "no foreign commits". That silent case is the one the453 guard exists for; § A foreign commit adopted onto your branch has it and the louder one measured.454 And **"yours" is not derivable from Git**: in a shared checkout both sessions write the same455 author and committer, so no flag separates them. It comes from the SHAs you recorded as you456 committed. If you cannot say which commits are yours, stop and ask — the repair deletes a commit,457 so a guess here is the loss this skill exists to prevent.458 Record that base SHA when you branch — deriving it later reads a cached remote ref, and the fetch459 that would refresh it is itself ownership-gated § A foreign commit adopted onto your branch.460 **A foreign commit in that range is evidence another writer was in this checkout, so repair is461 not yours to start.** Stop; the ownership rules above apply unchanged. Once ownership has462 transferred, repair is a history rewrite of *your* branch — `git rebase --onto` checks out the463 branch it rewrites — so it runs the existing sequence rather than a shortcut: the applicable Mode B464 evidence path, then `git branch backup/pre-rewrite <your-branch>` (**Snapshot before any history rewrite**465 — this is what makes the rebase reversible), then `git branch rescue/foreign-<short-sha> <foreign-sha>`466 (this preserves *their* work, a separate obligation and a different ref), then467 `git rebase --onto "<foreign-sha>^" "<foreign-sha>" <your-branch>` — **onto the foreign commit's468 parent, never onto the base**, because `--onto "$base"` discards everything before the foreign469 commit, your own earlier commits included, and exits 0. Then re-run the detection above: the470 rebase's exit code does not tell you whether it took something of yours with it. Retiring either471 ref afterwards requires Mode C/E deletion-grade evidence, not a guess. Full procedure,472 and why the "did their work survive?" probes return the wrong answer, in **A foreign473 commit adopted onto your branch** in474 [references/prevention_practices.md](references/prevention_practices.md). Real incident: a475 sibling session committed while `HEAD` sat on a freshly created branch; the PR carried that476 session's in-progress work, and the only signal was a repo validator reporting two changed477 components when the author had touched one.478- **If a parallel session is *actively* writing the shared tree, all repository mutation stops.**479 Do not `switch`, `add`, `reset`, create commits with a temporary index, update refs, or push. Use480 the repository's coordination system to quiesce that writer and transfer exclusive ownership; if481 none exists, report the gap and preserve the current evidence. Once you are the sole writer, an482 object-store-only commit can keep attributable foreign WIP out of the shared index and working483 tree. Freeze every candidate as the exact Git entry tuple `(mode, object ID, path)` — bytes alone484 are insufficient because `100755`, `120000`, and `160000` carry executable, symlink, and gitlink485 behavior. The safest source is an immutable candidate commit:486 ```bash487 candidate_ref=<immutable-candidate-commit-oid>488 candidate_path=path/to/file489 candidate_entry=$(git ls-tree "$candidate_ref" -- "$candidate_path")490 candidate_mode=$(printf '%s\n' "$candidate_entry" | awk 'NR == 1 { print $1 }')491 candidate_oid=$(printf '%s\n' "$candidate_entry" | awk 'NR == 1 { print $3 }')492 test -n "$candidate_mode" && test -n "$candidate_oid" || exit 1493494 candidate_index=$(mktemp /tmp/git_safety_candidate_index.XXXXXX)495 export GIT_INDEX_FILE="$candidate_index" # the tree's real index is untouched496 git read-tree origin/main # start from the pushed base, not the dirty tree497 git update-index --add --cacheinfo "$candidate_mode,$candidate_oid,$candidate_path"498 tree=$(git write-tree)499 commit=$(git commit-tree "$tree" -p origin/main -m "…") # HEAD does not move500 unset GIT_INDEX_FILE501 rm "$candidate_index"502 git push origin "$commit":refs/heads/<branch> # open the PR from here503 ```504 For an owned temporary **regular file** that is not yet in an immutable commit, derive its intended505 mode explicitly (`100755` when executable, otherwise `100644`) and hash its bytes; fail instead of506 applying that route to a symlink or submodule. For those entry types, first freeze an immutable507 candidate commit and copy its mode/object tuple as above. Never source an entry from a shared path508 that another session is editing. The sequence reads and writes only the object store and a509 throwaway index, so `git status` in the shared tree is byte-for-byte unchanged. It is a510 sole-writer preservation technique, not permission to mutate while someone else owns the repo.511 `commit-tree`512 does not run the normal `git commit` hook path: execute the repository's exact pre-commit/security513 gates against the candidate before push, and still let pre-push run. Use it only after ownership514 transfer, when preserved foreign WIP makes checkout switching or shared-index staging unsuitable.515- **A bare `git commit` snapshots the *whole* index, not just what you staged — and a commit that516 bypassed the index leaves a trap in it.** Moving the **current** branch without updating the517 shared index advances HEAD while the index stays on its old baseline — via `commit-tree` +518 `update-ref` on that branch, or a `git commit` through a temporary `GIT_INDEX_FILE`. (The519 sole-writer push-to-another-branch path above moves no *local* ref, so it leaves no drift.) Every520 file the new commit introduced then shows as a *staged deletion* (`git status` prints `D `521 lines plus matching `??` untracked entries). `git commit -- <path>` neither creates nor repairs522 this drift — it only updates its own paths. The drift detonates on anyone's next bare523 `git commit`: that commit snapshots the entire index, turning the phantom deletions real —524 delivered files vanish from HEAD while the working tree looks untouched. Real incident:525 a 24-file delivered directory sat in that window after a temporary-index commit; one bare commit526 by a parallel session would have deleted it from the branch tip, and the only sign anywhere was527 `D ` lines in `git status`. **Whoever advanced the branch past the index528 re-syncs immediately** — `git diff --cached --name-status`, then `git restore --staged --529 <the paths the commit touched>` until those paths no longer appear in the diff (a parallel530 session's own staged entries are theirs, not yours to clear). **And before any bare commit on a531 shared tree, read that same diff as your blast radius** — every entry, `D` lines included, must532 be one you intended; an entry you don't recognize means stop, not commit.533 (§ Commit-scope hygiene.)534- **Before any rebase or branch-delete, run the applicable Mode B evidence path.** Use the full535 loss audit only when every worktree/ref/tag/reflog/stash/dangler it enumerates is in evidence scope;536 otherwise use the authorized checkout/ref's scoped checks and limit the safety claim accordingly.537- **Before bumping a shared version/lockfile, check the base's current value** so two parallel538 branches don't both claim the same bump (a silent collision that blocks the later change from539 shipping). (§ Version / lockfile collisions between parallel branches.)540541## Mode E — Retire worktrees, stashes, and branches safely542543The opposite worry from Mode A: not "I lost something" but "these l544545…(truncated)