From e0c76edbd1344aaa63df38162ffcf35bb5f8f667 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:37:48 +0100 Subject: [PATCH 01/29] formal: model lease fencing and STOP_NOW concurrent input --- formal/tla/ControlLease.tla | 70 +++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 formal/tla/ControlLease.tla 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 +============================================================================= From c5dc040eb2b0e2c7ac414d01e4a1822711697618 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:38:08 +0100 Subject: [PATCH 02/29] formal: specify crash-recoverable cross-layer session handover --- formal/tla/SessionHandover.tla | 89 ++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 formal/tla/SessionHandover.tla 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") +============================================================================= From c91e1f7901765824632e6e75a77300ff344235a8 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:38:25 +0100 Subject: [PATCH 03/29] formal: bind private qualification projection binary and consumer pin --- formal/tla/ReleaseAdmission.tla | 71 +++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 formal/tla/ReleaseAdmission.tla 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) +============================================================================= From 8d6cd270e69b32b3a342370bd27f3c81890feb25 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:38:34 +0100 Subject: [PATCH 04/29] formal: configure bounded TLC invariants for ControlLease.cfg --- formal/tla/ControlLease.cfg | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 formal/tla/ControlLease.cfg 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 From 1c0120e1b80aa87e03bab4b39c69b3d0770b30d8 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:38:36 +0100 Subject: [PATCH 05/29] formal: configure bounded TLC invariants for SessionHandover.cfg --- formal/tla/SessionHandover.cfg | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 formal/tla/SessionHandover.cfg 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 From 008fe0c7eead03e1903eb7d6e13529ac586cdea3 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:38:38 +0100 Subject: [PATCH 06/29] formal: configure bounded TLC invariants for ReleaseAdmission.cfg --- formal/tla/ReleaseAdmission.cfg | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 formal/tla/ReleaseAdmission.cfg 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 From 505ce980a4efb0205ee425c458dea67e41748281 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:39:15 +0100 Subject: [PATCH 07/29] ci(formal): bounded TLC on free public GitHub Actions with pinned tool hash --- .github/workflows/formal-cross-layer-tlc.yml | 54 ++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 .github/workflows/formal-cross-layer-tlc.yml diff --git a/.github/workflows/formal-cross-layer-tlc.yml b/.github/workflows/formal-cross-layer-tlc.yml new file mode 100644 index 00000000..9271bd45 --- /dev/null +++ b/.github/workflows/formal-cross-layer-tlc.yml @@ -0,0 +1,54 @@ +name: Formal Cross-Layer Safety (TLC) + +on: + pull_request: + paths: + - "formal/**" + - ".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: Run dependency-free model contract tests + shell: bash + run: | + set -euo pipefail + python3 -m unittest discover -s formal/tests -p 'test_*.py' -v From 423c781fc51d1fbead5c2f14929f436b0a238687 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:39:51 +0100 Subject: [PATCH 08/29] test(formal): bounded crash, stale lease and artifact mutation negative controls --- formal/tests/test_model_contracts.py | 128 +++++++++++++++++++++++++++ 1 file changed, 128 insertions(+) create mode 100644 formal/tests/test_model_contracts.py diff --git a/formal/tests/test_model_contracts.py b/formal/tests/test_model_contracts.py new file mode 100644 index 00000000..050f9bd5 --- /dev/null +++ b/formal/tests/test_model_contracts.py @@ -0,0 +1,128 @@ +"""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: + yield "effect", replace(s, queued=0, effects=s.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() From f994565302d7222d582bceff899e33412eaa073f Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:40:36 +0100 Subject: [PATCH 09/29] docs(formal): map bounded state machines to actual cross-layer code and DLE gates --- formal/README.md | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 formal/README.md diff --git a/formal/README.md b/formal/README.md new file mode 100644 index 00000000..795835b2 --- /dev/null +++ b/formal/README.md @@ -0,0 +1,39 @@ +# Cross-layer formal verification — first public-safe execution slice + +**Authority:** `SemperSupra/WineBot` source and owning MVP DLE PR #158. **Status:** candidate; TLC/CI evidence required before acceptance. This is not a runtime fix and does not qualify private WinInspect. + +## Actual system boundaries + +| Model | Source surfaces | Atomicity problem | Acceptance property | +| --- | --- | --- | --- | +| `ControlLease.tla` | `api/core/broker.py`, `api/routers/input.py`, brokered WinInspect input | check-permission vs later physical input | an old queued epoch is discarded after STOP_NOW/revocation | +| `SessionHandover.tla` | `api/routers/lifecycle.py`, `api/utils/files.py`, Wine profile link, broker | separately written pointer, profile symlink, session state, broker | crash recovery converges all ownership projections to committed session | +| `ReleaseAdmission.tla` | private WinInspect #468, approved projection receipt, public product binary, WineBot #166 | source/evidence/artifact/consumer-pin mismatch | accepted source generation matches qualification, projection, build and consumer pin | + +The models intentionally do **not** assert that the current production implementation satisfies these properties. The existing `asyncio.Lock` and `threading.RLock` are in-process protections, not host/guest or crash-atomic transactions. `api/core/operations.py` is memory-only and can lose operation state on process restart. The session transition marker is a stepwise journal, not an end-to-end atomic commit. Input checking and input effect require an independently proven fencing point. + +## Method and execution + +- Start with finite explicit-state TLA+ safety models checked by TLC, one worker and short bounded execution per model, in the existing **public repository** on free public GitHub-hosted Ubuntu. No local/sovereign runner admission, no private source or secrets, and no paid private Actions minutes. +- TLA+ v1.7.4 `tla2tools.jar` is pinned by exact release URL **and release-published SHA-1**. SHA-1 is only a published legacy release checksum: before treating this as a production supply-chain attestation, pin a stronger independently trusted SHA-256 or signed provenance. This check verifies the known release asset, not source authenticity. +- Run `ControlLease`, `SessionHandover`, and `ReleaseAdmission` TLC invariants in one bounded static workflow. A nonzero exit, missing jar, timeout, TLA+ syntax error, state-invariant counterexample, or negative-control test failure must fail CI. +- Run separate stdlib Python fault/negative controls to ensure stale queued input and interrupted handover are detectable, and a stale artifact tuple is refused. These are scenario-level independent checks, **not** proofs against the implementation. +- Require real source-code mapping and fault injection before marking any product behavior verified. Future phases: broker epoch/fencing point; handover intent+reconciliation startup; durable operations; recording commit/replay; atomic release authority. + +## Required invariants + +**Control:** STOP_NOW invalidates queued older epochs; no agent effect may execute on an expired/superseded lease. One authoritative grant epoch; no assumption that an API's prior check atomically covers external Wine effects. + +**Handover:** Only one committed session owner; after a successful commit or recovery all pointer/profile/broker projections converge; a crash mid-handover is either safely compensated or an incomplete operation is visibly recoverable. No silently succeeded partial handover. + +**Release:** Every admission binds exact private source generation, reviewed projection, independently qualified public binary and WineBot consumer pin. Changing any upstream component invalidates downstream acceptance until requalified. + +## State-machine scope limits and next implementation batch + +This first slice deliberately abstracts remote processes and filesystem details into boolean or finite states and does not prove cross-process fencing, directory fsync, durable credentials, actual Windows Wine11 behavior, or read-only HWND identity. TLC proves only the bounded model and modeled transitions. A known-good TLC result must never be reported as WinInspect #468 C++ CTest PASS or MVP release admission. + +Next implement a trace adapter from real `api/routers/lifecycle.py` checkpoints and `api/core/broker.py` to the modeled actions; inject restart/kill between `write_session_dir`, `link_wine_user_dir`, `write_session_state` and `broker.update_session` on disposable synthetic fixtures; check post-restart convergence. Test two concurrent grant/revoke/STOP_NOW actors with delayed input commit and a generation token. Never enable actual unsafe agent input as a negative control. + +## Evidence and DLE reconciliation + +Every run must record GitHub workflow run/job and commit SHA, TLC tool version/hash, `Spec` and invariant names, distinct/generated states, first counterexample if any, actual unit test result, and whether the verdict is `MODEL_PASS`, `MODEL_FAIL`, `NOT_RUN`, or `PRODUCT_UNQUALIFIED`. The public workflow emits fixed synthetic diagnostic markers only. Follow PR #158 and the formal-work PR for source lineage, reviews, and closure; no new scheduler or second authoritative workset. From 3f10971cba94fa73d357752e783aa694a0487d98 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:43:00 +0100 Subject: [PATCH 10/29] fix(formal): bound effect observation so BFS state space terminates --- formal/tests/test_model_contracts.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/formal/tests/test_model_contracts.py b/formal/tests/test_model_contracts.py index 050f9bd5..d265ce6f 100644 --- a/formal/tests/test_model_contracts.py +++ b/formal/tests/test_model_contracts.py @@ -27,7 +27,8 @@ def lease_next(s: Lease): 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: - yield "effect", replace(s, queued=0, effects=s.effects + 1) + # 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) From cd59c6cb5b6efbf86939d25d50fa68785c37b44d Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:45:32 +0100 Subject: [PATCH 11/29] formal(red-team): explicit stale-queue input model that TLC must reject --- formal/tla/ControlLeaseUnsafe.tla | 39 +++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 formal/tla/ControlLeaseUnsafe.tla 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 +============================================================================= From 1bbbeb079bb5e5d562bcf06a4610a70914e8dd02 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:45:40 +0100 Subject: [PATCH 12/29] formal(red-team): invariant expecting concrete stale-input counterexample --- formal/tla/ControlLeaseUnsafe.cfg | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 formal/tla/ControlLeaseUnsafe.cfg 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 From 484c7a61f32eeafbf0685be8c4794c8eaae7c8c3 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:45:57 +0100 Subject: [PATCH 13/29] ci(formal): demand TLC counterexample for unguarded queued input --- .github/workflows/formal-cross-layer-tlc.yml | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/.github/workflows/formal-cross-layer-tlc.yml b/.github/workflows/formal-cross-layer-tlc.yml index 9271bd45..aea4bb4a 100644 --- a/.github/workflows/formal-cross-layer-tlc.yml +++ b/.github/workflows/formal-cross-layer-tlc.yml @@ -47,6 +47,25 @@ jobs: -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: Run dependency-free model contract tests shell: bash run: | From 951640c02eacc2e7e7a91ff51c16269ea77ead49 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:46:22 +0100 Subject: [PATCH 14/29] docs(formal): record unguarded-input negative control and source refinement gap --- formal/README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/formal/README.md b/formal/README.md index 795835b2..1837735d 100644 --- a/formal/README.md +++ b/formal/README.md @@ -20,6 +20,10 @@ The models intentionally do **not** assert that the current production implement - Run separate stdlib Python fault/negative controls to ensure stale queued input and interrupted handover are detectable, and a stale artifact tuple is refused. These are scenario-level independent checks, **not** proofs against the implementation. - Require real source-code mapping and fault injection before marking any product behavior verified. Future phases: broker epoch/fencing point; handover intent+reconciliation startup; durable operations; recording commit/replay; atomic release authority. +## Adversarial model-checker sentinel + +`ControlLeaseUnsafe.tla` intentionally models the check-to-effect hazard: an agent queues input while authorized, then STOP_NOW revokes authority, but an unchecked consumer still executes the queued action. The dedicated CI negative-control step **must receive a TLC counterexample for `NoUnauthorizedEffect`**; parser errors, timeouts or unexpected successful model checks fail the build instead. This sentinel does not prove an exploitable live dispatch, only that the formal oracle rejects the bad ordering. Source review of `api/routers/input.py` shows `broker.check_access()` before later `await run_async_command()` or `await _send_keys()`; no generation token accompanies that eventual effect. Qualify an actual commit-time fencing fix separately with controlled synthetic input. + ## Required invariants **Control:** STOP_NOW invalidates queued older epochs; no agent effect may execute on an expired/superseded lease. One authoritative grant epoch; no assumption that an API's prior check atomically covers external Wine effects. From fd6b7b10e5c6d5fa2270ca4134a315120f376935 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:52:27 +0100 Subject: [PATCH 15/29] test(formal): capture real input route check-to-effect race with synthetic STOP_NOW interleaving --- tests/test_input_revocation_interleaving.py | 63 +++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 tests/test_input_revocation_interleaving.py diff --git a/tests/test_input_revocation_interleaving.py b/tests/test_input_revocation_interleaving.py new file mode 100644 index 00000000..66b1ae8b --- /dev/null +++ b/tests/test_input_revocation_interleaving.py @@ -0,0 +1,63 @@ +"""Deterministic red-team witness of the current input check-to-effect race. + +This records existing behavior without injecting a real mouse event. It is a +known-unsafe witness, not a green assertion that production is fenced. +""" +import asyncio +import time +from unittest.mock import patch + +from api.core.broker import InputBroker +from api.core.models import ClickModel, ControlMode, ControlPolicyMode, UserIntent +from api.routers import input as input_router + + +def test_stop_now_between_window_search_and_click_exposes_unfenced_effect(): + async def exercise(): + admitted = asyncio.Event() + release_search = asyncio.Event() + observed = [] + broker = InputBroker() + broker.state.interactive = True + broker.state.control_mode = ControlMode.AGENT + broker.state.effective_control_mode = ControlPolicyMode.HYBRID + broker.state.user_intent = UserIntent.WAIT + broker.state.lease_expiry = time.time() + 60 + + async def synthetic_command(command, **_kwargs): + if "search" in command: + admitted.set() + await asyncio.wait_for(release_search.wait(), timeout=3) + return {"ok": True, "stdout": "42", "stderr": ""} + if "click" in command: + observed.append((tuple(command), broker.get_state().user_intent)) + return {"ok": True, "stdout": "42", "stderr": ""} + + with ( + patch.object(input_router, "broker", broker), + patch.object(input_router, "run_async_command", side_effect=synthetic_command), + patch.object(input_router, "_require_active_session", return_value="/tmp/synthetic"), + patch.object(input_router, "append_input_event"), + patch.object(input_router, "append_trace_event"), + patch.object(input_router, "emit_operation_timing"), + ): + task = asyncio.create_task( + input_router.click_at( + ClickModel(x=1, y=1, window_title="Synthetic") + ) + ) + await asyncio.wait_for(admitted.wait(), timeout=3) + await broker.set_user_intent(UserIntent.STOP_NOW) + assert not await broker.check_access() + release_search.set() + result = await asyncio.wait_for(task, timeout=3) + + return observed, result + + observed, result = asyncio.run(exercise()) + # RED witness: input effect occurred after STOP_NOW had revoked access. + # Replace this expected failure scenario with a rejection assertion once + # the real input dispatcher is epoch-fenced at its effect boundary. + assert len(observed) == 1 + assert observed[0][1] == UserIntent.STOP_NOW + assert result["status"] == "clicked" From 4254bc4fabe498e75ee7f95f46a694810aaf5669 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:53:39 +0100 Subject: [PATCH 16/29] docs(formal): map real click-route interleaving witness to future effect-fencing contract --- formal/README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/formal/README.md b/formal/README.md index 1837735d..64f28694 100644 --- a/formal/README.md +++ b/formal/README.md @@ -41,3 +41,9 @@ Next implement a trace adapter from real `api/routers/lifecycle.py` checkpoints ## Evidence and DLE reconciliation Every run must record GitHub workflow run/job and commit SHA, TLC tool version/hash, `Spec` and invariant names, distinct/generated states, first counterexample if any, actual unit test result, and whether the verdict is `MODEL_PASS`, `MODEL_FAIL`, `NOT_RUN`, or `PRODUCT_UNQUALIFIED`. The public workflow emits fixed synthetic diagnostic markers only. Follow PR #158 and the formal-work PR for source lineage, reviews, and closure; no new scheduler or second authoritative workset. + +## Concrete route interleaving — first code-to-model refinement + +The source-owned test `tests/test_input_revocation_interleaving.py` uses the production `click_at` coroutine and real `InputBroker` but replaces X11 execution with a pure synthetic command fixture. A barrier suspends the window lookup **after** the first broker permission check, performs real broker `STOP_NOW` revocation and confirms access denied, then allows the route to complete. It asserts the known-bad current behavior: one later click command is still requested while `STOP_NOW` is active. This is a **red-team witness**, deliberately green only when the defect is reproducible; it must be converted into a safety assertion when the mitigation is introduced. It does not simulate a physical input event, prove an OS-level exploit, or certify a solution. + +**Remediation contract:** Each asynchronous input request needs a session-scoped immutable authority token / generation, effective expiry, and a consumer-side enforcement point as close to the external effect as possible. A second check in an API route alone narrows but does not close the TOCTOU window if the called backend asynchronously queues unguarded work. Test human STOP_NOW, ordinary user override, lease expiry, session handover, delayed backend starts, process crash/restart, and possible already-in-flight input, including explicit semantics for actions that cannot be recalled. Do not make `STOP_NOW` wait indefinitely for a long-running input process. First materialize a fenced dispatcher in a separate controlled patch with safe mock effects, then qualify real native backends independently. From a3a3a6bd6dc8c15c2444a8be780fe352461fcc2f Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:55:22 +0100 Subject: [PATCH 17/29] docs(formal): pinpoint missing restart reconciliation for handover intent marker --- formal/README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/formal/README.md b/formal/README.md index 64f28694..e7d3f048 100644 --- a/formal/README.md +++ b/formal/README.md @@ -47,3 +47,7 @@ Every run must record GitHub workflow run/job and commit SHA, TLC tool version/h The source-owned test `tests/test_input_revocation_interleaving.py` uses the production `click_at` coroutine and real `InputBroker` but replaces X11 execution with a pure synthetic command fixture. A barrier suspends the window lookup **after** the first broker permission check, performs real broker `STOP_NOW` revocation and confirms access denied, then allows the route to complete. It asserts the known-bad current behavior: one later click command is still requested while `STOP_NOW` is active. This is a **red-team witness**, deliberately green only when the defect is reproducible; it must be converted into a safety assertion when the mitigation is introduced. It does not simulate a physical input event, prove an OS-level exploit, or certify a solution. **Remediation contract:** Each asynchronous input request needs a session-scoped immutable authority token / generation, effective expiry, and a consumer-side enforcement point as close to the external effect as possible. A second check in an API route alone narrows but does not close the TOCTOU window if the called backend asynchronously queues unguarded work. Test human STOP_NOW, ordinary user override, lease expiry, session handover, delayed backend starts, process crash/restart, and possible already-in-flight input, including explicit semantics for actions that cannot be recalled. Do not make `STOP_NOW` wait indefinitely for a long-running input process. First materialize a fenced dispatcher in a separate controlled patch with safe mock effects, then qualify real native backends independently. + +## Session-handover recovery evidence (source review) + +In current public `api/routers/lifecycle.py`, `_write_transition_marker` writes `session.transition.json` during resume and `_clear_transition_marker` removes it after completion or caught exception. A direct source search of this file found marker writes/removals and no recovery reader of the marker at startup. The exception rollback tries to restore selected session pointer/state, but a process termination after `write_session_dir` and before profile linkage / broker update never reaches the exception handler. Thus a marker alone is not a proven restart-reconciliation protocol. Before accepting a change, add a reader/validator for the durable intent (schema, owner generation, previous and target identity), recover to a single authoritative owner on startup, and make crash injection exercise each physical write boundary and directory-sync durability. This is a code-inspection finding, not proof of an observed production crash or data loss. From c0fd1c2ee4d269ac78701401368fb766d040e13c Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:59:21 +0100 Subject: [PATCH 18/29] formal(red-team): crash-split ownership negative-control SessionHandoverUnsafe.tla --- formal/tla/SessionHandoverUnsafe.tla | 37 ++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 formal/tla/SessionHandoverUnsafe.tla 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) +============================================================================= From ee9f292b872a67dfcb88f61ea0ebdd0e41a749a0 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:59:24 +0100 Subject: [PATCH 19/29] formal(red-team): crash-split ownership negative-control SessionHandoverUnsafe.cfg --- formal/tla/SessionHandoverUnsafe.cfg | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 formal/tla/SessionHandoverUnsafe.cfg 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 From 8e6bdaa9a5d10f1f9b3838e4c6b392fe27c2a834 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:59:47 +0100 Subject: [PATCH 20/29] ci(formal): prove crash-split session owner invariant violation --- .github/workflows/formal-cross-layer-tlc.yml | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/.github/workflows/formal-cross-layer-tlc.yml b/.github/workflows/formal-cross-layer-tlc.yml index aea4bb4a..6bf7ad7b 100644 --- a/.github/workflows/formal-cross-layer-tlc.yml +++ b/.github/workflows/formal-cross-layer-tlc.yml @@ -66,6 +66,24 @@ jobs: 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: | From 1790ced4696a460e58a7f1efd72cb337f89a2d77 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:00:01 +0100 Subject: [PATCH 21/29] docs(formal): classify crash-split owner negative-control and refinement obligation --- formal/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/formal/README.md b/formal/README.md index e7d3f048..47960f6d 100644 --- a/formal/README.md +++ b/formal/README.md @@ -24,6 +24,8 @@ The models intentionally do **not** assert that the current production implement `ControlLeaseUnsafe.tla` intentionally models the check-to-effect hazard: an agent queues input while authorized, then STOP_NOW revokes authority, but an unchecked consumer still executes the queued action. The dedicated CI negative-control step **must receive a TLC counterexample for `NoUnauthorizedEffect`**; parser errors, timeouts or unexpected successful model checks fail the build instead. This sentinel does not prove an exploitable live dispatch, only that the formal oracle rejects the bad ordering. Source review of `api/routers/input.py` shows `broker.check_access()` before later `await run_async_command()` or `await _send_keys()`; no generation token accompanies that eventual effect. Qualify an actual commit-time fencing fix separately with controlled synthetic input. +`SessionHandoverUnsafe.tla` is the companion crash-recovery negative control. It changes only the active-session pointer, crashes, then incorrectly declares the system idle without replay or compensation. TLC must find a `ConvergedAtRest` counterexample, distinguishing a source model with an actual recovery transition from one that simply assumes a clean restart. This still does not prove the Python implementation can recover; its observed marker readback/replay mechanism must be built and tested separately. + ## Required invariants **Control:** STOP_NOW invalidates queued older epochs; no agent effect may execute on an expired/superseded lease. One authoritative grant epoch; no assumption that an API's prior check atomically covers external Wine effects. From 4070e62bb2ba8cce333520d46345e133a0637a0a Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:30:21 +0100 Subject: [PATCH 22/29] fix(control): epoch-fence queued input admission across grant revoke and session transitions --- api/core/broker.py | 34 +++++++++++++++++++++++++++++----- 1 file changed, 29 insertions(+), 5 deletions(-) diff --git a/api/core/broker.py b/api/core/broker.py index d9af37ea..2955e938 100644 --- a/api/core/broker.py +++ b/api/core/broker.py @@ -31,6 +31,7 @@ def __init__(self): self.last_agent_activity = 0.0 self._grant_challenge_token = None self._grant_challenge_expiry = 0.0 + self._authority_epoch = 1 @property def last_activity(self) -> float: @@ -53,6 +54,7 @@ def _compute_effective_mode(self) -> ControlPolicyMode: async def set_instance_control_mode(self, mode: ControlPolicyMode): with self._lock: + self._authority_epoch += 1 self.state.instance_control_mode = mode self.state.effective_control_mode = self._compute_effective_mode() if self.state.effective_control_mode == ControlPolicyMode.AGENT_ONLY: @@ -71,6 +73,7 @@ async def issue_grant_challenge(self, ttl_seconds: int = 30) -> dict: async def set_session_control_mode(self, mode: ControlPolicyMode): with self._lock: + self._authority_epoch += 1 self.state.session_control_mode = mode self.state.effective_control_mode = self._compute_effective_mode() if self.state.effective_control_mode == ControlPolicyMode.AGENT_ONLY: @@ -86,6 +89,7 @@ async def update_session( session_control_mode: ControlPolicyMode = ControlPolicyMode.HYBRID, ): with self._lock: + self._authority_epoch += 1 self.state.session_id = session_id self.state.interactive = interactive self.state.instance_control_mode = ControlPolicyMode(get_instance_control_mode()) @@ -140,6 +144,7 @@ async def grant_agent( ) if not self.state.interactive: return # Always implicit in non-interactive + self._authority_epoch += 1 self.state.control_mode = ControlMode.AGENT self.state.lease_expiry = time.time() + lease_seconds self.state.user_intent = UserIntent.WAIT @@ -152,14 +157,17 @@ async def renew_agent(self, lease_seconds: int): ) if self.state.user_intent == UserIntent.STOP_NOW: raise HTTPException(status_code=403, detail="User requested STOP_NOW") + self._authority_epoch += 1 self.state.lease_expiry = time.time() + lease_seconds def revoke_agent(self, reason: str): - # Sync version for internal calls - self.state.control_mode = ControlMode.USER - self.state.lease_expiry = None - self.state.agent_status = AgentStatus.STOPPING - print(f"Broker: Agent revoked ({reason})") + # RLock is reentrant for callers already holding the state lock. + with self._lock: + self._authority_epoch += 1 + self.state.control_mode = ControlMode.USER + self.state.lease_expiry = None + self.state.agent_status = AgentStatus.STOPPING + print(f"Broker: Agent revoked ({reason})") async def report_user_activity(self): with self._lock: @@ -196,6 +204,22 @@ async def check_access(self) -> bool: return False return True + async def issue_input_ticket(self) -> int | None: + """Capture current authority generation for one pending input action.""" + with self._lock: + if not await self.check_access(): + return None + return self._authority_epoch + + async def validate_input_ticket(self, ticket: int) -> bool: + """Reject queued work after control/session changes or lease expiry. + + Admission is immediately before backend invocation; it cannot stop an + external process already running. Consumer-side fencing remains needed. + """ + with self._lock: + return ticket == self._authority_epoch and await self.check_access() + def get_state(self) -> ControlState: # Return a detached snapshot so callers cannot mutate shared broker state. with self._lock: From c8366f194bccec8d580c3cfd96cc9cf0b6f9ceb4 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:30:37 +0100 Subject: [PATCH 23/29] fix(input): revalidate generation ticket at mouse and key backend admission --- api/routers/input.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/api/routers/input.py b/api/routers/input.py index 8aa2eab4..db8ed56e 100644 --- a/api/routers/input.py +++ b/api/routers/input.py @@ -353,7 +353,8 @@ def input_events( async def click_at(data: ClickModel): """Click at coordinates (x, y).""" op_started = time.perf_counter() - if not await broker.check_access(): + authority_ticket = await broker.issue_input_ticket() + if authority_ticket is None: raise HTTPException(status_code=423, detail="Agent control denied by policy") await broker.report_agent_activity() @@ -435,6 +436,10 @@ async def click_at(data: ClickModel): cmd.extend(["click", str(data.button)]) + # Do not execute an action queued before STOP_NOW, lease expiry, or + # session handover. This is admission fencing, not an OS-level kill switch. + if not await broker.validate_input_ticket(authority_ticket): + raise HTTPException(status_code=423, detail="Agent control revoked before input dispatch") result = await run_async_command(cmd) if not result.get("ok"): emit_operation_timing( @@ -507,7 +512,8 @@ async def key_press(data: KeyModel): when configured and the explorer.exe desktop barrier is absent. """ op_started = time.perf_counter() - if not await broker.check_access(): + authority_ticket = await broker.issue_input_ticket() + if authority_ticket is None: raise HTTPException(status_code=423, detail="Agent control denied by policy") await broker.report_agent_activity() @@ -549,6 +555,8 @@ async def key_press(data: KeyModel): }, ) + if not await broker.validate_input_ticket(authority_ticket): + raise HTTPException(status_code=423, detail="Agent control revoked before input dispatch") result = await _send_keys( keys=data.keys, window_id=target_win_id, From aba5d7433bb4d13da1d811424cc387fcf8a304e6 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:31:03 +0100 Subject: [PATCH 24/29] test(control): assert STOP_NOW blocks actual click-route synthetic effect --- tests/test_input_revocation_interleaving.py | 28 +++++++++++---------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/tests/test_input_revocation_interleaving.py b/tests/test_input_revocation_interleaving.py index 66b1ae8b..4bc41372 100644 --- a/tests/test_input_revocation_interleaving.py +++ b/tests/test_input_revocation_interleaving.py @@ -1,18 +1,19 @@ -"""Deterministic red-team witness of the current input check-to-effect race. +"""Deterministic safety regression for broker revocation before input dispatch. -This records existing behavior without injecting a real mouse event. It is a -known-unsafe witness, not a green assertion that production is fenced. +No external xdotool, Wine, or real input processes are executed. """ import asyncio import time from unittest.mock import patch +from fastapi import HTTPException + from api.core.broker import InputBroker from api.core.models import ClickModel, ControlMode, ControlPolicyMode, UserIntent from api.routers import input as input_router -def test_stop_now_between_window_search_and_click_exposes_unfenced_effect(): +def test_stop_now_between_window_search_and_click_blocks_stale_effect(): async def exercise(): admitted = asyncio.Event() release_search = asyncio.Event() @@ -50,14 +51,15 @@ async def synthetic_command(command, **_kwargs): await broker.set_user_intent(UserIntent.STOP_NOW) assert not await broker.check_access() release_search.set() - result = await asyncio.wait_for(task, timeout=3) + try: + await asyncio.wait_for(task, timeout=3) + except HTTPException as exc: + status = exc.status_code + else: + status = 200 - return observed, result + return observed, status - observed, result = asyncio.run(exercise()) - # RED witness: input effect occurred after STOP_NOW had revoked access. - # Replace this expected failure scenario with a rejection assertion once - # the real input dispatcher is epoch-fenced at its effect boundary. - assert len(observed) == 1 - assert observed[0][1] == UserIntent.STOP_NOW - assert result["status"] == "clicked" + observed, status = asyncio.run(exercise()) + assert status == 423 + assert observed == [] From bcdded89f7721fdadd11506b868761b4ae283e39 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:31:50 +0100 Subject: [PATCH 25/29] test(control): fence key injection and invalidate tickets on handover or expiry --- tests/test_input_revocation_interleaving.py | 79 +++++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/tests/test_input_revocation_interleaving.py b/tests/test_input_revocation_interleaving.py index 4bc41372..f73fab08 100644 --- a/tests/test_input_revocation_interleaving.py +++ b/tests/test_input_revocation_interleaving.py @@ -63,3 +63,82 @@ async def synthetic_command(command, **_kwargs): observed, status = asyncio.run(exercise()) assert status == 423 assert observed == [] + + +def test_stop_now_between_key_window_lookup_and_dispatch_blocks_key_effect(): + from api.core.models import KeyModel + + async def exercise(): + entered_lookup = asyncio.Event() + resume_lookup = asyncio.Event() + effects = [] + broker = InputBroker() + broker.state.interactive = True + broker.state.control_mode = ControlMode.AGENT + broker.state.effective_control_mode = ControlPolicyMode.HYBRID + broker.state.user_intent = UserIntent.WAIT + broker.state.lease_expiry = time.time() + 60 + + async def lookup(command, **_kwargs): + if "search" in command: + entered_lookup.set() + await asyncio.wait_for(resume_lookup.wait(), timeout=3) + return {"ok": True, "stdout": "42", "stderr": ""} + + async def dispatch(**_kwargs): + effects.append("key-sent") + return {"ok": True, "backend": "xdotool"} + + with ( + patch.object(input_router, "broker", broker), + patch.object(input_router, "run_async_command", side_effect=lookup), + patch.object(input_router, "_send_keys", side_effect=dispatch), + patch.object(input_router, "_require_active_session", return_value="/tmp/synthetic"), + patch.object(input_router, "append_input_event"), + patch.object(input_router, "append_trace_event"), + patch.object(input_router, "emit_operation_timing"), + ): + task = asyncio.create_task( + input_router.key_press( + KeyModel(keys="F1", window_title="Synthetic", backend="xdotool") + ) + ) + await asyncio.wait_for(entered_lookup.wait(), timeout=3) + await broker.set_user_intent(UserIntent.STOP_NOW) + resume_lookup.set() + try: + await asyncio.wait_for(task, timeout=3) + except HTTPException as exc: + status = exc.status_code + else: + status = 200 + return status, effects + + status, effects = asyncio.run(exercise()) + assert status == 423 + assert effects == [] + + +def test_input_ticket_invalidates_on_session_handover_and_lease_expiry(): + async def exercise(): + broker = InputBroker() + broker.state.interactive = True + broker.state.control_mode = ControlMode.AGENT + broker.state.effective_control_mode = ControlPolicyMode.HYBRID + broker.state.lease_expiry = time.time() + 60 + ticket = await broker.issue_input_ticket() + assert ticket is not None + assert await broker.validate_input_ticket(ticket) + await broker.update_session("new-session", interactive=True) + assert not await broker.validate_input_ticket(ticket) + + broker.state.interactive = True + broker.state.control_mode = ControlMode.AGENT + broker.state.effective_control_mode = ControlPolicyMode.HYBRID + broker.state.lease_expiry = time.time() + 60 + new_ticket = await broker.issue_input_ticket() + assert new_ticket is not None + broker.state.lease_expiry = time.time() - 1 + assert not await broker.validate_input_ticket(new_ticket) + + asyncio.run(exercise()) From 542f7bc8771a15912253ebe987145370598f38aa Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:33:03 +0100 Subject: [PATCH 26/29] docs(formal): distinguish fixed queued-input race from remaining in-flight effect gap --- formal/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/formal/README.md b/formal/README.md index 47960f6d..9294c33d 100644 --- a/formal/README.md +++ b/formal/README.md @@ -46,9 +46,9 @@ Every run must record GitHub workflow run/job and commit SHA, TLC tool version/h ## Concrete route interleaving — first code-to-model refinement -The source-owned test `tests/test_input_revocation_interleaving.py` uses the production `click_at` coroutine and real `InputBroker` but replaces X11 execution with a pure synthetic command fixture. A barrier suspends the window lookup **after** the first broker permission check, performs real broker `STOP_NOW` revocation and confirms access denied, then allows the route to complete. It asserts the known-bad current behavior: one later click command is still requested while `STOP_NOW` is active. This is a **red-team witness**, deliberately green only when the defect is reproducible; it must be converted into a safety assertion when the mitigation is introduced. It does not simulate a physical input event, prove an OS-level exploit, or certify a solution. +The source-owned test `tests/test_input_revocation_interleaving.py` uses the production `click_at` coroutine and real `InputBroker` but replaces X11 execution with a pure synthetic command fixture. A barrier suspends the window lookup **after** the first broker permission check, performs real broker `STOP_NOW` revocation and confirms access denied, then allows the route to complete. It originally demonstrated a queued click after `STOP_NOW`; it is now a **safety assertion** that the click does **not** reach the synthetic effect and instead returns HTTP 423. The same test path also checks queued keyboard dispatch and invalidation of authority tickets on session turnover and lease expiration. It does not simulate a physical input event or prove an OS-level kill switch. -**Remediation contract:** Each asynchronous input request needs a session-scoped immutable authority token / generation, effective expiry, and a consumer-side enforcement point as close to the external effect as possible. A second check in an API route alone narrows but does not close the TOCTOU window if the called backend asynchronously queues unguarded work. Test human STOP_NOW, ordinary user override, lease expiry, session handover, delayed backend starts, process crash/restart, and possible already-in-flight input, including explicit semantics for actions that cannot be recalled. Do not make `STOP_NOW` wait indefinitely for a long-running input process. First materialize a fenced dispatcher in a separate controlled patch with safe mock effects, then qualify real native backends independently. +**Remediation contract:** Each asynchronous input request needs a session-scoped immutable authority token / generation, effective expiry, and a consumer-side enforcement point as close to the external effect as possible. A second check in an API route alone narrows but does not close the TOCTOU window if the called backend asynchronously queues unguarded work. Test human STOP_NOW, ordinary user override, lease expiry, session handover, delayed backend starts, process crash/restart, and possible already-in-flight input, including explicit semantics for actions that cannot be recalled. Do not make `STOP_NOW` wait indefinitely for a long-running input process. The first runtime mitigation in `api/core/broker.py` issues an epoch ticket on admission, revokes it whenever authority changes, and `api/routers/input.py` verifies the ticket directly before beginning a mouse or keyboard backend call. This closes the reproduced pre-dispatch interleaving but does **not** guarantee a process already started can be stopped; real native consumer-side fencing/cancellation still requires a separate design and qualification. ## Session-handover recovery evidence (source review) From f676e308e1217fa692792e4b84c1c608d985334a Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Sat, 21 Nov 2026 00:49:10 +0100 Subject: [PATCH 27/29] fix(control): enforce STOP_NOW before noninteractive and agent-only implicit access --- api/core/broker.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/api/core/broker.py b/api/core/broker.py index 2955e938..97dd2530 100644 --- a/api/core/broker.py +++ b/api/core/broker.py @@ -188,6 +188,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: + # STOP_NOW is an absolute veto, including headless and agent-only + # sessions. Never admit a new ticket after human emergency stop. + 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: From 7b7b801aae662da481dbde353c81e2500bf922f8 Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Sat, 21 Nov 2026 00:49:17 +0100 Subject: [PATCH 28/29] test(control): STOP_NOW rejects fresh headless and agent-only input tickets --- tests/test_input_revocation_interleaving.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/test_input_revocation_interleaving.py b/tests/test_input_revocation_interleaving.py index f73fab08..23a01876 100644 --- a/tests/test_input_revocation_interleaving.py +++ b/tests/test_input_revocation_interleaving.py @@ -142,3 +142,21 @@ async def exercise(): assert not await broker.validate_input_ticket(new_ticket) asyncio.run(exercise()) + + +def test_stop_now_blocks_new_tickets_in_headless_and_agent_only(): + async def exercise(): + for mode in (ControlPolicyMode.HYBRID, ControlPolicyMode.AGENT_ONLY): + broker = InputBroker() + broker.state.interactive = False + broker.state.control_mode = ControlMode.AGENT + broker.state.effective_control_mode = mode + assert await broker.check_access() + initial = await broker.issue_input_ticket() + assert initial is not None + await broker.set_user_intent(UserIntent.STOP_NOW) + assert not await broker.check_access() + assert await broker.issue_input_ticket() is None + assert not await broker.validate_input_ticket(initial) + + asyncio.run(exercise()) From d00d2110c5d40d7f8862063a3d7901f215da96bd Mon Sep 17 00:00:00 2001 From: "Mark E. DeYoung" <1854350+mark-e-deyoung@users.noreply.github.com> Date: Sat, 21 Nov 2026 00:49:35 +0100 Subject: [PATCH 29/29] docs(formal): qualify absolute STOP_NOW veto across headless policy shortcuts --- formal/README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/formal/README.md b/formal/README.md index 9294c33d..4c5844b7 100644 --- a/formal/README.md +++ b/formal/README.md @@ -53,3 +53,7 @@ The source-owned test `tests/test_input_revocation_interleaving.py` uses the pro ## Session-handover recovery evidence (source review) In current public `api/routers/lifecycle.py`, `_write_transition_marker` writes `session.transition.json` during resume and `_clear_transition_marker` removes it after completion or caught exception. A direct source search of this file found marker writes/removals and no recovery reader of the marker at startup. The exception rollback tries to restore selected session pointer/state, but a process termination after `write_session_dir` and before profile linkage / broker update never reaches the exception handler. Thus a marker alone is not a proven restart-reconciliation protocol. Before accepting a change, add a reader/validator for the durable intent (schema, owner generation, previous and target identity), recover to a single authoritative owner on startup, and make crash injection exercise each physical write boundary and directory-sync durability. This is a code-inspection finding, not proof of an observed production crash or data loss. + +## Absolute STOP_NOW admission in all policy modes + +Code review found another production policy ordering gap: `InputBroker.check_access()` previously returned `True` for a non-interactive session and could return via the agent-only mode before considering the `STOP_NOW` intent. An invalidated ticket blocked *old* queued work, but a *new* ticket could be issued after an emergency stop in headless/agent-only mode. The mitigation now checks `STOP_NOW` before any policy-mode shortcut and refuses both new tickets and existing stale tickets. `tests/test_input_revocation_interleaving.py` explicitly exercises both headless/HYBRID and headless/AGENT_ONLY mode with a previously authorized ticket. This remains an in-process admission defense; already-committed native input requires consumer-side fencing.