merge-smith — analyse branches, merge by risk
Agents do the reading and the routing; git does the merging on a throwaway integration branch, so nothing is risked. The base branch (main/develop) is never modified directly and nothing leaves the machine without an explicit yes.
Model tiers (best model where being wrong is expensive, cheap everywhere
else): branch analysis → Sonnet, conflict classification, per hunk →
Opus, trivial hunk auto-resolve → Sonnet, semantic resolution proposed →
Fable (plus a second Fable review where Phase 3 requires one), approved text
applied → the main session, verification failures and rework → Opus,
an unexplained reconcile failure diagnosed → Fable. Dispatch via the Agent
tool with the matching model override; payloads, return formats and timeouts:
references/conflict-routing.md.
Same split the rest of skillator uses — Fable decides, Opus builds. A bad
semantic merge is the worst failure this skill has: it exits 0, the tests pass,
and a change quietly disappears until production. Deciding what the merged hunk
should say is judgement, not lookup, so it goes to the strongest model
(model: "fable"; on another host, its top reasoning tier per §Other hosts).
Pasting in the approved text is not work for a fresh agent: the main session
already holds the hunk, the proposal and the approval. Fixing whatever
verification then catches is implementation — Opus's job, and handing it to the
deep tier is both worse and dearer.
Neither tier touches the mechanical majority. Fable sees only the semantic conflict hunks — typically a handful, not the merge. Opus sees only the classification and a failing check. Enumerating branches, regenerating a lockfile and re-running a green suite stay on Sonnet.
The aim: the source's work arrives in the destination, and the destination is not disturbed on the way in. Both halves are verified in Phase 4 — a merge that lands the feature while silently reverting base's newer work is a failed merge that reports success.
Vocabulary, shared with mergeprep-oracle: the source is the branch being
merged, the destination (<base>) is what it merges into. Same words, same
apply --reverse --check reconcile, same rule that a non-zero exit is evidence.
Mechanism: local git for all merge/conflict work; gh for PR context (titles,
descriptions, review/check state) and the optional final PR. If gh isn't
authenticated, fall back to pure git and say so.
Phase 0 — Orient & confirm
Establish, then confirm back before touching anything:
- Branches in scope and the base/target (main, develop, a release branch).
- Mode:
consolidate(many → one integration branch) ·into-base(one feature → base) ·reconcile(branches that edited the same code differently — conflicts are the main event, prefer best-version selection over union). Detect from the request; if ambiguous, ask once. - Direction — always stated, never inferred. Write it back as one line and get a
yes before anything else:
merging <source> INTO <destination>. Branch names lie (developmerged into a feature is a legitimate and completely different operation), and the two directions produce different trees, different conflict winners, and different blast radii. If the user's phrasing is reversible at all ("merge dev and my branch"), ask — this is the one question that is never worth guessing. - Pre-flight — run references/git-procedure.md
§Phase 0 and stop on any
STOP:line. It requires a clean tree (emptygit status --porcelain; never auto-stash — a dirty tree abortsgit mergeand corrupts every reconcile), and fast-forwards local<base>toorigin/<base>:fetch --allmovesorigin/<base>, not the local ref the integration branch is cut from. When<base>is checked out,git fetch origin <base>:<base>refuses with exit 128 — that is not divergence; the procedure usesgit merge --ff-onlythere. Only<base>not being an ancestor oforigin/<base>is divergence: stop and ask. It also lists.gitattributesmerge drivers (union/oursduplicate or drop lines silently) and LFS paths — log each. - Confirm the branches exist and their base. Note anything already merged (skip it) or wildly stale.
- Resuming? A
MERGE_HEAD, or an openmergerun inrelay-morpheus.sh list, means a session died mid-run: references/between-merges.md §Resume comes first, before the clean-tree check.
Never start merging on an unconfirmed branch list or base.
No user to confirm? A subagent, a batch run, or a "just go ahead" brief — that is not the direction and it is not push approval.
- Direction first. If the request does not say which branch goes INTO which
("merge X and Y", "merge the A work and the B work"), stop before the first
merge — no
git mergeeven on a throwaway branch — and report the two directions that exist (X INTO Y/Y INTO X) and what each would change. One side already being onmainis not a direction. The direction is never anassumed:call: both answers look sensible, they give different trees, and "go ahead" answers neither. - Direction stated → continue locally rather than blocking. Everything happens
on a throwaway integration branch, so mark every other unanswered call
assumed:in the merge log — semantic conflicts applied as proposed, verification run, Phase 5 ending at hand off locally — and list those assumptions in the report. - Push, PR and swap-in need a real yes — deleting an integration branch costs nothing, an unapproved push costs everyone.
If a branch is stale or carries unrelated/no-op churn, run
mergeprep-oracleon it first — it preps the branch in place (onto current base, unintended paths dropped) and commits a prep document to it, so this merge integrates nothing old or untouched. Read that document (docs/merges/prep-<branch>-*.md) before merging: it names every path deliberately dropped and every reviewer edit.
Phase 1 — Analyse the branches (Sonnet, in parallel)
One analysis subagent per branch (model: "sonnet"), each returns structured:
BRANCH: <name> (ahead <n> / behind <n> vs base)
INTENT: <what it does — from commits, diff, and the PR body if gh has one>
TOUCHES: <key files / areas>
RISK: <low|med|high> + why (migrations, shared core, deletions, deps)
Then build two things from the results (main session, cheap):
- Overlap matrix — which branches touch the same files (the conflict predictor).
- RISK cross-check — Sonnet's rating is a claim. A branch rated below high that
overlaps another in the matrix, or whose
git diff --name-only <base>...<branch>hits migrations, schema, auth, payments or lockfiles, is bumped to high; log it. - Recommended merge order — least-overlapping / lowest-risk first, dependencies
respected, so early merges don't compound conflicts. In
reconcilemode, order by which branch is the intended base of truth.
Present the analysis + predicted conflicts + proposed order. This is the "analyse the branches" deliverable — a light confirm here is cheap; a wrong order is not.
Phase 2 — Set up the integration branch
Create a throwaway branch from the base — integration/<YYYY-MM-DD>-<slug>, with
-2, -3 when a re-run already used the name (git-procedure.md §Phase 2; never reuse
an existing one) — and open a merge log file (docs/merges/merge-<date>-<slug>.md,
committed on the integration branch after every step, never only in a scratchpad):
record base, the cut commit, branches, order, and (as you go) every conflict + how it
was resolved.
The log makes the whole run auditable and revertible (drop the branch = zero harm).
Register the order with relay-morpheus — one stage per source — so a dead session
resumes at the right step (between-merges.md §Progress on disk).
Phase 3 — Merge by risk
Merge each branch onto the integration branch in order, one source per merge
commit: git -c rerere.enabled=false merge --no-ff --no-commit <source> — never
squash, octopus or fast-forward (Phase 4 needs HEAD^1 = the branch before this
source), and no rerere replaying a resolution nobody decided this run. Its relay stage
goes ~ before the merge. Between the merge and its commit: renumber the source's
colliding ticket IDs (renumber-tickets.sh; destination IDs never move) and run the
hazard check — duplicate migration numbers, check-tickets.sh, a build — because
those break with no conflict at all (between-merges.md). Then commit, run Phase 4's
reconcile, mark the stage x, and commit the log before merging the next.
On a conflict, classify each conflicted hunk, then route. The classifier is Opus, reading the diff3 view
below (base visible); it logs a class: + why: row per hunk before any
cheap-tier resolve — a cheap model labelling its own work trivial is how a logic
conflict skips Fable. One file can hold a trivial and a semantic hunk: two routes.
The main session may fill the classifier or trivial-resolver seat itself when it
runs on that tier or above, logging who: main session (<model>); the deep-tier
seats (propose, second review) are always separate agents — their value is that
they are not you.
- Trivial / mechanical → auto-resolve (
model: "sonnet"): lockfiles (package-lock.json,yarn.lock,pnpm-lock.yaml,Cargo.lock,go.sum→ regenerate per git-procedure.md §Lockfiles, offline fallback included), import ordering, formatting/whitespace-only, append-only files (changelogs), both-sides-added non-overlapping code, generated files. - Semantic / logic → escalate (
model: "fable"proposes, user approves, the main session applies): the same function/body edited both sides, signature/API changes, one side deleted what the other modified, config/schema/migration conflicts, any overlapping logic. The agent explains both sides + a proposed resolution + why; the user approves or adjusts before it's applied. - Unsure → treat as semantic. Escalation is the safe default.
Second review. A separate Fable agent reviews the proposal for every semantic
hunk of an unattended run (nobody else checks an assumed:), and for any hunk
in migrations, schema, auth or payments on every run. Disagreement → the hunk takes
destination, its row is marked flagged:, the report lists it. Hunks of one file
run in sequence, different files in parallel (conflict-routing.md).
Resolve per hunk, not per file. A conflicted file is rarely wholly one side's;
--ours/--theirs on a whole file is the single most common way a real change
disappears with exit 0. Open the conflict with all three versions visible and decide
each hunk on its own:
git checkout --conflict=diff3 -- <path> # shows base|ours|theirs, not just two sides
git checkout --ours -- <path> # ONLY legitimate for lockfiles and generated files
diff3 markers matter: two-way markers show you what the sides say and hide what
they started from, so "both changed this line" and "one side changed it, the other
inherited it" look identical. With the base section visible, most hunks resolve
themselves.
For each conflicted hunk, decide and log one of:
| Take | When |
|---|---|
source |
The hunk is the feature. The destination's version is the old world. |
destination |
Base moved ahead here and the source is stale — its version predates base's change. |
both |
Non-overlapping additions in the same region: keep both, order deliberately. |
rewrite |
Neither side is right once combined — Fable proposes, user approves, the main session applies, and the log carries the proposed text. |
Ask the direction on any hunk where the two sides genuinely disagree about
behaviour — do not resolve it from the merge's overall direction. Merging a feature
into base does not mean the feature wins every hunk: a hunk where base fixed a bug
the source still carries must go to destination, or the merge reintroduces the bug.
Present both versions, say which way you'd go and why, and let the user pick.
Where every conflicted hunk of a file goes one way, let git write it rather than
editing markers — git merge-file over the index stages (1 = merge base, 2 =
destination, 3 = source) sends only the conflicting hunks to that side and keeps both
sides' clean hunks. git diff | git apply --3way cannot do this: a conflicted path
does not exist in index. Commands: git-procedure.md §Taking a side.
Record each resolution in the merge log — one row per hunk, not per file
(file · hunk/lines · class: trivial/semantic · why · take:
source/destination/both/rewrite · who classified / who decided · assumed:/flagged:). Phase 4's reconcile checks hunks; a log written at file granularity
cannot explain the failures it will find. If a merge goes sideways, git merge --abort, note it, and re-plan that step —
never leave the tree half-merged.
Phase 4 — Verify (ask at run time)
Reconcile on every merge commit, in both directions, before the next merge. Tests
prove the merge works; this proves it is complete. It is per hunk — a --name-only
diff lists a path base or another branch also moved either way, absolving a hunk that
vanished inside it. And it is per merge — checked at the end of a consolidate run, a
later branch legitimately editing what an earlier one added reads as a loss.
references/reconcile.sh enumerates every path with
--raw -M (renames under both paths, deletions, submodules compared by commit) and
checks each; nothing is sampled:
. <this skill>/references/reconcile.sh # defines: reconcile FROM TO
PRE=$(git rev-parse HEAD^1) # integration branch before this source
# 1. the source arrived — every hunk it changed:
reconcile "$(git merge-base "$PRE" <source>)" <source>
# 2. the destination is undisturbed — every hunk it gained since <source> first forked:
reconcile "$(git merge-base "$PRE" "$(git rev-list --first-parent <source> --not "$PRE" | tail -n 1)")" "$PRE"
Direction 2 follows the source's first parents to its original fork point: after a
mergeprep-oracle prep, merge-base <base> <source> is the base tip, the diff is
empty, and a base hunk the prep reverted passes unchecked. Because direction 2 also
covers every earlier source, a later merge that drops one is caught at that merge.
Log each FAIL line and the count line. A FAIL is legitimate only when a
merge-log row names that path and that hunk — direction 1: resolved toward the
destination, or take: renumbered (the logged ticket-ID map); direction 2: take: source; either: take: regenerated lockfile, or take: both (a union keeps both
sides, so neither side's patch reverse-applies verbatim — confirm by eye that both
sides' lines are in the file, and say so in the row); and always, this run's own
merge log (docs/merges/merge-*.md gains rows on every merge, so direction 2 FAILs
it by construction — skip it, never "fix" it) — or a
prep-document row shows it deliberately dropped or resolved toward the branch.
Anything else is a change that silently vanished: Fable diagnoses what dropped it,
Opus re-applies it and re-runs the reconcile, before going further. git status, a name-only diff and a green suite all report success here.
Then detect the project's build/test command. Ask whether to run verification (default yes if a test command is detected — a conflict-free merge is not a correct one). If yes, run it (Sonnet agent or main session). A failure is Opus's, not the runner's: a broken test after a merge is a real defect in the merged code, and Opus fixes it. Escalate back to Fable only when the fix means re-deciding a semantic resolution rather than repairing one — re-run, and update the log. Gate "done" on green.
Phase 5 — End state (ask at run time)
Relay a summary: what merged, conflicts resolved (trivial vs escalated counts), reconcile result — both directions: every source hunk present, every destination hunk present, each exception named in the log, verification result, integration branch name, merge-log path. Then ask:
- Hand off locally — leave the integration branch + log; the user pushes/PRs.
- Swap-in (local only) — rename the base aside and promote the merge into its
name, so the working branch name keeps meaning what it meant:
Those last two lines are not optional:git branch -m <base> <base>_old_before_<source> # e.g. dev -> dev_old_before_ksk_aewag2 git branch -m <integration> <base> # merged result becomes dev git branch --unset-upstream <base>_old_before_<source> git branch -u origin/<base> <base>git branch -mcarriesbranch.<name>.*config with the rename, so without them the archive tracksorigin/<base>(and underpush.default=upstreama habitualgit pushfrom it pushes the pre-merge state over origin's base) while the promoted branch tracks nothing. Note also that the promoted<base>has now diverged fromorigin/<base>— the nextpullwill merge origin's base back into the merged result, which is expected but worth saying out loud. Name the archived base<base>_old_before_<source>, not a bare<base>_old: months later the only question anyone asks of that branch is "old before what?" Strip any-merge-ready/-prepsuffix from<source>first (older preps made such branches; currentmergeprep-oraclepreps in place, so usually there is nothing to strip). If the name is already taken, append_2,_3— never overwrite an existing archive. End state: sources unchanged (f1is stillf1),dev= merged result,dev_old_before_ksk_aewag2= previous base. Only after verification is green, and only if<base>isn't checked out in another worktree (renaming the branch you are on is fine — HEAD follows it; a second worktree silently ends up on the archive): run thegit worktree list --porcelaincheck in git-procedure.md §Phase 5 and stop on any output. Local refs only. Never rename on the remote: that means deleting and re-pushing a branch, which breaks open PRs, branch protection, CI, and every other clone. To publish afterwards, push the renamed branch under a new remote name and PR it, or merge<base>_old_before_<source>..<base>normally — both need the explicit yes below. - The integration branch is never deleted by this skill: after a hand-off it is the
user's to delete once the PR merges; a swap-in makes it
<base>; a failed run keeps it as the audit trail (between-merges.md §The integration branch afterwards). - Push + open a draft PR — only on an explicit yes: push the integration branch
and open a draft PR via
gh(never merge it; never touch base; never force-push).
Pushing, opening a PR, or merging a PR are never done without that explicit approval.
Rules
- Base branch is sacred. Only ever a merge source; never checked out for
modification, never pushed to, never force-pushed. Phase 0's fast-forward to
origin/<base>adds nothing of ours; the one exception is the approved local swap-in rename in Phase 5 — which preserves the old base as<base>_old_before_<source>and still touches nothing on the remote. - Completeness is verified in both directions, not assumed. Before calling a merge done: every hunk each source intended is present, and every hunk the destination gained since the merge base is present. Each exception is named — path and hunk — in the merge log or the branch's prep document. Unexplained difference = lost change.
- Direction is asked, not inferred.
<source> INTO <destination>is confirmed before the first merge (nobody to ask → Phase 0's branch), and the overall direction never decides an individual hunk. - Conflicts resolve per hunk. Whole-file
--ours/--theirsis for lockfiles and generated files only; anywhere else it is a change discarded with exit 0. - Everything on the integration branch, everything in the merge log — the run is
auditable and 100% revertible by deleting the branch. Progress is on disk before
each merge (relay stage
~), so a dead session resumes rather than restarts. - Route conflicts by class, not by vibe. Opus classifies each hunk first;
trivial→Sonnet, semantic→Fable proposes (+ second Fable review when unattended or
sensitive) + approval + the main session applies, analysis→Sonnet, broken
verification→Opus, unexplained reconcile
FAIL→Fable diagnoses, Opus re-applies. Unsure = semantic. - Agents read and route; git merges. Don't hand-edit conflict markers when a
clean
gitresolution (regenerate lockfile,--theirs/--ourson a lockfile) is right. - Two run-time gates: verification and push/PR. Both ask; push/PR needs an explicit yes. Never claim a push/PR/merge that wasn't approved.
- If
ghis unavailable, do the whole merge with pure git and tell the user PR context/opening isn't available. - A subagent that dies, returns null or times out is retried once, then stops the run rather than merging blind (conflict-routing.md §Null and timeout).
- Kept in sync with
mergeprep-oracle— same source/destination vocabulary, samegit diff --binary -M ... | git apply --reverse --checkreconcile in both directions (one loop,references/reconcile.sh, sourced by both), same per-hunk granularity, same treatment of a non-zero exit as evidence. A change to any of those in either skill belongs in both.
Other hosts
Sonnet/Fable/Opus and the Agent tool above are the Claude Code defaults. On
Cursor, Codex, Antigravity, Pi, or Prime Agent, map through PLATFORMS.md (beside the
installed skills, or at the repo/plugin root): branch analysis → cheap tier,
conflict classification → build tier, trivial conflicts → cheap tier,
semantic conflicts decided (and second-reviewed, and reconcile failures diagnosed)
by the deep tier — the deep row of PLATFORMS.md §Role tiers, never a slug
copied here — then applied in the main session, with verification failures and
rework on the build tier. Where the host has only one top tier, it does both. No delegation available → resolve semantic
conflicts in-session and say so; never hand them to a cheaper agent. Where
the host can't run analysis agents in parallel, analyse branches sequentially and
write each summary to the merge log as you go — slower, same result. The approval
gates (verification, push/PR) do not relax on any host.