From dd297c7237f23aa8952a915f5d3a4c7359d58f4d Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Sat, 21 Nov 2026 05:07:03 +0100 Subject: [PATCH 1/8] integration(mvp): compose independently qualified handover recovery with formal broker --- api/core/handover_recovery.py | 135 ++++++++++++++++++++++++++++++++++ 1 file changed, 135 insertions(+) create mode 100644 api/core/handover_recovery.py diff --git a/api/core/handover_recovery.py b/api/core/handover_recovery.py new file mode 100644 index 00000000..98f52d9f --- /dev/null +++ b/api/core/handover_recovery.py @@ -0,0 +1,135 @@ +"""Conservative restart reconciliation for an interrupted session handover. + +Only the current active-session pointer is authoritative on restart. We never +guess another session from loose markers or accept paths outside the current +session's parent directory. No Wine process is started by this reconciler. +""" +import json +import os +from pathlib import Path + +from api.core.constants import ( + SESSION_STATE_ACTIVE, + SESSION_STATE_COMPLETED, + SESSION_STATE_SUSPENDED, +) +from api.utils.files import read_session_state, write_session_state + +MARKER_NAME = "session.transition.json" +_MAX_MARKER_BYTES = 16384 + + +def _safe_peer(raw: object, active: Path) -> Path | None: + if raw is None: + return None + if not isinstance(raw, str) or not raw: + raise RuntimeError("Invalid handover peer") + path = Path(raw) + if not path.is_absolute() or path.is_symlink(): + raise RuntimeError("Invalid handover peer") + resolved = path.resolve(strict=True) + if resolved.parent != active.parent or not resolved.is_dir(): + raise RuntimeError("Handover peer is outside current session root") + return resolved + + +def _marker(session: Path) -> dict | None: + path = session / MARKER_NAME + if path.is_symlink(): + raise RuntimeError("Refusing symlink handover marker") + if not path.exists(): + return None + if path.stat().st_size > _MAX_MARKER_BYTES: + raise RuntimeError("Oversized handover marker") + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + raise RuntimeError("Invalid handover marker") from exc + if not isinstance(data, dict) or not isinstance(data.get("extra"), dict): + raise RuntimeError("Invalid handover marker envelope") + if not isinstance(data["extra"].get("operation_id"), str): + raise RuntimeError("Missing handover operation identity") + return data + + +def _remove_durable(session: Path) -> None: + path = session / MARKER_NAME + if path.is_symlink(): + raise RuntimeError("Refusing symlink handover marker") + if path.exists(): + path.unlink() + directory_fd = os.open(str(session), os.O_RDONLY) + try: + os.fsync(directory_fd) + finally: + os.close(directory_fd) + + +def reconcile_active_handover(session_dir: str, profile_link: str) -> str: + """Converge interrupted ownership to the active pointer, fail closed. + + Call only after the runtime has relinked the user profile and updated its + in-process broker for the active session. Reconcile no other session unless + its marker matches the exact same operation and points back to active. + """ + active = Path(session_dir).resolve(strict=True) + marker = _marker(active) + if marker is None: + return "no_marker" + if not active.is_dir() or not (active / "user").is_dir(): + raise RuntimeError("Active session profile unavailable") + link = Path(profile_link) + if not link.is_symlink() or link.resolve(strict=True) != (active / "user").resolve(): + raise RuntimeError("Active Wine profile link disagrees with session pointer") + + phase = marker.get("phase") + extra = marker["extra"] + operation_id = extra["operation_id"] + if phase == "resume_target_prepare": + peer = _safe_peer(extra.get("previous_session"), active) + if peer is not None and peer != active: + other = _marker(peer) + # The original transaction writes BOTH markers before changing + # the active pointer. A missing peer marker at this phase is not + # an admissible crash outcome, and must remain quarantined. + if other is None: + # Crash after deleting a peer marker is replayable only if + # both persisted owners already reached the safe end state. + if (read_session_state(str(active)) != SESSION_STATE_ACTIVE or + read_session_state(str(peer)) not in + (SESSION_STATE_SUSPENDED, SESSION_STATE_COMPLETED)): + raise RuntimeError("Absent handover peer marker before commit") + elif (other.get("phase") != "resume_handover_out" or + other["extra"].get("operation_id") != operation_id or + _safe_peer(other["extra"].get("target_session"), peer) != active): + raise RuntimeError("Conflicting handover peer marker") + if peer is not None and peer != active: + if read_session_state(str(peer)) in (None, SESSION_STATE_ACTIVE): + write_session_state(str(peer), SESSION_STATE_SUSPENDED) + write_session_state(str(active), SESSION_STATE_ACTIVE) + if peer is not None and peer != active: + _remove_durable(peer) + elif phase == "resume_handover_out": + peer = _safe_peer(extra.get("target_session"), active) + if peer is not None and peer != active: + other = _marker(peer) + if other is None: + if (read_session_state(str(active)) != SESSION_STATE_ACTIVE or + read_session_state(str(peer)) not in + (SESSION_STATE_SUSPENDED, SESSION_STATE_COMPLETED)): + raise RuntimeError("Absent handover peer marker before commit") + elif (other.get("phase") != "resume_target_prepare" or + other["extra"].get("operation_id") != operation_id or + _safe_peer(other["extra"].get("previous_session"), peer) != active): + raise RuntimeError("Conflicting handover peer marker") + # Even a stray target ACTIVE must not leave dual active state. + if read_session_state(str(peer)) in (None, SESSION_STATE_ACTIVE): + write_session_state(str(peer), SESSION_STATE_SUSPENDED) + write_session_state(str(active), SESSION_STATE_ACTIVE) + if peer is not None and peer != active: + _remove_durable(peer) + else: + raise RuntimeError("Unknown handover phase") + + _remove_durable(active) + return "reconciled" From 3bf99a33c0646f46a7794b88117fa30c1d6abc84 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Sat, 21 Nov 2026 05:07:06 +0100 Subject: [PATCH 2/8] integration(mvp): compose independently qualified handover recovery with formal broker --- api/server.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/api/server.py b/api/server.py index c3d51272..5bd040af 100644 --- a/api/server.py +++ b/api/server.py @@ -20,6 +20,7 @@ from api.core.broker import broker from api.core.config_guard import validate_current_environment from api.core.discovery import discovery_manager +from api.core.handover_recovery import reconcile_active_handover from api.core.models import ControlPolicyMode from api.core.monitor import inactivity_monitor_task from api.core.session_context import reset_current_session_dir, set_current_session_dir @@ -115,6 +116,11 @@ async def lifespan(_app: FastAPI): interactive, session_control_mode=session_control_mode, ) + # Reconcile a pending handover before readiness or new input grants. + profile_link = os.path.join( + os.getenv("WINEPREFIX", "/wineprefix"), "drive_c", "users", "winebot" + ) + reconcile_active_handover(session_dir, profile_link) # Start Discovery try: From 1572fa3764e1664d44fa8f2274702a9f416265e5 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Sat, 21 Nov 2026 05:07:09 +0100 Subject: [PATCH 3/8] integration(mvp): compose independently qualified handover recovery with formal broker --- api/routers/lifecycle.py | 53 ++++++++++++++++++++++++++++++++++------ 1 file changed, 46 insertions(+), 7 deletions(-) diff --git a/api/routers/lifecycle.py b/api/routers/lifecycle.py index ffbc712b..67c3ceb8 100644 --- a/api/routers/lifecycle.py +++ b/api/routers/lifecycle.py @@ -423,6 +423,17 @@ def _restore_resume_state( os.environ["WINEBOT_SESSION_ID"] = os.path.basename(previous_session_dir) if previous_current_state: write_session_state(previous_session_dir, previous_current_state) + # Restore and verify the Wine profile link after a failed activation. + _link_profile_checked(os.path.join(previous_session_dir, "user")) + + +def _link_profile_checked(user_dir: str) -> None: + link_wine_user_dir(user_dir) + profile_link = os.path.join( + os.getenv("WINEPREFIX", "/wineprefix"), "drive_c", "users", "winebot" + ) + if not os.path.islink(profile_link) or os.path.realpath(profile_link) != os.path.realpath(user_dir): + raise RuntimeError("Session profile link verification failed") def _transition_marker_path(session_dir: str) -> str: @@ -443,17 +454,27 @@ def _write_transition_marker(session_dir: str, phase: str, extra: dict[str, Any] f.flush() os.fsync(f.fileno()) os.replace(tmp_path, _transition_marker_path(session_dir)) + # fsync directory so the intent rename survives a process crash/reboot. + directory_fd = os.open(session_dir, os.O_RDONLY) + try: + os.fsync(directory_fd) + finally: + os.close(directory_fd) def _clear_transition_marker(session_dir: str | None) -> None: if not session_dir: return path = _transition_marker_path(session_dir) - try: - if os.path.exists(path): - os.unlink(path) - except Exception: - pass + if os.path.islink(path): + raise RuntimeError("Refusing symlink transition marker") + if os.path.exists(path): + os.unlink(path) + directory_fd = os.open(session_dir, os.O_RDONLY) + try: + os.fsync(directory_fd) + finally: + os.close(directory_fd) @router.get("/operations/{operation_id}") @@ -991,7 +1012,7 @@ async def resume_session(data: SessionResumeModel | None = Body(default=None)): os.environ["WINEBOT_SESSION_DIR"] = target_dir os.environ["WINEBOT_SESSION_ID"] = os.path.basename(target_dir) os.environ["WINEBOT_USER_DIR"] = user_dir - link_wine_user_dir(user_dir) + _link_profile_checked(user_dir) write_session_state(target_dir, SESSION_STATE_ACTIVE) append_lifecycle_event( target_dir, "session_resumed", "Session resumed via API", source="api" @@ -1013,9 +1034,17 @@ async def resume_session(data: SessionResumeModel | None = Body(default=None)): interactive, session_control_mode=session_control_mode, ) - _clear_transition_marker(target_dir) + # Commit the prior owner out of ACTIVE before removing the durable + # intent. If this write is interrupted, startup replay can finish. + if current_session and current_session != target_dir: + if previous_current_state in (None, SESSION_STATE_ACTIVE): + write_session_state(current_session, SESSION_STATE_SUSPENDED) + # Keep the active-side intent until last: if we die after + # removing the peer marker, startup can verify converged state + # and finish active-side cleanup idempotently. if current_session and current_session != target_dir: _clear_transition_marker(current_session) + _clear_transition_marker(target_dir) except Exception as exc: _restore_resume_state( previous_session_dir=current_session, @@ -1023,6 +1052,16 @@ async def resume_session(data: SessionResumeModel | None = Body(default=None)): previous_target_state=previous_target_state, previous_current_state=previous_current_state, ) + # A first activation has no older owner to compensate to. + # Retain transaction intent for startup reconciliation rather + # than silently acknowledging an incomplete operation. + if not current_session and read_session_dir() == target_dir: + await fail_operation( + operation_id, error="handover requires restart reconciliation" + ) + raise RuntimeError( + "Interrupted session activation requires restart reconciliation" + ) from exc _clear_transition_marker(target_dir) if current_session and current_session != target_dir: _clear_transition_marker(current_session) From 7fddf60493c9e074905d747e14841d9f16741b4a Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Sat, 21 Nov 2026 05:07:13 +0100 Subject: [PATCH 4/8] integration(mvp): compose independently qualified handover recovery with formal broker --- tests/test_handover_restart_recovery.py | 166 ++++++++++++++++++++++++ 1 file changed, 166 insertions(+) create mode 100644 tests/test_handover_restart_recovery.py diff --git a/tests/test_handover_restart_recovery.py b/tests/test_handover_restart_recovery.py new file mode 100644 index 00000000..4f503947 --- /dev/null +++ b/tests/test_handover_restart_recovery.py @@ -0,0 +1,166 @@ +"""Restart handover recovery tests: synthetic files, no Wine or host effects.""" +import json +from pathlib import Path +from unittest.mock import patch + +import pytest + +from api.core.handover_recovery import reconcile_active_handover + + +def _session(root: Path, name: str) -> Path: + path = root / name + (path / "user").mkdir(parents=True) + (path / "session.state").write_text("suspended", encoding="utf-8") + return path + + +def _write_marker(session: Path, phase: str, extra: dict) -> None: + (session / "session.transition.json").write_text( + json.dumps({"phase": phase, "extra": {"operation_id": "op-synthetic", **extra}}), + encoding="utf-8", + ) + + +def _profile_link(root: Path, session: Path) -> Path: + link = root / "active-profile" + link.symlink_to(session / "user", target_is_directory=True) + return link + + +def test_without_marker_is_noop(tmp_path): + current = _session(tmp_path, "A") + assert reconcile_active_handover(str(current), str(tmp_path / "absent")) == "no_marker" + assert (current / "session.state").read_text() == "suspended" + + +def test_crash_after_active_pointer_update_converges_target(tmp_path): + old = _session(tmp_path, "A") + target = _session(tmp_path, "B") + profile = _profile_link(tmp_path, target) + _write_marker(target, "resume_target_prepare", {"previous_session": str(old)}) + _write_marker(old, "resume_handover_out", {"target_session": str(target)}) + # Simulate crash with both persisted sessions incorrectly still ACTIVE. + (old / "session.state").write_text("active", encoding="utf-8") + assert reconcile_active_handover(str(target), str(profile)) == "reconciled" + assert (target / "session.state").read_text() == "active" + assert (old / "session.state").read_text() == "suspended" + assert not (target / "session.transition.json").exists() + assert not (old / "session.transition.json").exists() + assert reconcile_active_handover(str(target), str(profile)) == "no_marker" + + +def test_crash_before_active_pointer_update_keeps_old_owner(tmp_path): + old = _session(tmp_path, "A") + target = _session(tmp_path, "B") + profile = _profile_link(tmp_path, old) + _write_marker(old, "resume_handover_out", {"target_session": str(target)}) + _write_marker(target, "resume_target_prepare", {"previous_session": str(old)}) + (target / "session.state").write_text("active", encoding="utf-8") + assert reconcile_active_handover(str(old), str(profile)) == "reconciled" + assert (old / "session.state").read_text() == "active" + assert (target / "session.state").read_text() == "suspended" + assert not (old / "session.transition.json").exists() + assert not (target / "session.transition.json").exists() + + +def test_pointer_switch_without_recipient_peer_intent_fails_closed(tmp_path): + old = _session(tmp_path, "A") + target = _session(tmp_path, "B") + profile = _profile_link(tmp_path, target) + _write_marker(target, "resume_target_prepare", {"previous_session": str(old)}) + with pytest.raises(RuntimeError, match="Absent handover peer marker"): + reconcile_active_handover(str(target), str(profile)) + assert (target / "session.transition.json").exists() + assert (target / "session.state").read_text() != "active" + + +def test_profile_link_mismatch_fails_closed_without_deleting_intent(tmp_path): + old = _session(tmp_path, "A") + target = _session(tmp_path, "B") + profile = _profile_link(tmp_path, old) + _write_marker(target, "resume_target_prepare", {"previous_session": str(old)}) + with pytest.raises(RuntimeError, match="profile link disagrees"): + reconcile_active_handover(str(target), str(profile)) + assert (target / "session.transition.json").exists() + + +def test_conflicting_peer_operation_fails_closed(tmp_path): + old = _session(tmp_path, "A") + target = _session(tmp_path, "B") + profile = _profile_link(tmp_path, target) + _write_marker(target, "resume_target_prepare", {"previous_session": str(old)}) + _write_marker(old, "resume_handover_out", {"target_session": str(target)}) + peer = old / "session.transition.json" + data = json.loads(peer.read_text()) + data["extra"]["operation_id"] = "op-foreign" + peer.write_text(json.dumps(data), encoding="utf-8") + with pytest.raises(RuntimeError, match="Conflicting"): + reconcile_active_handover(str(target), str(profile)) + assert (target / "session.transition.json").exists() + assert peer.exists() + + +def test_unsafe_external_peer_is_rejected(tmp_path): + root = tmp_path / "sessions" + _session(root, "A") + target = _session(root, "B") + profile = _profile_link(tmp_path, target) + _write_marker(target, "resume_target_prepare", {"previous_session": str(tmp_path)}) + with pytest.raises(RuntimeError, match="outside current session root"): + reconcile_active_handover(str(target), str(profile)) + assert (target / "session.transition.json").exists() + + +def test_malformed_marker_fails_closed(tmp_path): + target = _session(tmp_path, "B") + profile = _profile_link(tmp_path, target) + (target / "session.transition.json").write_text("{not-json", encoding="utf-8") + with pytest.raises(RuntimeError, match="Invalid handover marker"): + reconcile_active_handover(str(target), str(profile)) + + +def test_live_resume_profile_link_is_verified_fail_closed(tmp_path, monkeypatch): + from api.routers.lifecycle import _link_profile_checked + + prefix = tmp_path / "wineprefix" + user = tmp_path / "A" / "user" + user.mkdir(parents=True) + monkeypatch.setenv("WINEPREFIX", str(prefix)) + _link_profile_checked(str(user)) + link = prefix / "drive_c" / "users" / "winebot" + assert link.is_symlink() + assert link.resolve() == user.resolve() + + other_user = tmp_path / "B" / "user" + other_user.mkdir(parents=True) + # Model a failed linker: it silently returns while leaving the old link. + with patch("api.routers.lifecycle.link_wine_user_dir"): + with pytest.raises(RuntimeError, match="profile link verification failed"): + _link_profile_checked(str(other_user)) + assert link.resolve() == user.resolve() + + +def test_replay_after_peer_cleanup_removes_remaining_marker(tmp_path): + old = _session(tmp_path, "A") + target = _session(tmp_path, "B") + profile = _profile_link(tmp_path, target) + (target / "session.state").write_text("active", encoding="utf-8") + _write_marker(target, "resume_target_prepare", {"previous_session": str(old)}) + # Crash after unlink+fsync of the old peer marker; persisted states + # have already safely converged, so only active-side cleanup remains. + assert reconcile_active_handover(str(target), str(profile)) == "reconciled" + assert not (target / "session.transition.json").exists() + assert (old / "session.state").read_text() == "suspended" + + +def test_incomplete_cleanup_without_peer_marker_is_quarantined(tmp_path): + old = _session(tmp_path, "A") + target = _session(tmp_path, "B") + profile = _profile_link(tmp_path, target) + (old / "session.state").write_text("active", encoding="utf-8") + _write_marker(target, "resume_target_prepare", {"previous_session": str(old)}) + with pytest.raises(RuntimeError, match="Absent handover peer marker"): + reconcile_active_handover(str(target), str(profile)) + assert (target / "session.transition.json").exists() + assert (old / "session.state").read_text() == "active" From f081a1209f15601a496194e7c9e125f4e80129da Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Sat, 21 Nov 2026 05:07:21 +0100 Subject: [PATCH 5/8] integration(mvp): admit source-qualified crash recovery tests into mandatory runner --- tests/test_api_contracts.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_api_contracts.py b/tests/test_api_contracts.py index 7afed32e..5ed41e79 100644 --- a/tests/test_api_contracts.py +++ b/tests/test_api_contracts.py @@ -488,7 +488,7 @@ def test_resume_session_rolls_back_state_on_broker_failure(tmp_path): with patch("api.routers.lifecycle.read_session_dir", return_value=str(current_dir)): with patch("api.routers.lifecycle.resolve_session_dir", return_value=str(target_dir)): with patch("api.routers.lifecycle.append_lifecycle_event"): - with patch("api.routers.lifecycle.link_wine_user_dir"): + with patch("api.routers.lifecycle._link_profile_checked"): with patch("api.routers.lifecycle.ensure_user_profile"): with patch( "api.routers.lifecycle.atomic_shutdown", From 4c954fa78a94af0a379afa0306e1bedc786a8dc9 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Sat, 21 Nov 2026 05:07:25 +0100 Subject: [PATCH 6/8] integration(mvp): admit source-qualified crash recovery tests into mandatory runner --- tests/test_lifecycle_hardened.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_lifecycle_hardened.py b/tests/test_lifecycle_hardened.py index 24aad16f..993931f3 100644 --- a/tests/test_lifecycle_hardened.py +++ b/tests/test_lifecycle_hardened.py @@ -22,7 +22,7 @@ def test_sessions_resume_concurrent_calls_idempotent(tmp_path): ), patch("api.routers.lifecycle.write_session_dir"): with patch("api.routers.lifecycle.write_session_state"): with patch("api.routers.lifecycle.append_lifecycle_event"): - with patch("api.routers.lifecycle.link_wine_user_dir"): + with patch("api.routers.lifecycle._link_profile_checked"): with patch("api.routers.lifecycle.ensure_user_profile"): with patch("api.routers.lifecycle.broker.update_session"): res1 = client.post( From acd9c6d21173594950082c1ef3a8c8210b1f9bc4 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Sat, 21 Nov 2026 05:07:29 +0100 Subject: [PATCH 7/8] integration(mvp): admit source-qualified crash recovery tests into mandatory runner --- scripts/ci/test.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/ci/test.sh b/scripts/ci/test.sh index 0b27b214..b2dca0f8 100755 --- a/scripts/ci/test.sh +++ b/scripts/ci/test.sh @@ -39,4 +39,5 @@ pytest \ tests/test_mvp_control_safety.py \ tests/test_mvp_control_api.py \ tests/test_mvp_mouse_lease.py \ - tests/test_mvp_inflight_cancel.py + tests/test_mvp_inflight_cancel.py \ + tests/test_handover_restart_recovery.py From 4f7f9bd194198705216fe20c399586a9355474a2 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Sat, 21 Nov 2026 05:08:51 +0100 Subject: [PATCH 8/8] ci(formal): trigger TLC for changes to broker, input and handover implementation --- .github/workflows/formal-cross-layer-tlc.yml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.github/workflows/formal-cross-layer-tlc.yml b/.github/workflows/formal-cross-layer-tlc.yml index 6bf7ad7b..fbb52287 100644 --- a/.github/workflows/formal-cross-layer-tlc.yml +++ b/.github/workflows/formal-cross-layer-tlc.yml @@ -4,6 +4,14 @@ on: pull_request: paths: - "formal/**" + - "api/core/broker.py" + - "api/core/handover_recovery.py" + - "api/routers/input.py" + - "api/routers/lifecycle.py" + - "api/server.py" + - "tests/test_mvp_control_safety.py" + - "tests/test_handover_restart_recovery.py" + - "scripts/ci/test.sh" - ".github/workflows/formal-cross-layer-tlc.yml" workflow_dispatch: