Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
f944dec
fix(mvp-control): STOP_NOW veto precedes headless and agent-only acce…
mark-e-deyoung Nov 21, 2026
99a44aa
test(mvp-control): emergency STOP_NOW veto and input cancellation in …
mark-e-deyoung Nov 21, 2026
9674d0f
formal(mvp): reuse previously qualified bounded TLC model and adversa…
mark-e-deyoung Nov 21, 2026
3dd337b
formal(mvp): reuse previously qualified bounded TLC model and adversa…
mark-e-deyoung Nov 21, 2026
cf83167
formal(mvp): reuse previously qualified bounded TLC model and adversa…
mark-e-deyoung Nov 21, 2026
765f694
formal(mvp): reuse previously qualified bounded TLC model and adversa…
mark-e-deyoung Nov 21, 2026
fba5155
formal(mvp): reuse previously qualified bounded TLC model and adversa…
mark-e-deyoung Nov 21, 2026
694f695
formal(mvp): reuse previously qualified bounded TLC model and adversa…
mark-e-deyoung Nov 21, 2026
66f69ed
formal(mvp): reuse previously qualified bounded TLC model and adversa…
mark-e-deyoung Nov 21, 2026
8cac538
formal(mvp): reuse previously qualified bounded TLC model and adversa…
mark-e-deyoung Nov 21, 2026
dc4cc06
formal(mvp): transplant qualified TLC safety harness
mark-e-deyoung Nov 21, 2026
c087b0c
formal(mvp): transplant qualified TLC safety harness
mark-e-deyoung Nov 21, 2026
ac3c231
formal(mvp): transplant qualified TLC safety harness
mark-e-deyoung Nov 21, 2026
ec6d67e
formal(mvp): transplant qualified TLC safety harness
mark-e-deyoung Nov 21, 2026
d254dd9
docs(formal): reconcile authority and refinement with qualified MVP b…
mark-e-deyoung Nov 21, 2026
2dabffc
integration: add tested fail-closed handover recovery on formal MVP
mark-e-deyoung Nov 21, 2026
3274232
integration: apply individually green MVP crash-recovery changes atop…
mark-e-deyoung Nov 21, 2026
a3623e0
integration: apply individually green MVP crash-recovery changes atop…
mark-e-deyoung Nov 21, 2026
bde9bf4
integration: apply individually green MVP crash-recovery changes atop…
mark-e-deyoung Nov 21, 2026
4cc3f44
integration: apply individually green MVP crash-recovery changes atop…
mark-e-deyoung Nov 21, 2026
3511a0c
integration: add tested fail-closed handover recovery on formal MVP
mark-e-deyoung Nov 21, 2026
9a13d8b
fix(integration): admit final verified resume test seam from green re…
mark-e-deyoung Nov 21, 2026
b44f212
ci(formal): trigger TLC when production broker, lifecycle, recovery o…
mark-e-deyoung Nov 21, 2026
3cdfdc2
fix(mvp): integrate durable metadata commit and formal CI triggers
mark-e-deyoung Nov 21, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 101 additions & 0 deletions .github/workflows/formal-cross-layer-tlc.yml
Original file line number Diff line number Diff line change
@@ -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
6 changes: 6 additions & 0 deletions api/core/broker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
135 changes: 135 additions & 0 deletions api/core/handover_recovery.py
Original file line number Diff line number Diff line change
@@ -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"
53 changes: 46 additions & 7 deletions api/routers/lifecycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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}")
Expand Down Expand Up @@ -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"
Expand All @@ -1013,16 +1034,34 @@ 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,
target_dir=target_dir,
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)
Expand Down
6 changes: 6 additions & 0 deletions api/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
8 changes: 8 additions & 0 deletions api/utils/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading