"""Phase 3 — MERGE_STATE ordering: apply_manifest before write_merge_state. Invariant: in the merge conflict path, the working tree must be updated (apply_manifest) BEFORE the MERGE_STATE.json is written. Rationale: If a crash occurs between write_merge_state and apply_manifest: - MERGE_STATE.json exists (claims a conflict is in progress) - Working tree is still at 'ours' (clean, not showing any conflict) - 'muse conflicts' lists conflict paths but the files look clean - The user cannot resolve anything — they are stuck If a crash occurs between apply_manifest and write_merge_state: - Working tree has partially merged state (some files updated) - No MERGE_STATE.json (no in-progress merge recorded) - The user sees a dirty tree, can inspect diffs, and can run 'muse merge' again - Recoverable The safe order is apply_manifest first, write_merge_state second. Testing tiers ------------- Unit write_merge_state is called AFTER apply_manifest (call order) Integration merge command produces a dirty working tree AND a MERGE_STATE.json Data after a simulated crash between apply and write_merge_state: no MERGE_STATE.json exists, working tree is at partially merged state """ from __future__ import annotations import pathlib from unittest.mock import call, patch, MagicMock import pytest from muse.core.types import Manifest from tests.cli_test_helper import CliRunner runner = CliRunner() def _run(repo: pathlib.Path, *args: str, expect_failure: bool = False) -> "CliRunner.Result": r = runner.invoke(None, list(args), cwd=repo) if not expect_failure: assert r.exit_code == 0, f"muse {' '.join(args)} failed:\n{r.output}" return r def _setup_conflict_scenario(repo: pathlib.Path) -> None: """Create two diverged branches with a conflict in file.py.""" f = repo / "file.py" # initial commit on main f.write_text("base content\n") _run(repo, "code", "add", "file.py") _run(repo, "commit", "-m", "base") # branch A modifies file.py _run(repo, "checkout", "-b", "branch-a") f.write_text("branch-a content\n") _run(repo, "code", "add", "file.py") _run(repo, "commit", "-m", "branch-a change") # go back to main and make a conflicting change _run(repo, "checkout", "main") f.write_text("main content\n") _run(repo, "code", "add", "file.py") _run(repo, "commit", "-m", "main change") # --------------------------------------------------------------------------- # Unit — call order: apply_manifest before write_merge_state # --------------------------------------------------------------------------- class TestCallOrder: def test_apply_manifest_called_before_write_merge_state( self, muse_repo: pathlib.Path ) -> None: """apply_manifest must be called before write_merge_state in the conflict path.""" _setup_conflict_scenario(muse_repo) call_order: list[str] = [] orig_apply = __import__( "muse.core.workdir", fromlist=["apply_manifest"] ).apply_manifest orig_write_merge = __import__( "muse.core.merge_engine", fromlist=["write_merge_state"] ).write_merge_state def track_apply(root: pathlib.Path, prev_manifest: Manifest, target_manifest: Manifest) -> None: call_order.append("apply_manifest") return orig_apply(root, prev_manifest, target_manifest) def track_write_merge(root: pathlib.Path, **kwargs: str | list[str] | None) -> None: call_order.append("write_merge_state") return orig_write_merge(root, **kwargs) with ( patch("muse.cli.commands.merge.apply_manifest", side_effect=track_apply), patch("muse.cli.commands.merge.write_merge_state", side_effect=track_write_merge), ): _run(muse_repo, "merge", "branch-a", expect_failure=True) apply_idx = next( (i for i, n in enumerate(call_order) if n == "apply_manifest"), None ) write_merge_idx = next( (i for i, n in enumerate(call_order) if n == "write_merge_state"), None ) assert apply_idx is not None, "apply_manifest was never called during conflict merge" assert write_merge_idx is not None, "write_merge_state was never called during conflict merge" assert apply_idx < write_merge_idx, ( f"write_merge_state (pos {write_merge_idx}) was called before " f"apply_manifest (pos {apply_idx}) — wrong order" ) # --------------------------------------------------------------------------- # Integration — merge conflict leaves both dirty workdir and MERGE_STATE # --------------------------------------------------------------------------- class TestMergeConflictIntegration: def test_conflict_produces_merge_state_file(self, muse_repo: pathlib.Path) -> None: """A merge conflict must create .muse/MERGE_STATE.json.""" _setup_conflict_scenario(muse_repo) _run(muse_repo, "merge", "branch-a", expect_failure=True) assert (muse_repo / ".muse" / "MERGE_STATE.json").exists(), ( "MERGE_STATE.json not created after conflicting merge" ) def test_conflict_leaves_working_tree_dirty(self, muse_repo: pathlib.Path) -> None: """After a conflicting merge, the working tree must reflect the partial merge.""" _setup_conflict_scenario(muse_repo) _run(muse_repo, "merge", "branch-a", expect_failure=True) # The status command should report the working tree as dirty (merge in progress) import json r = runner.invoke(None, ["status", "--json"], cwd=muse_repo) status = json.loads(r.output) assert status["merge_in_progress"] or status["dirty"] or status["conflict_count"] > 0, ( "Working tree appears clean after a conflicting merge — apply_manifest may not have run" ) # --------------------------------------------------------------------------- # Data — crash between apply_manifest and write_merge_state is recoverable # --------------------------------------------------------------------------- class TestCrashRecovery: def test_crash_after_apply_before_write_merge_leaves_no_merge_state( self, muse_repo: pathlib.Path ) -> None: """Simulated crash after apply_manifest but before write_merge_state: MERGE_STATE.json must NOT exist (no ghost merge state). The working tree has partial merge content (dirty but recoverable).""" _setup_conflict_scenario(muse_repo) def crash_after_apply(root: pathlib.Path, **kwargs: str | list[str] | None) -> None: raise RuntimeError("simulated crash after apply_manifest") with ( patch("muse.cli.commands.merge.write_merge_state", side_effect=crash_after_apply), ): try: _run(muse_repo, "merge", "branch-a", expect_failure=True) except (RuntimeError, SystemExit): pass assert not (muse_repo / ".muse" / "MERGE_STATE.json").exists(), ( "MERGE_STATE.json exists after crash before write_merge_state — " "wrong ordering: write_merge_state was called before apply_manifest" )