diff --git a/.github/workflows/formal-cross-layer-tlc.yml b/.github/workflows/formal-cross-layer-tlc.yml new file mode 100644 index 00000000..3d06f91c --- /dev/null +++ b/.github/workflows/formal-cross-layer-tlc.yml @@ -0,0 +1,101 @@ +name: Formal Cross-Layer Safety (TLC) + +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" + - "api/utils/files.py" + - "tests/test_invariants.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: + +permissions: + contents: read + +concurrency: + group: formal-cross-layer-${{ github.ref }} + cancel-in-progress: true + +jobs: + check-finite-state-models: + runs-on: ubuntu-24.04 + timeout-minutes: 12 + steps: + - name: Checkout public synthetic model source + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd + with: + persist-credentials: false + - name: Install pinned public TLC v1.7.4 + shell: bash + run: | + set -euo pipefail + mkdir -p "$RUNNER_TEMP/formal" + curl --fail --location --silent --show-error --retry 2 \ + --connect-timeout 15 --max-time 90 \ + https://github.com/tlaplus/tlaplus/releases/download/v1.7.4/tla2tools.jar \ + -o "$RUNNER_TEMP/formal/tla2tools.jar" + printf 'bee4a54f3ee3d4afc347c3240ec2d9e93b075104 %s\n' \ + "$RUNNER_TEMP/formal/tla2tools.jar" | sha1sum --check --status + java -version + - name: Exhaustive finite-state invariant checking + shell: bash + run: | + set -euo pipefail + cd formal/tla + for model in ControlLease SessionHandover ReleaseAdmission; do + echo "TLC_MODEL=$model" + timeout 90s java -Xmx768m -XX:+UseParallelGC \ + -cp "$RUNNER_TEMP/formal/tla2tools.jar" tlc2.TLC \ + -workers 1 -deadlock -config "$model.cfg" "$model.tla" + done + echo "FORMAL_TLC_VERDICT=PASS" + - name: Prove adversarial stale-input model is rejected by TLC + shell: bash + run: | + set -euo pipefail + cd formal/tla + if timeout 45s java -Xmx512m -XX:+UseParallelGC \ + -cp "$RUNNER_TEMP/formal/tla2tools.jar" tlc2.TLC \ + -workers 1 -deadlock -config ControlLeaseUnsafe.cfg \ + ControlLeaseUnsafe.tla > "$RUNNER_TEMP/formal/unsafe-tlc.log" 2>&1; then + echo "FORMAL_NEGATIVE_CONTROL=FAILED_TO_DETECT_STALE_INPUT" + exit 1 + fi + # A parser error or missing dependency is not a valid counterexample. + if ! grep -Fq 'Invariant NoUnauthorizedEffect is violated' \ + "$RUNNER_TEMP/formal/unsafe-tlc.log"; then + echo "FORMAL_NEGATIVE_CONTROL=NO_EXPECTED_COUNTEREXAMPLE" + exit 1 + fi + echo "FORMAL_NEGATIVE_CONTROL=STALE_INPUT_COUNTEREXAMPLE_CONFIRMED" + - name: Prove split-owner restart without reconciliation is rejected by TLC + shell: bash + run: | + set -euo pipefail + cd formal/tla + if timeout 45s java -Xmx512m -XX:+UseParallelGC \ + -cp "$RUNNER_TEMP/formal/tla2tools.jar" tlc2.TLC \ + -workers 1 -deadlock -config SessionHandoverUnsafe.cfg \ + SessionHandoverUnsafe.tla > "$RUNNER_TEMP/formal/unsafe-handover.log" 2>&1; then + echo "FORMAL_HANDOVER_NEGATIVE=FAILED_TO_DETECT_SPLIT_OWNER" + exit 1 + fi + if ! grep -Fq 'Invariant ConvergedAtRest is violated' \ + "$RUNNER_TEMP/formal/unsafe-handover.log"; then + echo "FORMAL_HANDOVER_NEGATIVE=NO_EXPECTED_COUNTEREXAMPLE" + exit 1 + fi + echo "FORMAL_HANDOVER_NEGATIVE=SPLIT_OWNER_COUNTEREXAMPLE_CONFIRMED" + - name: Run dependency-free model contract tests + shell: bash + run: | + set -euo pipefail + python3 -m unittest discover -s formal/tests -p 'test_*.py' -v diff --git a/api/core/broker.py b/api/core/broker.py index eeb02586..87ab48a0 100644 --- a/api/core/broker.py +++ b/api/core/broker.py @@ -243,6 +243,12 @@ async def set_user_intent(self, intent: UserIntent): async def check_access(self) -> bool: """Returns True if agent is allowed to execute.""" with self._lock: + # Emergency stop overrides implicit headless/agent-only grants. + # This check must run before every early-return mode shortcut. + if self.state.user_intent == UserIntent.STOP_NOW: + if self.state.control_mode == ControlMode.AGENT: + self.revoke_agent("user_stop_now") + return False if self.state.effective_control_mode == ControlPolicyMode.HUMAN_ONLY: return False if self.state.effective_control_mode == ControlPolicyMode.AGENT_ONLY: 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" 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) 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: diff --git a/api/utils/files.py b/api/utils/files.py index bf87730d..558ff44f 100644 --- a/api/utils/files.py +++ b/api/utils/files.py @@ -68,6 +68,14 @@ def _atomic_write_text(path: str, content: str) -> None: handle.flush() os.fsync(handle.fileno()) os.replace(tmp_path, path) + # fsync of the temporary file alone does not make the directory + # entry replacement durable after host power loss or filesystem + # replay. A failed directory sync must fail closed to the caller. + directory_fd = os.open(directory, os.O_RDONLY) + try: + os.fsync(directory_fd) + finally: + os.close(directory_fd) finally: if os.path.exists(tmp_path): os.unlink(tmp_path) diff --git a/formal/README.md b/formal/README.md new file mode 100644 index 00000000..d1e9d5be --- /dev/null +++ b/formal/README.md @@ -0,0 +1,59 @@ +# Formal safety integration on the qualified MVP baseline + +This stacked workstream starts at WineBot MVP PR #158 exact head +`9809519b94b9074ed681b297237f6dec89d43186`, not public main. +It reuses the public TLA+ finite-state specification and adversarial TLC +counterexample gates already qualified on draft PR #170. The contract +fixture for this MVP is `mark-e-deyoung/winebot-contracts@205666f7f0235cb0fc51ca8a5af84f9f67831a74`. + +## Why the base is important + +The public main-based conformance baseline and both main-based correction +branches produced 55 passed, 7 failed, 9 skipped tests under the same +external contract SHA; the MVP integration produced 62 passed, 0 failed, +9 skipped. The actual MVP diff contains its own control broker ownership +corrections and async input cancellation. We must not replace them with a +different main-based implementation whose assumptions and interface +disagree. PR #170 is a formal-analysis source, not an authoritative +runtime integration baseline. PR #171 remains independent and has to be +reconciled onto the MVP lifecycle code before it can be admitted. + +## Refinement map + +| Formal model | MVP source | Meaning of model PASS | Concrete gap | +| --- | --- | --- | --- | +| `ControlLease.tla` | `api/core/broker.py`, `api/routers/input.py` | Bounded stale queued epochs cannot execute after revocation in the abstract model | No durable cross-process epoch token; backends may finish already-delivered effects | +| `SessionHandover.tla` | `api/routers/lifecycle.py`, `api/server.py` | Abstract recovering owner converges | Startup has no verified persisted handover replay yet | +| `ReleaseAdmission.tla` | PR #158/#166, WinInspect-private #468 | Source, qualification, projection and pin belong to one source generation | Private C++ correction, approved projection, and native HWND qualification still blocked | + +`ControlLeaseUnsafe.tla` must produce an invariant counterexample for +stale input after STOP_NOW. `SessionHandoverUnsafe.tla` must produce a +counterexample for split ownership after crash. Expected negative-control +counterexamples are required; a parser failure or a silent checker exit +must not masquerade as success. + +## Targeted production change + +MVP #158's broker already tracks/cancels asynchronous input tasks, refuses +duplicate active leases and stale handover grant challenges, and does +a final policy check near input dispatch. Its `check_access()` nonetheless +evaluated headless and agent-only shortcuts before `STOP_NOW`. +This stacked patch moves the human emergency-stop veto ahead of every +shortcut and adds tests for newly admitted headless requests and +cancellation of an outstanding synthetic task. + +The retrofit changes no public contract assertions and introduces no +runtime actor, private source, paid resource or host-side input. + +## Qualification and custody + +- Run the imported public TLA+ v1.7.4 TLC workflow and both negative + controls on free public GitHub-hosted Ubuntu. +- Run the owning MVP lint/unit, source-provenance, real Wine workload, + disposable layer, and frozen external contract workflows. A green model + alone does not authorize release. +- Keep this PR stacked on `mvp/ic1-integration-20261117` until independently + accepted. Never merge into main or promote release without existing + native WinInspect proof obligations. +- Preserve exact source SHA, model verdict, 62/0/9 conformance comparison, + and counterexamples in DLE (Durable, Legible, Executable). diff --git a/formal/tests/test_model_contracts.py b/formal/tests/test_model_contracts.py new file mode 100644 index 00000000..d265ce6f --- /dev/null +++ b/formal/tests/test_model_contracts.py @@ -0,0 +1,129 @@ +"""Bounded deterministic negative controls for the public formal models. + +This is NOT a replacement for TLC; it tests the intended fault scenarios +independently, with synthetic data and no private source or external effects. +""" +import unittest +from collections import deque +from dataclasses import dataclass, replace + + +@dataclass(frozen=True) +class Lease: + epoch: int = 1 + granted: bool = False + stopped: bool = False + queued: int = 0 + effects: int = 0 + + +def lease_next(s: Lease): + if not s.granted and not s.stopped and s.epoch < 4: + yield "grant", replace(s, granted=True, epoch=s.epoch + 1) + if s.granted and not s.stopped and not s.queued: + yield "queue", replace(s, queued=s.epoch) + if s.granted and s.epoch < 4: + yield "stop", replace(s, granted=False, stopped=True, epoch=s.epoch + 1) + if s.stopped and not s.queued: + yield "ack", replace(s, stopped=False) + if s.queued and s.granted and not s.stopped and s.queued == s.epoch: + # Boolean observed effect, not an unbounded count: finite state space. + yield "effect", replace(s, queued=0, effects=1) + if s.queued and (not s.granted or s.stopped or s.queued != s.epoch): + yield "discard", replace(s, queued=0) + + +def explore(init, next_fn, invariant): + seen = {init} + queue = deque([(init, ())]) + while queue: + state, trace = queue.popleft() + if not invariant(state): + return trace, len(seen) + for name, successor in next_fn(state): + if successor not in seen: + seen.add(successor) + queue.append((successor, trace + (name,))) + return None, len(seen) + + +@dataclass(frozen=True) +class Handover: + phase: str = "idle" + committed: str = "A" + pointer: str = "A" + profile: str = "A" + broker: str = "A" + intent: bool = False + + +def handover_next(s: Handover): + if s.phase == "idle" and s.committed == "A": + yield "prepare", replace(s, phase="prepared", intent=True) + if s.phase == "prepared": + yield "pointer", replace(s, phase="pointer_written", pointer="B") + if s.phase == "pointer_written": + yield "profile", replace(s, phase="profile_linked", profile="B") + if s.phase == "profile_linked": + yield "broker", replace(s, phase="broker_switched", broker="B") + if s.phase == "broker_switched": + yield "commit", replace(s, phase="committed", committed="B", intent=False) + if s.phase in {"prepared", "pointer_written", "profile_linked", "broker_switched"}: + yield "crash", replace(s, phase="recovering") + if s.phase == "recovering": + yield "recover", Handover() + + +def converged_when_idle(s: Handover): + return s.phase not in {"idle", "committed"} or ( + s.pointer == s.profile == s.broker == s.committed and not s.intent + ) + + +class ModelContractTests(unittest.TestCase): + def test_lease_finite_model_has_no_nonfenced_effect(self): + counterexample, count = explore( + Lease(), + lease_next, + lambda s: s.effects >= 0 and not (s.stopped and s.granted), + ) + self.assertIsNone(counterexample) + self.assertGreater(count, 5) + + def test_stale_queued_input_is_discarded_after_stop(self): + state = Lease(epoch=2, granted=True, queued=2) + stopped = dict(lease_next(state))["stop"] + self.assertNotIn("effect", dict(lease_next(stopped))) + self.assertIn("discard", dict(lease_next(stopped))) + + def test_unfenced_negative_control_is_detected(self): + state = Lease(epoch=2, granted=True, queued=2) + stopped = dict(lease_next(state))["stop"] + # Deliberately simulate a broken dispatcher that acts on any queue. + unsafe_effect = stopped.queued > 0 + self.assertTrue(unsafe_effect) + self.assertFalse(stopped.granted) + + def test_handover_crash_at_each_precommit_step_converges(self): + current = Handover() + for action in ("prepare", "pointer", "profile", "broker"): + current = dict(handover_next(current))[action] + interrupted = dict(handover_next(current))["crash"] + recovered = dict(handover_next(interrupted))["recover"] + self.assertEqual(recovered, Handover()) + + def test_handover_bounded_model_never_claims_partial_commit(self): + counterexample, count = explore(Handover(), handover_next, converged_when_idle) + self.assertIsNone(counterexample) + self.assertGreater(count, 8) + + def test_release_requires_same_source_generation(self): + source = 2 + qualified, projected, built, pinned, approved = 1, 1, 1, 1, True + self.assertFalse( + approved and qualified == projected == built == pinned == source + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/formal/tla/ControlLease.cfg b/formal/tla/ControlLease.cfg new file mode 100644 index 00000000..97c0c91d --- /dev/null +++ b/formal/tla/ControlLease.cfg @@ -0,0 +1,3 @@ +SPECIFICATION Spec +CONSTANT MaxEpoch = 4 +INVARIANTS TypeOK NoUnauthorizedEffect NoAgentWhileStopped diff --git a/formal/tla/ControlLease.tla b/formal/tla/ControlLease.tla new file mode 100644 index 00000000..76909c56 --- /dev/null +++ b/formal/tla/ControlLease.tla @@ -0,0 +1,70 @@ +---------------------------- MODULE ControlLease ---------------------------- +EXTENDS Naturals, TLC + +\* Bounded safety model: authority revocation and queued input are separate +\* steps. The broker must fence input at EFFECT time, not just queue time. +CONSTANT MaxEpoch +ASSUME MaxEpoch \in Nat \ {0} + +VARIABLES epoch, granted, stopped, queued, lastEffect, effectWasAuthorized +vars == <> + +Init == + /\ epoch = 1 + /\ granted = FALSE + /\ stopped = FALSE + /\ queued = 0 + /\ lastEffect = 0 + /\ effectWasAuthorized = TRUE + +Grant == + /\ ~granted /\ ~stopped /\ epoch < MaxEpoch + /\ epoch' = epoch + 1 + /\ granted' = TRUE + /\ UNCHANGED <> + +QueueInput == + /\ granted /\ ~stopped /\ queued = 0 + /\ queued' = epoch + /\ UNCHANGED <> + +StopNow == + /\ granted /\ epoch < MaxEpoch + /\ epoch' = epoch + 1 + /\ granted' = FALSE + /\ stopped' = TRUE + /\ UNCHANGED <> + +AcknowledgeStop == + /\ stopped /\ queued = 0 + /\ stopped' = FALSE + /\ UNCHANGED <> + +ExecuteInput == + /\ queued # 0 /\ granted /\ ~stopped /\ queued = epoch + /\ lastEffect' = queued + /\ effectWasAuthorized' = granted /\ ~stopped /\ queued = epoch + /\ queued' = 0 + /\ UNCHANGED <> + +DiscardStale == + /\ queued # 0 /\ (~granted \/ stopped \/ queued # epoch) + /\ queued' = 0 + /\ UNCHANGED <> + +Next == Grant \/ QueueInput \/ StopNow \/ AcknowledgeStop + \/ ExecuteInput \/ DiscardStale + +Spec == Init /\ [][Next]_vars + +TypeOK == + /\ epoch \in 1..MaxEpoch + /\ granted \in BOOLEAN + /\ stopped \in BOOLEAN + /\ queued \in 0..MaxEpoch + /\ lastEffect \in 0..MaxEpoch + /\ effectWasAuthorized \in BOOLEAN + +NoUnauthorizedEffect == effectWasAuthorized +NoAgentWhileStopped == stopped => ~granted +============================================================================= diff --git a/formal/tla/ControlLeaseUnsafe.cfg b/formal/tla/ControlLeaseUnsafe.cfg new file mode 100644 index 00000000..bf0054a7 --- /dev/null +++ b/formal/tla/ControlLeaseUnsafe.cfg @@ -0,0 +1,2 @@ +SPECIFICATION Spec +INVARIANT NoUnauthorizedEffect diff --git a/formal/tla/ControlLeaseUnsafe.tla b/formal/tla/ControlLeaseUnsafe.tla new file mode 100644 index 00000000..73891041 --- /dev/null +++ b/formal/tla/ControlLeaseUnsafe.tla @@ -0,0 +1,39 @@ +------------------------ MODULE ControlLeaseUnsafe ------------------------- +\* Deliberately BROKEN negative control. TLC MUST find a counterexample: +\* queue under agent authority, STOP_NOW revokes, stale action executes anyway. +VARIABLES granted, queued, stopped, unauthorizedEffect +vars == <> + +Init == + /\ granted = FALSE + /\ queued = FALSE + /\ stopped = FALSE + /\ unauthorizedEffect = FALSE + +Grant == + /\ ~granted /\ ~stopped + /\ granted' = TRUE + /\ UNCHANGED <> + +Queue == + /\ granted /\ ~queued + /\ queued' = TRUE + /\ UNCHANGED <> + +Revoke == + /\ granted + /\ granted' = FALSE + /\ stopped' = TRUE + /\ UNCHANGED <> + +UnsafeExecute == + /\ queued + /\ unauthorizedEffect' = ~granted \/ stopped + /\ queued' = FALSE + /\ UNCHANGED <> + +Next == Grant \/ Queue \/ Revoke \/ UnsafeExecute +Spec == Init /\ [][Next]_vars + +NoUnauthorizedEffect == ~unauthorizedEffect +============================================================================= diff --git a/formal/tla/ReleaseAdmission.cfg b/formal/tla/ReleaseAdmission.cfg new file mode 100644 index 00000000..8918ac92 --- /dev/null +++ b/formal/tla/ReleaseAdmission.cfg @@ -0,0 +1,2 @@ +SPECIFICATION Spec +INVARIANTS TypeOK NoStaleAcceptedArtifact diff --git a/formal/tla/ReleaseAdmission.tla b/formal/tla/ReleaseAdmission.tla new file mode 100644 index 00000000..a1c243fc --- /dev/null +++ b/formal/tla/ReleaseAdmission.tla @@ -0,0 +1,71 @@ +------------------------- MODULE ReleaseAdmission -------------------------- +EXTENDS Naturals + +\* Abstract artifact generation IDs, not actual content digests. +\* Every evidence link must bind to the SAME exact source generation. +VARIABLES source, qualified, projected, built, pinned, approved, phase +vars == <> +Stages == {"candidate", "qualified", "projected", "built", "pinned", "accepted"} + +Init == + /\ source = 1 + /\ qualified = 0 + /\ projected = 0 + /\ built = 0 + /\ pinned = 0 + /\ approved = FALSE + /\ phase = "candidate" + +Qualify == + /\ phase = "candidate" + /\ qualified' = source + /\ phase' = "qualified" + /\ UNCHANGED <> + +ApproveAndProject == + /\ phase = "qualified" /\ qualified = source + /\ projected' = source + /\ approved' = TRUE + /\ phase' = "projected" + /\ UNCHANGED <> + +Build == + /\ phase = "projected" /\ approved /\ projected = source + /\ built' = source + /\ phase' = "built" + /\ UNCHANGED <> + +Pin == + /\ phase = "built" /\ built = source + /\ pinned' = source + /\ phase' = "pinned" + /\ UNCHANGED <> + +Accept == + /\ phase = "pinned" + /\ qualified = source /\ projected = source + /\ built = source /\ pinned = source /\ approved + /\ phase' = "accepted" + /\ UNCHANGED <> + +SourceChanges == + /\ phase # "accepted" /\ source = 1 + /\ source' = 2 + /\ approved' = FALSE + /\ phase' = "candidate" + /\ UNCHANGED <> + +Next == Qualify \/ ApproveAndProject \/ Build \/ Pin \/ Accept \/ SourceChanges +Spec == Init /\ [][Next]_vars + +TypeOK == + /\ source \in {1,2} + /\ qualified \in 0..2 /\ projected \in 0..2 + /\ built \in 0..2 /\ pinned \in 0..2 + /\ approved \in BOOLEAN /\ phase \in Stages + +NoStaleAcceptedArtifact == + (phase = "accepted") => + (approved /\ qualified = source /\ projected = source /\ + built = source /\ pinned = source) +============================================================================= diff --git a/formal/tla/SessionHandover.cfg b/formal/tla/SessionHandover.cfg new file mode 100644 index 00000000..664875ea --- /dev/null +++ b/formal/tla/SessionHandover.cfg @@ -0,0 +1,2 @@ +SPECIFICATION Spec +INVARIANTS TypeOK ConvergedAtRest NoFalseCommit diff --git a/formal/tla/SessionHandover.tla b/formal/tla/SessionHandover.tla new file mode 100644 index 00000000..85129101 --- /dev/null +++ b/formal/tla/SessionHandover.tla @@ -0,0 +1,89 @@ +-------------------------- MODULE SessionHandover --------------------------- +EXTENDS TLC + +\* Logical committed owner is distinct from tentative pointer/profile/broker. +\* Crash recovery must converge all projections back to the committed owner. +Sessions == {"A", "B"} +Phases == {"idle", "prepared", "pointer_written", "profile_linked", + "broker_switched", "committed", "recovering"} + +VARIABLES phase, committed, pointer, profile, broker, intent +vars == <> + +Init == + /\ phase = "idle" + /\ committed = "A" + /\ pointer = "A" + /\ profile = "A" + /\ broker = "A" + /\ intent = FALSE + +Prepare == + /\ phase = "idle" /\ committed = "A" + /\ phase' = "prepared" + /\ intent' = TRUE + /\ UNCHANGED <> + +WritePointer == + /\ phase = "prepared" + /\ phase' = "pointer_written" + /\ pointer' = "B" + /\ UNCHANGED <> + +LinkProfile == + /\ phase = "pointer_written" + /\ phase' = "profile_linked" + /\ profile' = "B" + /\ UNCHANGED <> + +SwitchBroker == + /\ phase = "profile_linked" + /\ phase' = "broker_switched" + /\ broker' = "B" + /\ UNCHANGED <> + +Commit == + /\ phase = "broker_switched" + /\ pointer = "B" /\ profile = "B" /\ broker = "B" + /\ committed' = "B" + /\ phase' = "committed" + /\ intent' = FALSE + /\ UNCHANGED <> + +Crash == + /\ phase \in {"prepared", "pointer_written", "profile_linked", + "broker_switched"} + /\ phase' = "recovering" + /\ UNCHANGED <> + +Recover == + /\ phase = "recovering" + /\ pointer' = committed + /\ profile' = committed + /\ broker' = committed + /\ phase' = "idle" + /\ intent' = FALSE + /\ UNCHANGED committed + +Next == Prepare \/ WritePointer \/ LinkProfile \/ SwitchBroker + \/ Commit \/ Crash \/ Recover + +Spec == Init /\ [][Next]_vars + +TypeOK == + /\ phase \in Phases + /\ committed \in Sessions + /\ pointer \in Sessions + /\ profile \in Sessions + /\ broker \in Sessions + /\ intent \in BOOLEAN + +ConvergedAtRest == + (phase \in {"idle", "committed"}) => + (pointer = committed /\ profile = committed /\ + broker = committed /\ ~intent) +NoFalseCommit == + (phase = "committed") => + (committed = "B" /\ pointer = "B" /\ + profile = "B" /\ broker = "B") +============================================================================= diff --git a/formal/tla/SessionHandoverUnsafe.cfg b/formal/tla/SessionHandoverUnsafe.cfg new file mode 100644 index 00000000..a7f35c4f --- /dev/null +++ b/formal/tla/SessionHandoverUnsafe.cfg @@ -0,0 +1,2 @@ +SPECIFICATION Spec +INVARIANT ConvergedAtRest diff --git a/formal/tla/SessionHandoverUnsafe.tla b/formal/tla/SessionHandoverUnsafe.tla new file mode 100644 index 00000000..5efebd7e --- /dev/null +++ b/formal/tla/SessionHandoverUnsafe.tla @@ -0,0 +1,37 @@ +---------------------- MODULE SessionHandoverUnsafe ---------------------- +\* Deliberately BROKEN crash-recovery model. After pointer replacement the +\* process dies, then an unprepared startup declares IDLE without reconciling +\* the profile and broker. TLC must expose a split-owner resting state. +VARIABLES phase, committed, pointer, profile, broker +vars == <> + +Init == + /\ phase = "idle" + /\ committed = "A" + /\ pointer = "A" + /\ profile = "A" + /\ broker = "A" + +Prepare == + /\ phase = "idle" + /\ phase' = "prepared" + /\ UNCHANGED <> + +WritePointer == + /\ phase = "prepared" + /\ pointer' = "B" + /\ phase' = "pointer_written" + /\ UNCHANGED <> + +CrashWithoutRecovery == + /\ phase = "pointer_written" + /\ phase' = "idle" + /\ UNCHANGED <> + +Next == Prepare \/ WritePointer \/ CrashWithoutRecovery +Spec == Init /\ [][Next]_vars + +ConvergedAtRest == + (phase = "idle") => + (pointer = committed /\ profile = committed /\ broker = committed) +============================================================================= 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 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", 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" diff --git a/tests/test_invariants.py b/tests/test_invariants.py index 74dc8ab9..9aafa73a 100644 --- a/tests/test_invariants.py +++ b/tests/test_invariants.py @@ -1,4 +1,5 @@ import os +import stat from unittest.mock import patch import pytest @@ -93,3 +94,77 @@ def test_critical_state_write_is_fail_closed(tmp_path): with patch("api.utils.files.os.replace", side_effect=OSError("disk failure")): with pytest.raises(OSError): write_session_state(str(session_dir), "active") + + +def test_atomic_session_state_fsyncs_file_then_directory(tmp_path): + """Success means both data and the new directory entry were synced.""" + session_dir = tmp_path / "session" + session_dir.mkdir() + real_fsync = os.fsync + fsync_targets = [] + + def instrument(fd): + fsync_targets.append("dir" if stat.S_ISDIR(os.fstat(fd).st_mode) else "file") + return real_fsync(fd) + + with patch("api.utils.files.os.fsync", side_effect=instrument): + write_session_state(str(session_dir), "active") + + assert fsync_targets == ["file", "dir"] + assert (session_dir / "session.state").read_text(encoding="utf-8") == "active" + + +def test_atomic_session_state_directory_fsync_failure_is_not_acknowledged(tmp_path): + """A renamed-but-uncommitted file must raise rather than report success.""" + session_dir = tmp_path / "session" + session_dir.mkdir() + real_fsync = os.fsync + + def directory_fail(fd): + if stat.S_ISDIR(os.fstat(fd).st_mode): + raise OSError("directory sync rejected") + return real_fsync(fd) + + with patch("api.utils.files.os.fsync", side_effect=directory_fail): + with pytest.raises(OSError, match="directory sync rejected"): + write_session_state(str(session_dir), "active") + # The rename may have occurred before the durability failure; callers + # must reconcile the on-disk state rather than assume rollback. + assert list(session_dir.glob("tmp-*")) == [] + + +def test_atomic_current_session_pointer_fsyncs_parent(tmp_path): + """The authoritative active-session pointer must persist its rename.""" + from api.utils import files + + pointer_file = tmp_path / "active-session" + real_fsync = os.fsync + fsync_targets = [] + + def instrument(fd): + fsync_targets.append("dir" if stat.S_ISDIR(os.fstat(fd).st_mode) else "file") + return real_fsync(fd) + + with ( + patch.object(files, "SESSION_FILE", str(pointer_file)), + patch.object(files, "set_current_session_dir"), + patch("api.utils.files.os.fsync", side_effect=instrument), + ): + files.write_session_dir(str(tmp_path / "synthetic-A")) + + assert fsync_targets == ["file", "dir"] + assert pointer_file.read_text(encoding="utf-8") == str(tmp_path / "synthetic-A") + + +def test_atomic_failed_replace_keeps_old_session_state_and_removes_temp(tmp_path): + session_dir = tmp_path / "synthetic" + session_dir.mkdir() + state_file = session_dir / "session.state" + state_file.write_text("suspended", encoding="utf-8") + + with patch("api.utils.files.os.replace", side_effect=OSError("replace interrupted")): + with pytest.raises(OSError, match="replace interrupted"): + write_session_state(str(session_dir), "active") + + assert state_file.read_text(encoding="utf-8") == "suspended" + assert sorted(p.name for p in session_dir.iterdir()) == ["session.state"] 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( diff --git a/tests/test_mvp_control_safety.py b/tests/test_mvp_control_safety.py index c8609f0d..285a06d3 100644 --- a/tests/test_mvp_control_safety.py +++ b/tests/test_mvp_control_safety.py @@ -12,7 +12,7 @@ from fastapi import HTTPException from api.core.broker import InputBroker -from api.core.models import ControlMode, UserIntent +from api.core.models import ControlMode, ControlPolicyMode, UserIntent def _broker() -> InputBroker: @@ -110,3 +110,56 @@ def test_active_agent_lease_is_revoked_across_session_handover(): assert state.control_mode == ControlMode.USER assert state.lease_expiry is None assert asyncio.run(b.check_access()) is False + + +@pytest.mark.parametrize( + "policy", + [ControlPolicyMode.HYBRID, ControlPolicyMode.AGENT_ONLY], +) +def test_stop_now_is_absolute_veto_in_headless_policy_modes(policy): + """A fresh request after emergency stop cannot use implicit access.""" + with patch("api.core.broker.get_instance_control_mode", return_value="hybrid"): + b = InputBroker() + with b._lock: + b.state.interactive = False + b.state.control_mode = ControlMode.AGENT + b.state.effective_control_mode = policy + assert asyncio.run(b.check_access()) is True + + asyncio.run(b.set_user_intent(UserIntent.STOP_NOW)) + assert b.get_state().control_mode == ControlMode.USER + assert asyncio.run(b.check_access()) is False + # Even switching policy after STOP_NOW must not resurrect access. + asyncio.run(b.set_session_control_mode(ControlPolicyMode.AGENT_ONLY)) + assert asyncio.run(b.check_access()) is False + with pytest.raises(HTTPException) as stopped: + token = asyncio.run(b.issue_grant_challenge())["token"] + asyncio.run(b.grant_agent(30, user_ack=True, challenge_token=token)) + assert stopped.value.status_code == 403 + + +def test_stop_now_cancels_tracked_async_input_in_headless_mode(): + """Fail-stop semantics also apply to already-admitted async input waits.""" + async def exercise(): + with patch("api.core.broker.get_instance_control_mode", return_value="hybrid"): + b = InputBroker() + with b._lock: + b.state.interactive = False + b.state.control_mode = ControlMode.AGENT + b.state.effective_control_mode = ControlPolicyMode.AGENT_ONLY + started = asyncio.Event() + + async def held(): + with b.track_async_input(): + started.set() + await asyncio.Event().wait() + + task = asyncio.create_task(held()) + await asyncio.wait_for(started.wait(), timeout=2) + await b.set_user_intent(UserIntent.STOP_NOW) + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(task, timeout=2) + assert not b._active_async_input + assert not await b.check_access() + + asyncio.run(exercise())