test_merge.py
python
sha256:f19d5e4a89766fc91b926cdf801255e12dcd968041c0ece8adf6627760788d22
merge: next build — MCP (#291 #292 #295 #324), profiles/sit…
Opus 5.5
minor
⚠ breaking
1 day ago
| 1 | """DOC_MRG — /muse/merge contract (musehub#249, QA contract v2). |
| 2 | |
| 3 | Every claim on the page was checked against muse 0.2.1rc20 (muse ``dev`` 5becda10) in disposable |
| 4 | sandboxes on 2026-11-07. These tests keep the corrected page honest in both directions: they run the |
| 5 | real ``muse merge`` and its neighbours in throwaway repositories (offline, a temporary HOME, no |
| 6 | identity, no remotes, no git) and compare the engine's behaviour with what the page says, so a change |
| 7 | to either side fails here. Known product defects stay documented as contract plus warning (#241 |
| 8 | defect-preservation rule): each is a strict xfail against its ticket, pinned to the behaviour the |
| 9 | contract wants, and the page's warning describes what the engine does today. The merge fixes of Muse batch 1 |
| 10 | (muse#192, #172, #174, #175, #176, #178) flipped their xfails; those tests now pin the fixed contract. |
| 11 | |
| 12 | * DOC_MRG_01/02/03 — CLI parse, labels, anchors: the shared checkers (``test_doc_inf_*``). |
| 13 | * DOC_MRG_04 — strategy semantics (the engine table) and the Git comparison's Muse column. |
| 14 | * DOC_MRG_05 — the routing figure: diff unit, resolution and Harmony column, executed. |
| 15 | * DOC_MRG_06 — history shapes, JSON shapes, exit codes, resolve flow. |
| 16 | * DOC_MRG_07 — proposal merge: the CLI/server contract and the flags the page says are not available. |
| 17 | * DOC_MRG_08 — formerly known defects, now fixed: the contracts, pinned. |
| 18 | |
| 19 | Rendering is the shared in-process fixture (no database). The Git column of the comparison table was |
| 20 | recorded once in a disposable repository (git 2.54.0); no test runs git. |
| 21 | """ |
| 22 | |
| 23 | from __future__ import annotations |
| 24 | |
| 25 | import argparse |
| 26 | import html as html_lib |
| 27 | import json |
| 28 | import os |
| 29 | import pathlib |
| 30 | import re |
| 31 | import shutil |
| 32 | import subprocess |
| 33 | import sys |
| 34 | from dataclasses import dataclass, field |
| 35 | |
| 36 | import pytest |
| 37 | |
| 38 | from tests.docs_contract import cli_check as cc |
| 39 | from tests.docs_contract import registry_check as rc |
| 40 | |
| 41 | PAGE = rc.phase_path("merge") |
| 42 | MUSE_ISSUES = "https://staging.musehub.ai/gabriel/muse/issues/" |
| 43 | HUB_ISSUES = "https://staging.musehub.ai/gabriel/musehub/issues/" |
| 44 | |
| 45 | # Product tickets the page's known-defect warnings link to (filed under #249, assigned to gabriel). |
| 46 | _T_PROPCLI = "172" # hub proposal merge --strategy squash|rebase sent as the content strategy |
| 47 | _T_INDEP = "173" # independence merge corrupts touching edits |
| 48 | _T_AUTOSHELF = "174" # --autoshelf on a fast-forward restores the pre-merge tree |
| 49 | _T_REBASE = "175" # --history rebase writes one squash-shaped commit |
| 50 | _T_RENAME = "178" # merge ignores renames |
| 51 | _T_LEASE = "180" # --force-with-lease is client-side only |
| 52 | _T_PROPSRV = "284" # musehub: unknown mergeStrategy was a 404 — fixed (422); the page records it |
| 53 | _T_DELBR = "285" # musehub: deleteBranch was never read — fixed; the page records it |
| 54 | _T_MERGECOMMIT = "192" # resolve + commit omits the merged branch's non-conflicting changes |
| 55 | # Fixed tickets stay linked where the page records the history of a row (as for muse#173); muse#176 is no longer linked. |
| 56 | _MUSE_LINKS = {_T_MERGECOMMIT, _T_PROPCLI, _T_INDEP, _T_AUTOSHELF, _T_REBASE, _T_RENAME, _T_LEASE, "33"} |
| 57 | _HUB_LINKS = {_T_PROPSRV, _T_DELBR, "66", "67", "182"} |
| 58 | |
| 59 | _ENVELOPE = {"muse_version", "schema", "exit_code", "duration_ms", "timestamp", "warnings"} |
| 60 | _MERGE_KEYS = {"status", "commit_id", "branch", "current_branch", "base_commit_id", "conflicts", "files_changed", |
| 61 | "semver_impact", "strategy", "on_conflict", "history", "dry_run", "merge_result"} |
| 62 | _MERGE_RESULT_KEYS = {"status", "commit_id", "strategy", "on_conflict", "history", "conflicts", "files_changed", "semver_impact"} |
| 63 | _ROUTING_KEYS = {"requested_strategy", "on_conflict", "history", "resolved_diff_unit", "resolved_resolution", "case"} |
| 64 | _PER_PATH_KEYS = {"path", "ours_changed", "theirs_changed", "ours_id", "theirs_id", "base_id", "decision", "reason", |
| 65 | "harmony_checked", "harmony_result", "harmony_pattern_id", "attributes_rule", "independence_merge_attempted"} |
| 66 | _SUMMARY_KEYS = {"total_paths", "clean_no_change", "take_ours_only", "take_theirs_only", "convergent", "harmony_auto_resolved", |
| 67 | "attributes_auto_resolved", "independence_merged", "conflicts"} |
| 68 | _CONFLICTS_KEYS = {"merge_in_progress", "merge_from", "ours_commit", "theirs_commit", "base_commit", "conflict_count", |
| 69 | "total_conflict_count", "resolved_count", "conflicts", "resolved_conflicts", "next_steps"} |
| 70 | |
| 71 | XFAIL = dict(strict=True, raises=AssertionError) |
| 72 | |
| 73 | |
| 74 | @pytest.fixture(scope="module") |
| 75 | def html(rendered: dict[str, str]) -> str: |
| 76 | return rendered[PAGE].replace("'", "'").replace(""", '"').replace(""", '"') |
| 77 | |
| 78 | |
| 79 | def _text(fragment: str) -> str: |
| 80 | return html_lib.unescape(re.sub(r"<[^>]+>", "", fragment)) |
| 81 | |
| 82 | |
| 83 | def _section(html: str, anchor: str) -> str: |
| 84 | rest = html.split(f'id="{anchor}"', 1)[1] |
| 85 | return " ".join(rest.split("</section>", 1)[0].split()) |
| 86 | |
| 87 | |
| 88 | def _rows(html: str, table_id: str) -> list[dict[str, str]]: |
| 89 | """Attributes of every <tr data-…> in the table with this id.""" |
| 90 | table = html.split(f'id="{table_id}"', 1)[1].split("</table>", 1)[0] |
| 91 | return [dict(re.findall(r'data-([a-z-]+)="([^"]*)"', m)) for m in re.findall(r"<tr [^>]*data-[^>]*>", table)] |
| 92 | |
| 93 | |
| 94 | # ── Engine harness: the real CLI in throwaway repositories ───────────────── |
| 95 | |
| 96 | |
| 97 | @dataclass |
| 98 | class R: |
| 99 | rc: int |
| 100 | out: str |
| 101 | err: str |
| 102 | json: dict = field(default_factory=dict) |
| 103 | |
| 104 | |
| 105 | class Sandbox: |
| 106 | def __init__(self, root: pathlib.Path) -> None: |
| 107 | self.root = root |
| 108 | self.home = root / "home" |
| 109 | self.home.mkdir(parents=True) |
| 110 | env = {k: v for k, v in os.environ.items() if not k.startswith(("MUSE_", "GIT_"))} |
| 111 | env.update(HOME=str(self.home), XDG_CONFIG_HOME=str(self.home / ".config"), MUSE_KEYCHAIN_BACKEND="disabled", |
| 112 | PYTHON_KEYRING_BACKEND="keyring.backends.fail.Keyring", NO_COLOR="1", |
| 113 | PYTHONPATH=os.pathsep.join(p for p in sys.path if p)) |
| 114 | self.env = env |
| 115 | self.n = 0 |
| 116 | |
| 117 | def run(self, repo: pathlib.Path, *args: str, ok: bool = True) -> R: |
| 118 | assert str(repo.resolve()).startswith(str(self.root.resolve())), repo |
| 119 | p = subprocess.run([sys.executable, "-c", "import sys; from muse.cli.app import main; main(sys.argv[1:])", *args], |
| 120 | cwd=repo, env=self.env, capture_output=True, text=True, timeout=120) |
| 121 | if ok: |
| 122 | assert p.returncode == 0, (args, p.stdout, p.stderr) |
| 123 | try: |
| 124 | out = json.loads(p.stdout) |
| 125 | except ValueError: |
| 126 | out = {} |
| 127 | return R(p.returncode, p.stdout, p.stderr, out if isinstance(out, dict) else {}) |
| 128 | |
| 129 | @staticmethod |
| 130 | def write(repo: pathlib.Path, files: dict[str, str | None]) -> None: |
| 131 | for rel, text in files.items(): |
| 132 | path = repo / rel |
| 133 | if text is None: |
| 134 | path.unlink() |
| 135 | else: |
| 136 | path.parent.mkdir(parents=True, exist_ok=True) |
| 137 | path.write_text(text) |
| 138 | |
| 139 | def commit(self, repo: pathlib.Path, files: dict[str, str | None], msg: str) -> None: |
| 140 | self.write(repo, files) |
| 141 | self.run(repo, "code", "add", ".") |
| 142 | self.run(repo, "commit", "-m", msg) |
| 143 | |
| 144 | def build(self, base: dict, feat: dict | list[dict], dev: dict | None) -> pathlib.Path: |
| 145 | """A code-domain repo on ``dev`` with ``feat`` branched from the base; ``dev`` has its own commit.""" |
| 146 | self.n += 1 |
| 147 | repo = self.root / "repos" / f"r{self.n}" |
| 148 | repo.mkdir(parents=True) |
| 149 | self.run(repo, "init", "--domain", "code", "--default-branch", "dev") |
| 150 | for remote in self.run(repo, "remote").out.split(): |
| 151 | self.run(repo, "remote", "remove", remote) |
| 152 | assert "No remotes" in self.run(repo, "remote", "-v").out + self.run(repo, "remote", "-v").err |
| 153 | self.commit(repo, base, "base") |
| 154 | self.run(repo, "checkout", "-b", "feat") |
| 155 | for i, step in enumerate(feat if isinstance(feat, list) else [feat], 1): |
| 156 | self.commit(repo, step, f"feat {i}") |
| 157 | self.run(repo, "checkout", "dev") |
| 158 | if dev is not None: |
| 159 | self.commit(repo, dev, "dev") |
| 160 | return repo |
| 161 | |
| 162 | def copy(self, repo: pathlib.Path) -> pathlib.Path: |
| 163 | self.n += 1 |
| 164 | dest = self.root / "copies" / f"c{self.n}" |
| 165 | shutil.copytree(repo, dest, symlinks=True) |
| 166 | return dest |
| 167 | |
| 168 | def merge(self, repo: pathlib.Path, *flags: str, branch: str = "feat") -> R: |
| 169 | """Merge in a private copy, so every variant starts from the same state.""" |
| 170 | return self.run(self.copy(repo), "merge", branch, *flags, "--json", ok=False) |
| 171 | |
| 172 | |
| 173 | @pytest.fixture(scope="module") |
| 174 | def sb(tmp_path_factory: pytest.TempPathFactory) -> Sandbox: |
| 175 | return Sandbox(tmp_path_factory.mktemp("merge-engine")) |
| 176 | |
| 177 | |
| 178 | def _read(repo: pathlib.Path, rel: str) -> str: |
| 179 | return (repo / rel).read_text() |
| 180 | |
| 181 | |
| 182 | def _merged(sb: Sandbox, repo: pathlib.Path, *flags: str) -> tuple[R, pathlib.Path]: |
| 183 | work = sb.copy(repo) |
| 184 | return sb.run(work, "merge", "feat", *flags, "--json", ok=False), work |
| 185 | |
| 186 | |
| 187 | # ── Fixture: one conflict, plus a file only each side changed ─────────────── |
| 188 | |
| 189 | _A_BASE = "def a():\n return 'base'\n\n\ndef b():\n return 'base'\n" |
| 190 | _A_DEV = "def a():\n return 'dev'\n\n\ndef b():\n return 'base'\n" |
| 191 | _A_FEAT = "def a():\n return 'feat'\n\n\ndef b():\n return 'feat-b'\n" |
| 192 | _A_RESOLVED = "def a():\n return 'resolved'\n\n\ndef b():\n return 'feat-b'\n" |
| 193 | _SAME_BASE = {"a.py": _A_BASE, "p.txt": "p0\n", "q.txt": "q0\n"} |
| 194 | _SAME_FEAT = {"a.py": _A_FEAT, "q.txt": "q1\n"} |
| 195 | _SAME_DEV = {"a.py": _A_DEV, "p.txt": "p1\n"} |
| 196 | |
| 197 | |
| 198 | @pytest.fixture(scope="module") |
| 199 | def same(sb: Sandbox) -> pathlib.Path: |
| 200 | return sb.build(_SAME_BASE, _SAME_FEAT, _SAME_DEV) |
| 201 | |
| 202 | |
| 203 | # ── DOC_MRG_04: the engine table, executed ────────────────────────────────── |
| 204 | |
| 205 | |
| 206 | class TestStrategies: |
| 207 | def test_recursive_conflicts_on_the_symbol_only(self, sb: Sandbox, same: pathlib.Path) -> None: |
| 208 | r, work = _merged(sb, same) |
| 209 | assert r.rc == 1 and r.json["status"] == "conflict" |
| 210 | assert r.json["conflicts"] == ["a.py::a"] |
| 211 | text = _read(work, "a.py") |
| 212 | assert "<<<<<<< dev [modified]" in text and "||||||| base" in text and "======= feat [modified]" in text |
| 213 | assert text.rstrip().count(">>>>>>> end conflict") == 1 |
| 214 | # markers wrap only the conflicting body lines: b() merged normally (theirs' edit), file stays parseable around them |
| 215 | assert "return 'feat-b'" in text and text.index("def b()") > text.index(">>>>>>> end conflict") |
| 216 | assert (_read(work, "p.txt"), _read(work, "q.txt")) == ("p1\n", "q1\n") # one-sided files from both sides |
| 217 | assert (work / ".muse" / "MERGE_STATE.json").exists() |
| 218 | |
| 219 | def test_snapshot_matches_recursive_in_the_code_domain(self, sb: Sandbox, same: pathlib.Path) -> None: |
| 220 | r, _ = _merged(sb, same, "--strategy", "snapshot") |
| 221 | assert r.rc == 1 and r.json["conflicts"] == ["a.py::a"] |
| 222 | |
| 223 | def test_replay_conflicts_on_the_whole_file(self, sb: Sandbox, same: pathlib.Path) -> None: |
| 224 | r, _ = _merged(sb, same, "--strategy", "replay") |
| 225 | assert r.rc == 1 and r.json["conflicts"] == ["a.py"] |
| 226 | |
| 227 | def test_overlay_takes_theirs_whole_file_and_keeps_one_sided_files(self, sb: Sandbox, same: pathlib.Path) -> None: |
| 228 | r, work = _merged(sb, same, "--strategy", "overlay") |
| 229 | assert r.rc == 0 and r.json["conflicts"] == [] |
| 230 | assert _read(work, "a.py") == _A_FEAT |
| 231 | assert (_read(work, "p.txt"), _read(work, "q.txt")) == ("p1\n", "q1\n") |
| 232 | assert not (work / ".muse" / "MERGE_STATE.json").exists() |
| 233 | |
| 234 | def test_ours_and_theirs_take_the_conflicting_file_whole(self, sb: Sandbox, same: pathlib.Path) -> None: |
| 235 | r, work = _merged(sb, same, "--strategy", "ours") |
| 236 | assert r.rc == 0 and _read(work, "a.py") == _A_DEV # theirs' non-conflicting b() edit is dropped with the file |
| 237 | assert (_read(work, "p.txt"), _read(work, "q.txt")) == ("p1\n", "q1\n") # non-conflicting paths merge normally |
| 238 | r, work = _merged(sb, same, "--strategy", "theirs") |
| 239 | assert r.rc == 0 and _read(work, "a.py") == _A_FEAT |
| 240 | assert (_read(work, "p.txt"), _read(work, "q.txt")) == ("p1\n", "q1\n") |
| 241 | |
| 242 | @pytest.mark.parametrize("side", ["ours", "theirs"]) |
| 243 | def test_on_conflict_is_the_alias_the_page_says(self, sb: Sandbox, same: pathlib.Path, side: str) -> None: |
| 244 | r1, w1 = _merged(sb, same, "--on-conflict", side) |
| 245 | r2, w2 = _merged(sb, same, "--strategy", side) |
| 246 | assert r1.rc == r2.rc == 0 |
| 247 | assert {p: _read(w1, p) for p in ("a.py", "p.txt", "q.txt")} == {p: _read(w2, p) for p in ("a.py", "p.txt", "q.txt")} |
| 248 | assert not (w1 / ".muse" / "MERGE_STATE.json").exists() |
| 249 | |
| 250 | def test_the_engine_table_on_the_page_is_the_engine(self, html: str) -> None: |
| 251 | from muse.core.merge_engine import STRATEGY_MAP |
| 252 | |
| 253 | rows = _rows(html, "merge-route-table") |
| 254 | assert {r["strategy"] for r in rows} == set(STRATEGY_MAP) |
| 255 | for row in rows: |
| 256 | engine = STRATEGY_MAP[row["strategy"]] |
| 257 | assert (row["diff-unit"], row["resolution"]) == (engine.diff_unit, engine.resolution), row |
| 258 | # the strategy table in the Engine model section names the same pair in its 2nd and 3rd cells |
| 259 | table = _section(html, "engine-model").split("<tbody>", 1)[1] |
| 260 | for key, engine in STRATEGY_MAP.items(): |
| 261 | cells = re.search(rf'<tr data-strategy="{key}">(.*?)</tr>', table).group(1) |
| 262 | codes = re.findall(r"<code>([a-z_]+)</code>", cells) |
| 263 | assert engine.diff_unit in codes and engine.resolution in codes, (key, codes) |
| 264 | |
| 265 | |
| 266 | # ── DOC_MRG_04: the Git comparison table (Muse column re-run) ─────────────── |
| 267 | |
| 268 | _BASE_PY = "def alpha(x):\n total = x + 1\n return total\n\n\ndef beta(y):\n value = y * 2\n return value\n" |
| 269 | _F = "def f(a):\n one = a + {}\n mid = 0\n other = 0\n two = a + {}\n return one + two\n" |
| 270 | |
| 271 | # case -> (base, dev, feat, ideal merged m.py or None when a conflict is the right answer) |
| 272 | _CASES = { |
| 273 | "S1": ({"m.py": _BASE_PY + "\n\ndef gamma(z):\n return z\n"}, |
| 274 | {"m.py": (_BASE_PY + "\n\ndef gamma(z):\n return z\n").replace("total = x + 1", "total = x + 100")}, |
| 275 | {"m.py": (_BASE_PY + "\n\ndef gamma(z):\n return z\n").replace("return z", "return z * 3")}, |
| 276 | (_BASE_PY + "\n\ndef gamma(z):\n return z\n").replace("total = x + 1", "total = x + 100").replace("return z", "return z * 3")), |
| 277 | "S2": ({"m.py": _BASE_PY}, {"m.py": _BASE_PY.replace("x + 1", "x + 10")}, {"m.py": _BASE_PY.replace("x + 1", "x + 20")}, None), |
| 278 | "S3": ({"m.py": _BASE_PY}, {"m.py": _BASE_PY + "\n\ndef from_dev():\n return 'dev'\n"}, |
| 279 | {"m.py": _BASE_PY + "\n\ndef from_feat():\n return 'feat'\n"}, |
| 280 | _BASE_PY + "\n\ndef from_dev():\n return 'dev'\n\n\ndef from_feat():\n return 'feat'\n"), |
| 281 | "S4": ({"m.py": _F.format(1, 2)}, {"m.py": _F.format(100, 2)}, {"m.py": _F.format(1, 200)}, None), |
| 282 | "S5": ({"m.py": "x = 1; y = 2\n"}, {"m.py": "x = 10; y = 2\n"}, {"m.py": "x = 1; y = 20\n"}, "x = 10; y = 20\n"), |
| 283 | "S6": ({"util.py": _BASE_PY}, {"util.py": _BASE_PY.replace("x + 1", "x + 10")}, {"helpers.py": _BASE_PY, "util.py": None}, |
| 284 | _BASE_PY.replace("x + 1", "x + 10")), # Muse follows the pure rename like Git (muse#178, fixed) |
| 285 | "S7": ({"m.py": "def a():\n return 1\ndef b():\n return 2\n"}, {"m.py": "def a():\n return 10\ndef b():\n return 2\n"}, |
| 286 | {"m.py": "def a():\n return 1\ndef b(k=0):\n return 2\n"}, "def a():\n return 10\ndef b(k=0):\n return 2\n"), |
| 287 | "S8": ({"m.py": "def f(): return 1\ndef g(): return 2\n"}, {"m.py": "def f(): return 10\ndef g(): return 2\n"}, |
| 288 | {"m.py": "def f(): return 1\ndef g(): return 20\n"}, "def f(): return 10\ndef g(): return 20\n"), |
| 289 | } |
| 290 | _CORRECT = {"S1", "S2", "S3", "S4", "S5", "S6", "S7", "S8"} |
| 291 | |
| 292 | |
| 293 | @pytest.fixture(scope="module") |
| 294 | def compare(sb: Sandbox) -> dict[str, tuple[str, str]]: |
| 295 | """case -> (muse outcome label, merged file text): clean | conflict | wrong.""" |
| 296 | out: dict[str, tuple[str, str]] = {} |
| 297 | for case, (base, dev, feat, ideal) in _CASES.items(): |
| 298 | repo = sb.build(base, feat, dev) |
| 299 | r = sb.run(repo, "merge", "feat", "--json", ok=False) |
| 300 | target = "m.py" if "m.py" in base else "helpers.py" |
| 301 | text = _read(repo, target) if (repo / target).exists() else "" |
| 302 | if r.rc != 0: |
| 303 | label = "conflict" |
| 304 | else: |
| 305 | label = "clean" if text == ideal else "wrong" |
| 306 | out[case] = (label, text) |
| 307 | return out |
| 308 | |
| 309 | |
| 310 | class TestGitComparison: |
| 311 | def test_every_documented_muse_outcome_is_what_the_engine_does(self, html: str, compare: dict) -> None: |
| 312 | table = html.split("Git and Muse on identical files", 1)[1].split("</table>", 1)[0] |
| 313 | shown = {m[0]: m[1] for m in re.findall(r'<tr data-case="(S\d)" data-muse="([a-z]+)"', table)} |
| 314 | assert set(shown) == set(_CASES) |
| 315 | assert shown == {case: label for case, (label, _) in compare.items()}, {c: (shown[c], compare[c][0]) for c in shown} |
| 316 | |
| 317 | def test_git_column_is_recorded_for_every_case(self, html: str) -> None: |
| 318 | table = html.split("Git and Muse on identical files", 1)[1].split("</table>", 1)[0] |
| 319 | git = re.findall(r'<tr data-case="(S\d)"[^>]*>.*?<td>(clean|conflict)</td>\s*<td>', table, flags=re.S) |
| 320 | assert [c for c, _ in git] == sorted(_CASES) |
| 321 | assert dict(git) == {"S1": "clean", "S2": "conflict", "S3": "conflict", "S4": "clean", "S5": "conflict", "S6": "clean", |
| 322 | "S7": "conflict", "S8": "conflict"} |
| 323 | |
| 324 | def test_no_row_is_clean_but_wrong_and_the_fixed_defect_is_linked(self, html: str, compare: dict) -> None: |
| 325 | # muse#173 (independence merge wrote a wrong file for touching edits) is fixed: S5, S7 and S8 conflict |
| 326 | # like Git. The page still links the issue so the history of those rows is traceable. |
| 327 | assert {c for c, (label, _) in compare.items() if label == "wrong"} == set() |
| 328 | assert {c: compare[c][0] for c in ("S5", "S7", "S8")} == {"S5": "conflict", "S7": "conflict", "S8": "conflict"} |
| 329 | assert f"{MUSE_ISSUES}{_T_INDEP}" in html.split("Git and Muse on identical files", 1)[1] |
| 330 | |
| 331 | |
| 332 | # ── DOC_MRG_05: the routing figure, executed ──────────────────────────────── |
| 333 | |
| 334 | |
| 335 | @pytest.fixture(scope="module") |
| 336 | def learned(sb: Sandbox, same: pathlib.Path) -> pathlib.Path: |
| 337 | """The ``same`` repo after a conflict was resolved and committed, plus a fresh branch pair that recreates it.""" |
| 338 | repo = sb.copy(same) |
| 339 | base = sb.run(repo, "merge-base", "dev", "feat", "--json").json["merge_base"] |
| 340 | assert sb.run(repo, "merge", "feat", "--json", ok=False).rc == 1 |
| 341 | sb.write(repo, {"a.py": _A_RESOLVED}) |
| 342 | sb.run(repo, "resolve", "--all", "--json") |
| 343 | sb.run(repo, "code", "add", ".") # the documented interim step (muse#192) |
| 344 | sb.run(repo, "commit", "-m", "merge: resolve a") |
| 345 | # the identical conflict again: the same base, ours and theirs content for a.py |
| 346 | sb.run(repo, "branch", "ours2", base) |
| 347 | sb.run(repo, "checkout", "ours2") |
| 348 | sb.commit(repo, {"a.py": _A_DEV}, "ours2") |
| 349 | sb.run(repo, "branch", "theirs2", base) |
| 350 | sb.run(repo, "checkout", "theirs2") |
| 351 | sb.commit(repo, {"a.py": _A_FEAT}, "theirs2") |
| 352 | sb.run(repo, "checkout", "ours2") |
| 353 | return repo |
| 354 | |
| 355 | |
| 356 | class TestRouting: |
| 357 | @pytest.mark.parametrize("key", ["recursive", "overlay", "snapshot", "replay", "ours", "theirs"]) |
| 358 | def test_dry_run_explain_reports_the_figure_row(self, sb: Sandbox, same: pathlib.Path, html: str, key: str) -> None: |
| 359 | row = next(r for r in _rows(html, "merge-route-table") if r["strategy"] == key) |
| 360 | r, _ = _merged(sb, same, "--strategy", key, "--dry-run", "--explain") |
| 361 | routing = r.json["explain"]["strategy_routing"] |
| 362 | assert (routing["resolved_diff_unit"], routing["resolved_resolution"]) == (row["diff-unit"], row["resolution"]) |
| 363 | assert set(routing) == _ROUTING_KEYS |
| 364 | |
| 365 | def test_harmony_column_is_what_a_replayed_resolution_does(self, sb: Sandbox, learned: pathlib.Path, html: str) -> None: |
| 366 | def outcome(*flags: str) -> tuple[int, str]: |
| 367 | work = sb.copy(learned) |
| 368 | r = sb.run(work, "merge", "theirs2", *flags, "--json", ok=False) |
| 369 | return r.rc, _read(work, "a.py") if r.rc == 0 else "" |
| 370 | |
| 371 | # default: Harmony replays the saved resolution |
| 372 | rc_, text = outcome() |
| 373 | assert (rc_, text) == (0, _A_RESOLVED) |
| 374 | explain = sb.run(sb.copy(learned), "merge", "theirs2", "--explain", "--json").json["explain"] |
| 375 | entry = next(e for e in explain["per_path"] if e["path"] == "a.py") |
| 376 | assert entry["decision"] == "harmony_auto_resolved" and entry["harmony_checked"] is True |
| 377 | # the page's table: consulted = yes <=> the saved resolution is what you get (or a conflict Harmony could not match) |
| 378 | rows = {r["strategy"]: r for r in _rows(html, "merge-route-table")} |
| 379 | assert outcome("--strategy", "snapshot") == (0, _A_RESOLVED) and rows["snapshot"]["harmony"] == "yes" |
| 380 | assert outcome("--strategy", "replay")[0] == 1 and rows["replay"]["harmony"] == "yes" # checked, cannot match a whole-file conflict |
| 381 | for key, expected in (("overlay", _A_FEAT), ("ours", _A_DEV), ("theirs", _A_FEAT)): |
| 382 | assert outcome("--strategy", key) == (0, expected) and rows[key]["harmony"] == "no", key |
| 383 | assert outcome("--on-conflict", "ours") == (0, _A_DEV) |
| 384 | assert outcome("--on-conflict", "theirs") == (0, _A_FEAT) |
| 385 | # the flags the page lists as skipping Harmony |
| 386 | assert outcome("--no-harmony-autoupdate")[0] == 1 |
| 387 | r = sb.merge(learned, "--dry-run", branch="theirs2") |
| 388 | assert r.rc == 1 and r.json["status"] == "conflict" |
| 389 | |
| 390 | def test_the_replayed_resolution_needs_an_identical_conflict(self, sb: Sandbox, learned: pathlib.Path) -> None: |
| 391 | # the page: "an unrelated change elsewhere in the file can stop it matching" |
| 392 | work = sb.copy(learned) |
| 393 | sb.run(work, "checkout", "theirs2") |
| 394 | sb.commit(work, {"a.py": _A_FEAT + "\n\ndef extra():\n return 1\n"}, "theirs2 plus an unrelated function") |
| 395 | sb.run(work, "checkout", "ours2") |
| 396 | r = sb.run(work, "merge", "theirs2", "--json", ok=False) |
| 397 | assert r.rc == 1 and r.json["status"] == "conflict" |
| 398 | |
| 399 | def test_route_table_has_the_five_steps_and_three_resolving_rows(self, html: str) -> None: |
| 400 | figure = html.split('id="merge-routing-figure"', 1)[1].split("</figure>", 1)[0] |
| 401 | assert figure.count('class="mrgfig__step"') == 5 |
| 402 | rows = _rows(html, "merge-route-table") |
| 403 | assert [r["harmony"] for r in rows] == ["yes", "yes", "yes", "no", "no", "no"] |
| 404 | assert "<figcaption" in html.split('id="merge-routing-figure"', 1)[1] |
| 405 | assert 'aria-labelledby="merge-routing-figure-title"' in html |
| 406 | |
| 407 | |
| 408 | # ── DOC_MRG_06: history shapes, JSON shapes, exit codes, the resolve flow ── |
| 409 | |
| 410 | |
| 411 | @pytest.fixture(scope="module") |
| 412 | def three(sb: Sandbox) -> pathlib.Path: |
| 413 | base = {"m.py": "def a():\n return 1\n\n\ndef b():\n return 2\n\n\ndef c():\n return 3\n", "p.txt": "p0\n"} |
| 414 | steps = [{"m.py": base["m.py"].replace("return 1", "return 10")}, |
| 415 | {"m.py": base["m.py"].replace("return 1", "return 10").replace("return 2", "return 20")}, |
| 416 | {"m.py": base["m.py"].replace("return 1", "return 10").replace("return 2", "return 20").replace("return 3", "return 30")}] |
| 417 | return sb.build(base, steps, {"p.txt": "p1\n"}) |
| 418 | |
| 419 | |
| 420 | def _new_commits(sb: Sandbox, repo: pathlib.Path, before: str) -> list[str]: |
| 421 | return sb.run(repo, "rev-list", f"{before}..HEAD", "--json").json["commit_ids"] |
| 422 | |
| 423 | |
| 424 | class TestHistory: |
| 425 | def _after(self, sb: Sandbox, three: pathlib.Path, mode: str) -> tuple[pathlib.Path, str, dict]: |
| 426 | work = sb.copy(three) |
| 427 | before = sb.run(work, "read", "HEAD", "--json").json["commit_id"] |
| 428 | assert sb.run(work, "merge", "feat", "--history", mode, "--json").rc == 0 |
| 429 | return work, before, sb.run(work, "read", "HEAD", "--json").json |
| 430 | |
| 431 | def test_merge_makes_one_two_parent_commit(self, sb: Sandbox, three: pathlib.Path) -> None: |
| 432 | _, before, head = self._after(sb, three, "merge") |
| 433 | assert head["parent_commit_id"] == before and head["parent2_commit_id"] |
| 434 | |
| 435 | def test_squash_makes_one_single_parent_commit(self, sb: Sandbox, three: pathlib.Path) -> None: |
| 436 | work, before, head = self._after(sb, three, "squash") |
| 437 | assert head["parent_commit_id"] == before and not head.get("parent2_commit_id") |
| 438 | assert _new_commits(sb, work, before) == [head["commit_id"]] |
| 439 | assert head["message"].startswith("Squash merge branch 'feat'") |
| 440 | |
| 441 | def test_rebase_replays_each_commit_and_keeps_its_authorship(self, sb: Sandbox, three: pathlib.Path) -> None: |
| 442 | work, before, head = self._after(sb, three, "rebase") |
| 443 | new = _new_commits(sb, work, before) |
| 444 | assert len(new) == 3 and head["commit_id"] in new |
| 445 | originals = {c["message"]: c for c in sb.run(three, "log", "dev..feat", "--json").json["commits"]} |
| 446 | chain, parent = [], before |
| 447 | for cid in reversed(new): # rev-list is newest first |
| 448 | rec = sb.run(work, "read", cid, "--json").json |
| 449 | assert rec["parent_commit_id"] == parent and not rec.get("parent2_commit_id") # linear, one parent each |
| 450 | orig = sb.run(three, "read", originals[rec["message"]]["commit_id"], "--json").json # same message |
| 451 | assert rec["metadata"]["replayed_from"] == orig["commit_id"] |
| 452 | assert (rec["author"], rec["agent_id"], rec["model_id"]) == (orig["author"], orig["agent_id"], orig["model_id"]) |
| 453 | chain.append(rec["message"]) |
| 454 | parent = cid |
| 455 | assert chain == ["feat 1", "feat 2", "feat 3"] |
| 456 | |
| 457 | def test_rebase_keeps_each_replayed_commits_agent_and_model(self, sb: Sandbox) -> None: |
| 458 | repo = sb.build({"m.py": "a = 1\nb = 2\n"}, [], {"p.txt": "p1\n"}) |
| 459 | sb.run(repo, "checkout", "feat") |
| 460 | for i, (agent, model) in enumerate((("agent-a", "model-a"), ("agent-b", "model-b")), 1): |
| 461 | sb.write(repo, {"m.py": f"a = {10 * i}\nb = 2\n"}) |
| 462 | sb.run(repo, "code", "add", ".") |
| 463 | sb.run(repo, "commit", "-m", f"step {i}", "--agent-id", agent, "--model-id", model) |
| 464 | sb.run(repo, "checkout", "dev") |
| 465 | before = sb.run(repo, "read", "HEAD", "--json").json["commit_id"] |
| 466 | sb.run(repo, "merge", "feat", "--history", "rebase", "--json") |
| 467 | replayed = [sb.run(repo, "read", c, "--json").json for c in reversed(_new_commits(sb, repo, before))] |
| 468 | assert [(r["message"], r["agent_id"], r["model_id"]) for r in replayed] == [ |
| 469 | ("step 1", "agent-a", "model-a"), ("step 2", "agent-b", "model-b")] |
| 470 | |
| 471 | def test_the_trees_agree_across_modes(self, sb: Sandbox, three: pathlib.Path) -> None: |
| 472 | trees = [] |
| 473 | for mode in ("merge", "squash", "rebase"): |
| 474 | work, _, _ = self._after(sb, three, mode) |
| 475 | trees.append((_read(work, "m.py"), _read(work, "p.txt"))) |
| 476 | assert trees[0] == trees[1] == trees[2] |
| 477 | |
| 478 | def test_the_history_table_names_what_was_measured(self, html: str) -> None: |
| 479 | rows = _rows(html, "history-table") |
| 480 | assert [r["history"] for r in rows] == ["merge", "squash", "rebase"] |
| 481 | assert "muse#175" in _text(_section(html, "history")) or f"{MUSE_ISSUES}{_T_REBASE}" in html |
| 482 | |
| 483 | |
| 484 | @pytest.fixture(scope="module") |
| 485 | def clean(sb: Sandbox) -> pathlib.Path: |
| 486 | return sb.build({"src/auth/tokens.py": "def validate_token(t):\n return bool(t)\n\n\ndef refresh_token(t):\n return t + '-1'\n", "pyproject.toml": '[project]\nversion = "1.0.0"\n'}, |
| 487 | {"src/auth/tokens.py": "def validate_token(t):\n return bool(t)\n\n\ndef refresh_token(t):\n return t + '-2'\n"}, |
| 488 | {"src/auth/tokens.py": "def validate_token(t):\n return bool(t) and len(t) > 8\n\n\ndef refresh_token(t):\n return t + '-1'\n"}) |
| 489 | |
| 490 | |
| 491 | @pytest.fixture(scope="module") |
| 492 | def conflicted(sb: Sandbox) -> pathlib.Path: |
| 493 | tok = "def validate_token(t):\n return bool(t)\n\n\ndef refresh_token(t):\n return t + '-1'\n" |
| 494 | pyp = '[project]\nname = "demo"\nversion = "1.0.0"\n' |
| 495 | return sb.build({"src/auth/tokens.py": tok, "pyproject.toml": pyp}, |
| 496 | {"src/auth/tokens.py": tok.replace("bool(t)", "t is not None"), "pyproject.toml": pyp.replace("1.0.0", "2.0.0")}, |
| 497 | {"src/auth/tokens.py": tok.replace("bool(t)", "bool(t) and len(t) > 8"), "pyproject.toml": pyp.replace("1.0.0", "1.1.0")}) |
| 498 | |
| 499 | |
| 500 | class TestShapes: |
| 501 | def test_clean_and_dry_run_envelope(self, sb: Sandbox, clean: pathlib.Path) -> None: |
| 502 | for flags, dry in (((), False), (("--dry-run",), True)): |
| 503 | r = sb.merge(clean, *flags) |
| 504 | assert r.rc == 0 and set(r.json) == _ENVELOPE | _MERGE_KEYS, set(r.json) ^ (_ENVELOPE | _MERGE_KEYS) |
| 505 | assert r.json["status"] == "merged" and r.json["dry_run"] is dry and r.json["conflicts"] == [] |
| 506 | assert set(r.json["merge_result"]) == _MERGE_RESULT_KEYS |
| 507 | assert set(r.json["files_changed"]) == {"added", "modified", "deleted"} |
| 508 | assert not {"merge_type", "fast_forward", "files_added", "commits_to_merge", "auto_resolved"} & set(r.json) |
| 509 | assert (r.json["commit_id"] is None) is True # a dry-run writes no commit |
| 510 | |
| 511 | def test_fast_forward_has_the_same_keys(self, sb: Sandbox) -> None: |
| 512 | repo = sb.build({"m.py": "x = 1\n"}, {"m.py": "x = 2\n", "n.py": "y = 1\n"}, None) |
| 513 | r = sb.merge(repo, "--dry-run") |
| 514 | assert r.rc == 0 and r.json["status"] == "fast_forward" and set(r.json) == _ENVELOPE | _MERGE_KEYS |
| 515 | |
| 516 | def test_conflict_envelope_and_conflicts_command(self, sb: Sandbox, conflicted: pathlib.Path) -> None: |
| 517 | work = sb.copy(conflicted) |
| 518 | r = sb.run(work, "merge", "feat", "--json", ok=False) |
| 519 | assert r.rc == 1 and r.json["status"] == "conflict" |
| 520 | assert set(r.json) == _ENVELOPE | _MERGE_KEYS | {"conflict_records", "symbol_conflicts"} |
| 521 | assert r.json["conflict_records"] == [] and r.json["symbol_conflicts"] == [] |
| 522 | c = sb.run(work, "conflicts", "--json").json |
| 523 | assert set(c) == _ENVELOPE | _CONFLICTS_KEYS |
| 524 | assert c["merge_in_progress"] is True and c["merge_from"] == "feat" |
| 525 | assert [(x["path"], x["kind"]) for x in c["conflicts"]] == [ |
| 526 | ("pyproject.toml::project", "symbol"), ("pyproject.toml::project.version", "symbol"), |
| 527 | ("src/auth/tokens.py::validate_token", "symbol")] |
| 528 | assert set(c["conflicts"][0]) == {"path", "file", "symbol", "kind"} |
| 529 | assert set(c["next_steps"]) == {"resolve_ours", "resolve_theirs", "resolve_all_ours", "resolve_all_theirs", "commit", "abort"} |
| 530 | assert sb.run(work, "conflicts", "--count", "--json").out.strip() == "3" # a bare number, even with --json |
| 531 | assert sb.run(work, "conflicts", "--exit-code", ok=False).rc == 1 |
| 532 | assert sb.run(work, "conflicts", "--filter", "file", "--json").json["conflict_count"] == 0 |
| 533 | |
| 534 | def test_no_merge_in_progress(self, sb: Sandbox, clean: pathlib.Path) -> None: |
| 535 | c = sb.run(sb.copy(clean), "conflicts", "--json").json |
| 536 | assert c["merge_in_progress"] is False and c["conflicts"] == [] and c["conflict_count"] == 0 |
| 537 | |
| 538 | def test_json_file_is_a_whole_file_conflict(self, sb: Sandbox) -> None: |
| 539 | repo = sb.build({"c.json": '{"name": "x", "version": "1.0.0"}\n'}, {"c.json": '{"name": "x", "version": "2.0.0", "b": 2}\n'}, |
| 540 | {"c.json": '{"name": "x", "version": "1.1.0", "a": 1}\n'}) |
| 541 | work = sb.copy(repo) |
| 542 | assert sb.run(work, "merge", "feat", "--json", ok=False).rc == 1 |
| 543 | c = sb.run(work, "conflicts", "--json").json["conflicts"] |
| 544 | assert [(x["path"], x["kind"], x["symbol"]) for x in c] == [("c.json", "file", None)] |
| 545 | r, w = _merged(sb, repo, "--strategy", "overlay") # overlay: theirs, whole file, dev's key is gone |
| 546 | assert r.rc == 0 and json.loads(_read(w, "c.json")) == {"name": "x", "version": "2.0.0", "b": 2} |
| 547 | |
| 548 | def test_explain_object_shape_and_vocabulary(self, sb: Sandbox, clean: pathlib.Path, conflicted: pathlib.Path, html: str) -> None: |
| 549 | ex = sb.merge(clean, "--explain").json["explain"] |
| 550 | assert set(ex) == {"strategy_routing", "merge_base_commit_id", "per_path", "summary"} |
| 551 | assert set(ex["strategy_routing"]) == _ROUTING_KEYS and set(ex["summary"]) == _SUMMARY_KEYS |
| 552 | assert all(set(e) == _PER_PATH_KEYS for e in ex["per_path"]) |
| 553 | decisions = {e["path"]: e["decision"] for e in ex["per_path"]} |
| 554 | assert decisions["src/auth/tokens.py"] == "independence_merged" and decisions["pyproject.toml"] == "no_change" |
| 555 | ex = sb.merge(conflicted, "--explain").json["explain"] |
| 556 | assert {e["path"]: e["decision"] for e in ex["per_path"]}["src/auth/tokens.py"] == "conflict" |
| 557 | # the decision vocabulary on the page is the engine's |
| 558 | decisions_html = _section(html, "explain").split("The <code>decision</code> values", 1)[1].split("<tbody>", 1)[1].split("</tbody>", 1)[0] |
| 559 | page = set(re.findall(r"<code>([a-z_]+)</code>", decisions_html)) |
| 560 | assert {"no_change", "take_ours_only", "take_theirs_only", "convergent", "independence_merged", "harmony_auto_resolved", |
| 561 | "attributes_auto_resolved", "overlay_auto_resolved", "conflict"} <= page |
| 562 | |
| 563 | def test_markers_and_resolve_flow(self, sb: Sandbox, conflicted: pathlib.Path) -> None: |
| 564 | work = sb.copy(conflicted) |
| 565 | sb.run(work, "merge", "feat", "--json", ok=False) |
| 566 | text = _read(work, "src/auth/tokens.py") |
| 567 | assert re.search(r"<<<<<<< dev \[modified\]\n.*\n\|\|\|\|\|\|\| base\n.*\n======= feat \[modified\]\n.*\n>>>>>>> end conflict\n", text) |
| 568 | r = sb.run(work, "resolve", "src/auth/tokens.py::validate_token", "--json") |
| 569 | assert r.json["resolved"] == ["src/auth/tokens.py::validate_token"] and r.json["remaining"] == 2 and r.json["ready_to_commit"] is False |
| 570 | r = sb.run(work, "resolve", "--all", "--json") |
| 571 | assert r.json["remaining"] == 0 and r.json["ready_to_commit"] is True |
| 572 | before = sb.run(work, "read", "HEAD", "--json").json["commit_id"] |
| 573 | sb.run(work, "commit", "-m", "merge: resolve") |
| 574 | head = sb.run(work, "read", "HEAD", "--json").json |
| 575 | assert head["parent_commit_id"] == before and head["parent2_commit_id"] # two parents |
| 576 | # resolve does not look at the file: markers are committed as they are |
| 577 | assert "<<<<<<< dev [modified]" in _read(work, "src/auth/tokens.py") |
| 578 | |
| 579 | def test_code_add_before_the_commit_puts_the_whole_merge_in_it(self, sb: Sandbox, same: pathlib.Path) -> None: |
| 580 | work = sb.copy(same) |
| 581 | sb.run(work, "merge", "feat", "--json", ok=False) |
| 582 | sb.write(work, {"a.py": _A_RESOLVED}) |
| 583 | sb.run(work, "resolve", "--all", "--json") |
| 584 | sb.run(work, "code", "add", ".") |
| 585 | sb.run(work, "commit", "-m", "merge: resolve") |
| 586 | assert "q.txt" in sb.run(work, "read", "HEAD", "--json").json["files_modified"] + sb.run(work, "diff", "HEAD~1", "HEAD", "--json").json.get("modified", []) |
| 587 | assert "nothing to commit" in sb.run(work, "status").out or "modified" not in sb.run(work, "status").out |
| 588 | |
| 589 | def test_exit_codes(self, sb: Sandbox, clean: pathlib.Path, conflicted: pathlib.Path) -> None: |
| 590 | work = sb.copy(clean) |
| 591 | r = sb.run(work, "merge", "dev", "--json", ok=False) # on dev: a branch into itself |
| 592 | assert r.rc == 1 and r.json["error"] == "Cannot merge a branch into itself." |
| 593 | r = sb.run(work, "merge", "nope", "--json", ok=False) |
| 594 | assert r.rc == 1 |
| 595 | r = sb.run(work, "merge", "feat", "--strategy", "bogus", "--json", ok=False) |
| 596 | assert r.rc == 1 and r.json["status"] == "error" and "Invalid --strategy" in r.json["error"] # JSON on stdout |
| 597 | assert sb.run(work, "merge", "feat", "--no-such-flag", ok=False).rc == 2 # argparse |
| 598 | assert sb.merge(conflicted, "--dry-run").rc == 1 # a dry-run that finds conflicts |
| 599 | dirty = sb.copy(clean) |
| 600 | sb.write(dirty, {"src/auth/tokens.py": "# local edit\n"}) |
| 601 | r = sb.run(dirty, "merge", "feat", "--json", ok=False) |
| 602 | assert r.rc == 1 and "would be overwritten" in (r.out + r.err) |
| 603 | |
| 604 | def test_dry_run_changes_nothing(self, sb: Sandbox, conflicted: pathlib.Path) -> None: |
| 605 | work = sb.copy(conflicted) |
| 606 | before = {p: _read(work, p) for p in ("src/auth/tokens.py", "pyproject.toml")} |
| 607 | sb.run(work, "merge", "feat", "--dry-run", "--explain", "--json", ok=False) |
| 608 | assert {p: _read(work, p) for p in before} == before |
| 609 | assert not (work / ".muse" / "MERGE_STATE.json").exists() |
| 610 | |
| 611 | def test_abort_restores_and_removes_merge_state(self, sb: Sandbox, conflicted: pathlib.Path) -> None: |
| 612 | work = sb.copy(conflicted) |
| 613 | before = _read(work, "pyproject.toml") |
| 614 | sb.run(work, "merge", "feat", "--json", ok=False) |
| 615 | assert (work / ".muse" / "MERGE_STATE.json").exists() |
| 616 | sb.run(work, "merge", "--abort") |
| 617 | assert _read(work, "pyproject.toml") == before and not (work / ".muse" / "MERGE_STATE.json").exists() |
| 618 | |
| 619 | def test_no_ff_makes_a_two_parent_commit_on_a_fast_forward(self, sb: Sandbox) -> None: |
| 620 | repo = sb.build({"m.py": "x = 1\n"}, {"m.py": "x = 2\n"}, None) |
| 621 | work = sb.copy(repo) |
| 622 | sb.run(work, "merge", "feat", "--no-ff", "--json") |
| 623 | head = sb.run(work, "read", "HEAD", "--json").json |
| 624 | assert head["parent_commit_id"] and head["parent2_commit_id"] |
| 625 | |
| 626 | def test_safe_protocol_commands(self, sb: Sandbox, clean: pathlib.Path) -> None: |
| 627 | mb = sb.run(clean, "merge-base", "dev", "feat", "--json").json |
| 628 | assert {"commit_a", "commit_b", "merge_base"} <= set(mb) |
| 629 | rl = sb.run(clean, "rev-list", "dev..feat", "--json").json |
| 630 | assert "commits" not in rl and len(rl["commit_ids"]) == 1 # IDs only: the page uses muse log for messages |
| 631 | log = sb.run(clean, "log", "dev..feat", "--json").json |
| 632 | assert [(c["message"], bool(c["committed_at"])) for c in log["commits"]] == [("feat 1", True)] |
| 633 | work = sb.copy(clean) |
| 634 | sb.run(work, "branch", "feat-backup") # on dev |
| 635 | sb.run(work, "branch", "feat-backup2", "feat") |
| 636 | tips = {b: sb.run(work, "rev-parse", b).out.strip() for b in ("dev", "feat", "feat-backup", "feat-backup2")} |
| 637 | assert tips["feat-backup"] == tips["dev"] != tips["feat"] and tips["feat-backup2"] == tips["feat"] |
| 638 | assert "dev" in sb.run(work, "status").out # the backup did not switch branches |
| 639 | assert sb.run(clean, "diff", "dev", "feat", "--json").json # `muse diff A B --json | jq keys` |
| 640 | |
| 641 | |
| 642 | # ── DOC_MRG_07: proposal merge ────────────────────────────────────────────── |
| 643 | |
| 644 | |
| 645 | def _sub(parser: argparse.ArgumentParser, *names: str) -> argparse.ArgumentParser: |
| 646 | for name in names: |
| 647 | action = next(a for a in parser._actions if isinstance(a, argparse._SubParsersAction)) |
| 648 | parser = action.choices[name] |
| 649 | return parser |
| 650 | |
| 651 | |
| 652 | @pytest.fixture(scope="module") |
| 653 | def proposal_parser() -> argparse.ArgumentParser: |
| 654 | return _sub(cc.capture_parser(), "hub", "proposal", "merge") |
| 655 | |
| 656 | |
| 657 | class TestProposalMerge: |
| 658 | def test_flags_the_page_says_are_not_available_are_still_not_accepted(self, proposal_parser: argparse.ArgumentParser, html: str) -> None: |
| 659 | accepted = {s for a in proposal_parser._actions for s in a.option_strings} |
| 660 | assert {"--strategy", "--no-delete-branch", "--hub", "--json"} <= accepted |
| 661 | assert "--history" in accepted # muse#172: the history style is its own flag |
| 662 | for flag in ("--on-conflict", "--dry-run", "--explain"): |
| 663 | assert flag not in accepted, f"{flag} now exists: update the Proposal merge section" |
| 664 | section = _text(_section(html, "proposal-merge")) |
| 665 | assert "proposal merge does not offer them" in section and "Not available in 0.2.1rc20" not in section |
| 666 | |
| 667 | def test_the_cli_choices_the_page_documents(self, proposal_parser: argparse.ArgumentParser, html: str) -> None: |
| 668 | strategy = next(a for a in proposal_parser._actions if "--strategy" in a.option_strings) |
| 669 | history = next(a for a in proposal_parser._actions if "--history" in a.option_strings) |
| 670 | assert list(strategy.choices) == ["overlay", "weave", "replay", "selective"] and strategy.default is None |
| 671 | assert list(history.choices) == ["merge", "squash", "rebase"] and history.default == "merge" |
| 672 | flags = _section(html, "proposal-merge").split("<h3>Flags</h3>", 1)[1].split("</table>", 1)[0] |
| 673 | for value in [*strategy.choices, *history.choices]: |
| 674 | assert f"<code>{value}</code>" in flags, value |
| 675 | |
| 676 | def test_the_api_fields_are_the_ones_the_cli_sends(self) -> None: |
| 677 | from musehub.models.musehub import ProposalMergeRequest |
| 678 | |
| 679 | assert set(ProposalMergeRequest.model_fields) == {"merge_strategy", "commit_history", "delete_branch"} |
| 680 | body = ProposalMergeRequest.model_validate({"mergeStrategy": "overlay", "commitHistory": "squash", "deleteBranch": False}) |
| 681 | assert (body.merge_strategy, body.commit_history, body.delete_branch) == ("overlay", "squash", False) |
| 682 | assert ProposalMergeRequest.model_validate({}).delete_branch is None # omitted → the repo setting decides |
| 683 | |
| 684 | @pytest.mark.parametrize("value", ["squash", "rebase", "bogus"]) |
| 685 | def test_an_unknown_merge_strategy_is_a_validation_error(self, value: str) -> None: |
| 686 | from pydantic import ValidationError |
| 687 | |
| 688 | from musehub.models.musehub import ProposalMergeRequest |
| 689 | |
| 690 | with pytest.raises(ValidationError) as err: |
| 691 | ProposalMergeRequest.model_validate({"mergeStrategy": value}) |
| 692 | assert all(v in str(err.value) for v in ("overlay", "weave", "replay", "selective")) |
| 693 | |
| 694 | def test_every_cli_strategy_is_accepted_by_the_server(self, proposal_parser: argparse.ArgumentParser) -> None: |
| 695 | from musehub.models.musehub import ProposalMergeRequest |
| 696 | from musehub.services.proposal_merge_strategies import execute_merge_strategy |
| 697 | |
| 698 | strategy = next(a for a in proposal_parser._actions if "--strategy" in a.option_strings) |
| 699 | history = next(a for a in proposal_parser._actions if "--history" in a.option_strings) |
| 700 | rejected = [] |
| 701 | for value in [*strategy.choices, "merge_commit"]: # merge_commit: what the CLI sends when --strategy is omitted |
| 702 | body = ProposalMergeRequest.model_validate({"mergeStrategy": value, "commitHistory": history.default}) |
| 703 | effective = "overlay" if body.merge_strategy == "merge_commit" else body.merge_strategy # merge_proposal's mapping |
| 704 | # selective merges the proposal's own selective_domains (merge_proposal passes them through) |
| 705 | domains = ["code"] if effective == "selective" else None |
| 706 | try: |
| 707 | execute_merge_strategy(effective, {"a": "sha256:1"}, {"a": "sha256:2"}, ancestor_manifest={"a": "sha256:0"}, |
| 708 | selective_domains=domains) |
| 709 | except ValueError as exc: |
| 710 | rejected.append(f"{value}: {exc}") |
| 711 | assert not rejected, rejected |
| 712 | for value in history.choices: |
| 713 | assert ProposalMergeRequest.model_validate({"commitHistory": value}).commit_history == value |
| 714 | |
| 715 | def test_the_server_reads_delete_branch(self, html: str) -> None: |
| 716 | import inspect |
| 717 | |
| 718 | from musehub.api.routes.musehub import proposals |
| 719 | from musehub.services import musehub_proposals |
| 720 | |
| 721 | assert "delete_branch=body.delete_branch" in inspect.getsource(proposals.merge_proposal) |
| 722 | assert "delete_branch_on_merge" in inspect.getsource(musehub_proposals.merge_proposal) |
| 723 | section = _text(_section(html, "proposal-merge")) |
| 724 | assert "ignored by the server" not in section and "has no effect" not in section |
| 725 | assert "deleteBranch is honoured" in " ".join(section.split()) |
| 726 | |
| 727 | |
| 728 | # ── DOC_MRG_08: formerly known defects (Muse batch 1), the fixed contracts pinned ─ |
| 729 | |
| 730 | |
| 731 | class TestFixedDefects: |
| 732 | @pytest.mark.parametrize("case", ["S5", "S7", "S8"]) |
| 733 | def test_a_clean_merge_never_writes_a_wrong_file(self, compare: dict, case: str) -> None: |
| 734 | assert compare[case][0] in ("clean", "conflict"), compare[case] |
| 735 | |
| 736 | def test_resolve_then_commit_contains_the_whole_merge(self, sb: Sandbox, same: pathlib.Path) -> None: |
| 737 | work = sb.copy(same) |
| 738 | sb.run(work, "merge", "feat", "--json", ok=False) |
| 739 | sb.write(work, {"a.py": _A_RESOLVED}) |
| 740 | sb.run(work, "resolve", "--all", "--json") |
| 741 | sb.run(work, "commit", "-m", "merge: resolve") # no code add: the documented contract needs none |
| 742 | assert "modified" not in sb.run(work, "status").out, sb.run(work, "status").out |
| 743 | |
| 744 | def test_rename_plus_edit_merges_cleanly(self, compare: dict) -> None: |
| 745 | label, text = compare["S6"] |
| 746 | assert label == "clean" and "x + 10" in text |
| 747 | |
| 748 | def test_explain_labels_a_followed_rename(self, sb: Sandbox, html: str) -> None: |
| 749 | base, dev, feat, _ = _CASES["S6"] |
| 750 | ex = sb.merge(sb.build(base, feat, dev), "--explain").json["explain"] |
| 751 | by_path = {e["path"]: e for e in ex["per_path"]} |
| 752 | assert by_path["util.py"]["decision"] == "renamed" and by_path["util.py"]["renamed_to"] == "helpers.py" |
| 753 | assert by_path["helpers.py"]["decision"] == "rename_followed" and by_path["helpers.py"]["renamed_from"] == "util.py" |
| 754 | for entry in ex["per_path"]: # renamed_from / renamed_to only on rename entries |
| 755 | extra = {"renamed_to"} if entry["decision"] == "renamed" else {"renamed_from"} if entry["decision"] == "rename_followed" else set() |
| 756 | assert set(entry) == _PER_PATH_KEYS | extra, entry |
| 757 | table = _section(html, "explain").split("The <code>decision</code> values", 1)[1].split("</tbody>", 1)[0] |
| 758 | for label in ("prefer_theirs_resolved", "prefer_ours_resolved", "modify_delete_conflict", "attributes_auto_resolved", |
| 759 | "dimension_merged", "plugin_merged", "rename_followed", "renamed", "rename_conflict"): |
| 760 | assert f"<code>{label}</code>" in table, label |
| 761 | |
| 762 | def test_rebase_replays_every_commit(self, sb: Sandbox, three: pathlib.Path) -> None: |
| 763 | work = sb.copy(three) |
| 764 | before = sb.run(work, "read", "HEAD", "--json").json["commit_id"] |
| 765 | sb.run(work, "merge", "feat", "--history", "rebase", "--json") |
| 766 | assert len(_new_commits(sb, work, before)) == 3 |
| 767 | |
| 768 | def test_autoshelf_keeps_the_merged_change(self, sb: Sandbox) -> None: |
| 769 | base = "def greet(name):\n return 'Hello, ' + name\n" |
| 770 | repo = sb.build({"app.py": base}, {"app.py": base + "\n\ndef extra():\n return 1\n"}, None) |
| 771 | work = sb.copy(repo) |
| 772 | sb.write(work, {"app.py": base + "# dirty\n"}) |
| 773 | sb.run(work, "merge", "feat", "--autoshelf") |
| 774 | assert "def extra" in _read(work, "app.py") |
| 775 | |
| 776 | @pytest.mark.parametrize("flags", [("--strategy", "theirs"), ("--strategy", "overlay"), ("--on-conflict", "ours")]) |
| 777 | def test_explain_is_emitted_on_real_merges(self, sb: Sandbox, same: pathlib.Path, flags: tuple[str, ...]) -> None: |
| 778 | assert "explain" in sb.merge(same, *flags, "--explain").json |
| 779 | |
| 780 | def test_explain_is_emitted_on_a_fast_forward(self, sb: Sandbox) -> None: |
| 781 | repo = sb.build({"m.py": "x = 1\n"}, {"m.py": "x = 2\n"}, None) |
| 782 | assert "explain" in sb.merge(repo, "--explain").json |
| 783 | |
| 784 | |
| 785 | # ── Static page checks ─────────────────────────────────────────────────────── |
| 786 | |
| 787 | |
| 788 | class TestPage: |
| 789 | def test_workspace_specific_text_is_gone(self, html: str) -> None: |
| 790 | for needle in ("~/ecosystem", "deploy/rc12", "8 accidental", "push local", "this workspace", "claude-sonnet-4-6", |
| 791 | "diff_symbols", "Phase 05: Harmony", "icon-warn"): |
| 792 | assert needle not in html, needle |
| 793 | assert "Phase 06: Harmony" in html |
| 794 | |
| 795 | def test_every_known_defect_links_its_ticket(self, html: str) -> None: |
| 796 | muse = set(re.findall(rf"{re.escape(MUSE_ISSUES)}(\d+)", html)) |
| 797 | hub = set(re.findall(rf"{re.escape(HUB_ISSUES)}(\d+)", html)) |
| 798 | assert _MUSE_LINKS <= muse, _MUSE_LINKS - muse |
| 799 | assert _HUB_LINKS <= hub, _HUB_LINKS - hub |
| 800 | |
| 801 | def test_every_section_the_sidebar_links_exists(self, html: str) -> None: |
| 802 | for anchor in ("overview", "granularity", "engine-model", "strategy", "strategy-routing", "history", "on-conflict", "explain", |
| 803 | "local-merge", "proposal-merge", "safe-protocol", "harmony", "cli", "git-comparison", "strategy-dry-run", |
| 804 | "local-merge-resolving", "safe-step1", "safe-step2", "safe-step3", "safe-step4"): |
| 805 | assert f'id="{anchor}"' in html, anchor |
| 806 | |
| 807 | def test_every_cli_row_accepts_json(self, html: str) -> None: |
| 808 | parser = cc.capture_parser() |
| 809 | table = _section(html, "cli").split('id="cli-table"', 1)[1].split("</table>", 1)[0] |
| 810 | commands = [html_lib.unescape(c) for c in re.findall(r"<td><code>(muse [^<]*)</code></td>", table)] |
| 811 | assert len(commands) >= 18 |
| 812 | for command in commands: |
| 813 | line = re.sub(r"<|>", "", command) |
| 814 | if "--json" not in line: |
| 815 | continue |
| 816 | assert cc.check_line(parser, cc.DocCommand(re.sub(r"<[^>]*>|\s--json", "", command) + " --json", in_pre=False)).kind == "ok", command |
File History
8 commits
sha256:f19d5e4a89766fc91b926cdf801255e12dcd968041c0ece8adf6627760788d22
merge: next build — MCP (#291 #292 #295 #324), profiles/sit…
Opus 5.5
minor
⚠
1 day ago
sha256:6eda345790556873998197bb44bb3ff45bfe7fa527eb701f635a044f93e537b0
merge: rc26 — REST proposal-merge fixes (#284 #285); wire c…
Opus 5.5
minor
⚠
1 day ago
sha256:ec486b81f09923974e084f9a5dbdeaad8035e1b1a25743b8d2239bb67f3e440c
fix(proposals): validate mergeStrategy (422, not 404) and h…
Opus 5.5
minor
⚠
2 days ago
sha256:e1629e5f328982dbf6e535d3f253993c78ff225dfee4ebb0e0a15fc1db69046b
merge: rc25 — docs and docs-contract tests match Muse batch…
Opus 5.5
minor
⚠
2 days ago
sha256:2371627bdafbda7522b1fb93c4e58579d3a553b90168e7a7304aaaac27448e8e
docs(merge): whole-merge commit, rename following, rebase r…
Opus 5.5
patch
2 days ago
sha256:369f691c7aaec3ca84a864ad1d099d5409045ddc12d185a922b3c84b9e2a1bad
merge: 100% passing, parallelized MuseHub test suite (task/…
Sonnet 5.5
patch
3 days ago
sha256:8166b51ae53275831023a7ce334228b3ccc8237b55d68a35172389db9ff46ad5
test: 100% passing MuseHub suite, parallelized (xdist, one …
Sonnet 5.5
patch
3 days ago
sha256:0914c802f6e5260fd54b28ecfb013b7815a76983780d5d2f854ef46c3ed36ab8
docs(merge): #249 Merge Engine QA contract v2 — correct /mu…
Sonnet 5.5
minor
⚠
9 days ago