Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
test(hyprland-plugin): fix unreachable and fail-open proof harness paths (#4104)
Francesco Bonacci83a71552d608
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_agent_conflict_proof.py b/libs/cua-driver/hyprland-plugin/tests/production_agent_conflict_proof.pyindex c11f9d5402..0405d54c37 100644--- a/libs/cua-driver/hyprland-plugin/tests/production_agent_conflict_proof.py+++ b/libs/cua-driver/hyprland-plugin/tests/production_agent_conflict_proof.py@@ -37,7 +37,7 @@ import timefrom driver_input_live import state, wait_forfrom primary_trace import analyzefrom production_cancel_proof import (MAX_GROUNDING_AGE_NS, PROFILE, close_owned, grounded_snapshot,- validate_app_profile, verify_fresh_observation, verify_recovery_cleanup, verify_recovery_trace)+ observation_started_ns, validate_app_profile, verify_fresh_observation, verify_recovery_cleanup, verify_recovery_trace)from production_mcp import DirectMCP, assert_distinct_runtimes, stop_processimport production_pointer_grounding as pointer_groundingfrom production_primary_conflict_proof import ExactDesktop, clear_status, validate_plan as primary_plan@@ -135,8 +135,8 @@ def verify_close_events(before, after, allowed):def ground(actor, spec):"""Ground one scroll on the acting runtime's fresh image; resolve scroll_visible before input."""- started_ns = time.monotonic_ns()before = grounded_snapshot(actor, spec['target'], spec)+ prepared_ns = observation_started_ns(before)image = pointer_grounding.read_pixels(before['proof_image'])stage = spec['pointer_stage']if stage == 'scroll_visible':@@ -145,7 +145,7 @@ def ground(actor, spec):arguments, oracle = pointer_grounding.action(before, image, spec['app'], stage)return {'snapshot': before, 'arguments': arguments, 'oracle': oracle, 'stage': stage,'requested_stage': spec['pointer_stage'],- 'prepared_ns': before.get('proof_observation_started_ns', started_ns)}+ 'prepared_ns': prepared_ns}def action(actor, observer, spec, stage, trace, guard, save, record, *, owner_lane=None):diff --git a/libs/cua-driver/hyprland-plugin/tests/production_agent_conflict_proof_test.py b/libs/cua-driver/hyprland-plugin/tests/production_agent_conflict_proof_test.pyindex 2cace8c843..28eaa95d06 100644--- a/libs/cua-driver/hyprland-plugin/tests/production_agent_conflict_proof_test.py+++ b/libs/cua-driver/hyprland-plugin/tests/production_agent_conflict_proof_test.py@@ -234,6 +234,22 @@ class OracleTests(unittest.TestCase):class ActionTests(unittest.TestCase):+ def test_grounding_without_observation_timestamp_fails_closed_before_input(self):+ spec = {**plan()['agents'][0], 'pointer_stage': 'scroll_down'}+ for value in (None, True, 0, -1, '10'):+ before = {'snapshot_id': 's00000001', 'proof_image': 'before.png'}+ if value is not None:+ before['proof_observation_started_ns'] = value+ actor = Mock()+ with self.subTest(value=value), \+ patch.object(proof, 'grounded_snapshot', return_value=before), \+ patch.object(proof.time, 'monotonic_ns', return_value=1_000), \+ patch.object(proof.pointer_grounding, 'read_pixels') as pixels, \+ self.assertRaisesRegex(AssertionError, 'invalid observation timestamp'):+ proof.ground(actor, spec)+ pixels.assert_not_called()+ actor.tool.assert_not_called()+def test_single_normal_scroll_fresh_snapshot_unknown_never_replayed(self):cases = {'owner': (None, 'guard', 'stale', 'unknown', 'same_snapshot', 'cached', 'before_return','same_runtime', 'effect', 'pre_activity', 'dead_before', 'observation', 'lane_mismatch',@@ -281,7 +297,7 @@ class ActionTests(unittest.TestCase):snapshots = stack.enter_context(patch.object(proof, 'grounded_snapshot',side_effect=[before, AssertionError('snapshot unavailable')] if failure == 'observation' else [before, after]))stack.enter_context(patch.object(proof.time, 'monotonic_ns', side_effect=- [5, proof.MAX_GROUNDING_AGE_NS + 11] if failure == 'stale' else [5, 30, 40, 70]))+ [proof.MAX_GROUNDING_AGE_NS + 11] if failure == 'stale' else [30, 40, 70]))stack.enter_context(patch.object(proof.pointer_grounding, 'read_pixels', return_value='pixels'))resolved = 'scroll_up' if spec['pointer_stage'] == 'scroll_visible' else spec['pointer_stage']choose = stack.enter_context(patch.object(proof.pointer_grounding, 'visible_inkscape_scroll_stage',diff --git a/libs/cua-driver/hyprland-plugin/tests/production_cancel_proof.py b/libs/cua-driver/hyprland-plugin/tests/production_cancel_proof.pyindex 0e9a868d49..3ce90d12d7 100644--- a/libs/cua-driver/hyprland-plugin/tests/production_cancel_proof.py+++ b/libs/cua-driver/hyprland-plugin/tests/production_cancel_proof.py@@ -158,11 +158,10 @@ def recover_once(client, observer, victim, sibling, spec, stage, trace, boundaryresponse = client.tool('start_session', {'session': fresh['name']})assert not response.get('isError'), responseidentity = app_process_identity(spec['app'], spec['target']['pid'])- started_ns = time.monotonic_ns()before = grounded_snapshot(client, fresh['target'], fresh)# Match prepare_drag: discovery precedes the observation; the complete# snapshot and pixel grounding remain inside the five-second limit.- started_ns = before.get('proof_observation_started_ns', started_ns)+ started_ns = observation_started_ns(before)image = pointer_grounding.read_pixels(before['proof_image'])requested_stage = stageif stage == 'scroll_visible':@@ -197,13 +196,28 @@ def recover_once(client, observer, victim, sibling, spec, stage, trace, boundarypage = trace.collect()save('recovery-prefix.json', page)result['trace'] = verify_recovery_trace(boundary, page, lane, tool)- assert client.process.poll() is None and sibling.process.poll() is None, 'runtime exited during recovery'+ require_recovery_runtimes(client, sibling)if guard:guard()result['result'] = 'verified'return page+def require_recovery_runtimes(*clients):+ """After a recovery action, its fresh runtime and every peer must still be live."""+ assert all(client.process.poll() is None for client in clients), 'runtime exited during recovery'+++def observation_started_ns(snapshot):+ """Freshness starts at the recorded observation; never substitute this wrapper's clock.++ Callers bound the age with 0 <= dispatch_ns - started_ns, so a future value also fails.+ """+ value = snapshot.get('proof_observation_started_ns')+ assert type(value) is int and value > 0, 'invalid observation timestamp'+ return value++def observation_runtime(client):"""Snapshot counters belong to one direct process and its evidence directory."""assert_distinct_runtimes([client])@@ -276,7 +290,7 @@ def prepare_drag(client, spec):"""Ground once before either gesture starts; never reuse an earlier action's image."""started_ns = time.monotonic_ns()before = grounded_snapshot(client, spec['target'], spec)- observation_started_ns = before.get('proof_observation_started_ns', started_ns)+ observation_ns = observation_started_ns(before)observed_ns = time.monotonic_ns()arguments, oracle = dict(spec['drag']), Noneif 'pointer_stage' in spec:@@ -284,9 +298,9 @@ def prepare_drag(client, spec):before, pointer_grounding.read_pixels(before['proof_image']), spec['app'], spec['pointer_stage'])return {'snapshot': before, 'arguments': arguments, 'oracle': oracle,'target': dict(spec['target']), 'session': spec['name'],- 'prepared_ns': observation_started_ns,+ 'prepared_ns': observation_ns,'timing': {'preparation_started_ns': started_ns,- 'observation_started_ns': observation_started_ns, 'observation_finished_ns': observed_ns,+ 'observation_started_ns': observation_ns, 'observation_finished_ns': observed_ns,'grounding_finished_ns': time.monotonic_ns()}}diff --git a/libs/cua-driver/hyprland-plugin/tests/production_cancel_proof_test.py b/libs/cua-driver/hyprland-plugin/tests/production_cancel_proof_test.pyindex e56b0f18c8..35721a66e3 100644--- a/libs/cua-driver/hyprland-plugin/tests/production_cancel_proof_test.py+++ b/libs/cua-driver/hyprland-plugin/tests/production_cancel_proof_test.py@@ -8,6 +8,7 @@ from pathlib import Pathimport subprocessimport tempfileimport threading+import timefrom types import SimpleNamespaceimport unittestfrom unittest.mock import Mock, patch@@ -335,7 +336,7 @@ class RecoveryTests(unittest.TestCase):for app, stage, tool in (('calc', 'click_b2', 'click'), ('inkscape', 'scroll_down', 'scroll'),('inkscape', 'scroll_visible', 'scroll')):for failure in (None, 'slow_discovery', 'alive', 'reused', 'stale', 'identity', 'snapshot', 'unknown', 'denied', 'effect', 'trace', 'primary_before', 'primary_after',- *(['margin'] if stage == 'scroll_visible' else [])):+ 'untimed', *(['margin'] if stage == 'scroll_visible' else [])):with self.subTest(app=app, failure=failure), ExitStack() as stack:victim, sibling, observer, fresh = [client(pid) for pid in (100, 101, 102, 103)]victim.failed = True@@ -346,8 +347,10 @@ class RecoveryTests(unittest.TestCase):'status': 'refused', 'refusal': {'code': 'permission_denied'}}}fresh.tool.side_effect = [{}, TimeoutError('lost reply') if failure == 'unknown' else response]spec = next(spec for spec in plan()['agents'] if spec['app'] == app)- before, after = {'proof_image': 'before.png'}, {'proof_image': 'after.png'}+ before, after = {'proof_image': 'before.png', 'proof_observation_started_ns': 100}, {'proof_image': 'after.png'}dispatch_ns = 101+ if failure == 'untimed':+ del before['proof_observation_started_ns'] # Never fall back to the wrapper clock.if failure == 'slow_discovery':before['proof_observation_started_ns'] = MAX_GROUNDING_AGE_NS + 200dispatch_ns = MAX_GROUNDING_AGE_NS + 301@@ -357,7 +360,7 @@ class RecoveryTests(unittest.TestCase):side_effect=AssertionError('app changed') if failure == 'identity' else None,return_value={'pid': spec['target']['pid']}))stack.enter_context(patch('production_cancel_proof.time.monotonic_ns',- side_effect=[100, MAX_GROUNDING_AGE_NS + 101 if failure == 'stale' else dispatch_ns]))+ side_effect=[MAX_GROUNDING_AGE_NS + 101 if failure == 'stale' else dispatch_ns]))stack.enter_context(patch('production_cancel_proof.pointer_grounding.read_pixels', return_value='pixels'))resolved_stage = 'scroll_up' if stage == 'scroll_visible' else stagechoose_stage = stack.enter_context(patch('production_cancel_proof.pointer_grounding.visible_inkscape_scroll_stage',@@ -378,7 +381,11 @@ class RecoveryTests(unittest.TestCase):def attempt():return recover_once(fresh, observer, victim, sibling, spec, stage, trace_client,trace(FINISH[:-1]), 1, save, result, guard)- if failure not in (None, 'slow_discovery'):+ if failure == 'untimed':+ with self.assertRaisesRegex(AssertionError, 'invalid observation timestamp'):+ attempt()+ self.assertEqual([call.args[0] for call in fresh.tool.call_args_list], ['start_session'])+ elif failure not in (None, 'slow_discovery'):with self.assertRaises((AssertionError, TimeoutError)):attempt()else:@@ -388,8 +395,7 @@ class RecoveryTests(unittest.TestCase):self.assertNotEqual(result['runtime_pid'], result['victim_pid'])self.assertFalse(result['replayed'])self.assertEqual(result['action']['dispatch_ns'], dispatch_ns)- self.assertEqual(result['grounding']['prepared_ns'],- before.get('proof_observation_started_ns', 100))+ self.assertEqual(result['grounding']['prepared_ns'], before['proof_observation_started_ns'])identity.assert_called_once_with(app, spec['target']['pid'])action.assert_called_once_with(before, 'pixels', app, resolved_stage)self.assertEqual(result['grounding']['requested_stage'], stage)@@ -401,7 +407,7 @@ class RecoveryTests(unittest.TestCase):self.assertIs(snapshot.call_args_list[0].args[0], fresh)self.assertIs(snapshot.call_args_list[1].args[0], observer)inputs = [call for call in fresh.tool.call_args_list if call.args[0] != 'start_session']- self.assertEqual(len(inputs), 0 if failure in ('alive', 'reused', 'stale', 'identity', 'snapshot', 'primary_before', 'margin') else 1)+ self.assertEqual(len(inputs), 0 if failure in ('alive', 'reused', 'stale', 'identity', 'snapshot', 'primary_before', 'margin', 'untimed') else 1)if inputs:self.assertEqual(inputs[0].args, (tool, {**arguments, **spec['target'],'session': spec['name'] + '-recovery', 'delivery_mode': 'background'}))@@ -551,7 +557,7 @@ class OwnershipTests(unittest.TestCase):def test_pointer_preparation_uses_exact_image_and_preserves_oracle(self):spec = {**plan()['agents'][0], 'drag': {}, 'pointer_stage': 'select_range'}- before = {'proof_image': 'fresh.png', 'window_bounds': BOUNDS}+ before = {'proof_image': 'fresh.png', 'window_bounds': BOUNDS, 'proof_observation_started_ns': 100}arguments = {**plan()['agents'][0]['drag'], 'steps': 30}oracle = {'selection': 'A1:B3'}with patch('production_cancel_proof.grounded_snapshot', return_value=before) as snapshot, \@@ -599,9 +605,20 @@ class OwnershipTests(unittest.TestCase):self.assertEqual(prepared['timing']['grounding_age_ns'], MAX_GROUNDING_AGE_NS + 1)mcp.tool.assert_not_called()+ def test_untimed_observation_never_gets_the_wrapper_clock(self):+ spec, mcp = plan()['agents'][0], Mock()+ for value in (None, True, 0, -1, 100.0):+ snapshot = {} if value is None else {'proof_observation_started_ns': value}+ with self.subTest(value=value), \+ patch('production_cancel_proof.grounded_snapshot', return_value=snapshot), \+ patch('production_cancel_proof.time.monotonic_ns', return_value=100), \+ self.assertRaisesRegex(AssertionError, 'invalid observation timestamp'):+ prepare_drag(mcp, spec)+ mcp.tool.assert_not_called()+def test_expired_or_retargeted_grounding_never_dispatches(self):spec, mcp = plan()['agents'][0], Mock()- with patch('production_cancel_proof.grounded_snapshot', return_value={}), \+ with patch('production_cancel_proof.grounded_snapshot', return_value={'proof_observation_started_ns': 100}), \patch('production_cancel_proof.time.monotonic_ns', return_value=100):prepared = prepare_drag(mcp, spec)for change, now in [({}, 101 + MAX_GROUNDING_AGE_NS), ({}, 99),@@ -614,7 +631,7 @@ class OwnershipTests(unittest.TestCase):def test_prepared_drag_does_not_snapshot_during_sibling_gesture(self):spec, mcp = plan()['agents'][0], Mock()mcp.tool.return_value = RESPONSE- with patch('production_cancel_proof.grounded_snapshot', return_value={}) as snapshot, \+ with patch('production_cancel_proof.grounded_snapshot', return_value={'proof_observation_started_ns': 100}) as snapshot, \patch('production_cancel_proof.time.monotonic_ns', return_value=100):prepared = prepare_drag(mcp, spec)result = call_drag(mcp, spec, prepared)@@ -734,7 +751,8 @@ class OwnershipTests(unittest.TestCase):def test_unknown_drag_is_called_once_with_fresh_grounding(self):mcp, spec = Mock(), plan()['agents'][0]mcp.tool.side_effect = TimeoutError('lost reply')- with patch('production_cancel_proof.grounded_snapshot', return_value={}) as snapshot:+ with patch('production_cancel_proof.grounded_snapshot', return_value={'proof_observation_started_ns': 100}) as snapshot, \+ patch('production_cancel_proof.time.monotonic_ns', return_value=100):result = call_drag(mcp, spec)snapshot.assert_called_once_with(mcp, spec['target'], spec)self.assertEqual(result['outcome'], 'unknown')@@ -919,7 +937,9 @@ class RunnerTests(unittest.TestCase):pool = Mock(submit=Mock(side_effect=futures))proof_image = root / 'fresh.png'proof_image.write_bytes(b'synthetic-test-image')- snapshot = Mock(return_value={'window_bounds': BOUNDS, 'proof_image': str(proof_image)})+ # Real monotonic clock: every mocked observation is fresh at setup.+ snapshot = Mock(return_value={'window_bounds': BOUNDS, 'proof_image': str(proof_image),+ 'proof_observation_started_ns': time.monotonic_ns()})preparation_clock_ns = 2 * MAX_GROUNDING_AGE_NSif failure == 'prepare_budget':# A monotonic clock has an unspecified origin: timestamp 1diff --git a/libs/cua-driver/hyprland-plugin/tests/production_desktop_fault_proof.py b/libs/cua-driver/hyprland-plugin/tests/production_desktop_fault_proof.pyindex b591ab8760..92e6dab315 100644--- a/libs/cua-driver/hyprland-plugin/tests/production_desktop_fault_proof.py+++ b/libs/cua-driver/hyprland-plugin/tests/production_desktop_fault_proof.py@@ -54,20 +54,17 @@ from desktop_faults import _identity, _same_compositor, _hyprfrom input_config_toggle import ENABLED, DISABLEDfrom driver_input_live import state, wait_for, wmfrom primary_trace import Trace, analyze-from production_cancel_proof import (MAX_GROUNDING_AGE_NS, PROFILE, active_drags, call_drag, close_owned,+from production_cancel_proof import (PROFILE, active_drags, call_drag, close_owned,grounded_snapshot, poll_active, prepare_drag, stopped_prefix, verify_recovery_cleanup)from production_geometry_fault_proof import recover, fault_outcome, validate_plan as geometry_planfrom production_mcp import DirectMCP, assert_distinct_runtimes, stop_process-from production_realapp_proof import (PRIMARY_LIFETIME_MS, app_process_identity, check_response, primary_acknowledgement,- provenance, require_primary_active, trace_interval)+from production_realapp_proof import (PRIMARY_LIFETIME_MS, primary_acknowledgement, provenance,+ require_primary_active, trace_interval)from realapp_proof import cleanup_all, released_synthetic_input-import production_pointer_grounding as pointer_groundingKEYMAP_US = 'hl.config({input = {kb_rules = "evdev", kb_model = "pc105", kb_layout = "us", kb_variant = "", kb_options = "", kb_file = ""}})\n'KEYMAP_CAPS_CTRL = 'hl.config({input = {kb_rules = "evdev", kb_model = "pc105", kb_layout = "us", kb_variant = "", kb_options = "ctrl:nocaps", kb_file = ""}})\n'-KEYMAP_CAPS_SUPER = 'hl.config({input = {kb_rules = "evdev", kb_model = "pc105", kb_layout = "us", kb_variant = "", kb_options = "caps:super", kb_file = ""}})\n'-KEYMAP_REMAPS = {'caps_to_ctrl': KEYMAP_CAPS_CTRL, 'caps_to_super': KEYMAP_CAPS_SUPER}WATCHDOG_SECONDS = {'config_disable': 12, 'keymap': 30}@@ -533,7 +530,7 @@ def verify_cancelled(boundary, record, before_restore_ns):tail = trace_interval(prefix, boundary)assert prefix['events'][-1][1] <= record['gate_ns'] <= record['requested_ns'] <= record['acknowledged_ns']assert record['acknowledged_ns'] <= before_restore_ns- assert 0 <= record['requested_ns'] - record['gate_ns'] <= 250_000_000+ assert 0 <= record['requested_ns'] - record['gate_ns'] <= 250_000_000, 'stale fault gate'synthetic = [row for row in tail if row[5] in (1, 2)]assert all(row[5] == lane for row in synthetic), 'cleanup crossed lanes'cancelled = [row for row in synthetic if row[2] == 'agent_cancel']@@ -555,36 +552,6 @@ def verify_cancelled(boundary, record, before_restore_ns):return isolation-def verify_layout_refusal(record):- policy = pointer_cleanup(record)- assert record['outcome'] == 'response' and record['replayed'] is False- assert record['tool'] in ('click', 'scroll')- assert type(record['runtime_pid']) is int and record['runtime_pid'] != record['previous_runtime_pid']- assert record['prepared_ns'] <= record['dispatch_ns'] <= record['observed_ns']- assert record['dispatch_ns'] - record['prepared_ns'] <= MAX_GROUNDING_AGE_NS- assert record['snapshot']['window_bounds'] == record['after_snapshot']['window_bounds'], 'refused target geometry changed'- check_response(record['response'], {'kind': 'refused', 'reason': 'unsupported_layout'})- content = record['response']['structuredContent']- assert content.get('route') == 'synthetic_events' and content.get('detail') == 'unsupported_layout'- assert content.get('code') == 'background_unavailable', 'not the compositor layout refusal'- before, after = keymap_lanes(record['before'], cleared=policy == 'cleared'), keymap_lanes(record['after'], cleared=policy == 'cleared')- if policy == 'retained_inert':- verify_retained_inert(record['before'], record['before'], record['lane'])- verify_refusal_claim(record['before'], record['after'], record['response'], record['lane'])- verify_target_snapshots(record['target'], record['bounds'], record['snapshot'], record['after_snapshot'])- for lane in before:- assert all(before[lane][key] == after[lane][key] for key in ('epoch', 'desktop_generation', 'dispatches')), \- 'layout refusal changed compositor state or dispatched input'- verify_keymap_options(record['keymap_options'], False)- tail = trace_interval(record['trace_before'], record['trace_after'])- assert not any(row[5] in (1, 2) for row in tail), 'refused fresh action dispatched synthetic input'- assert analyze(stopped_prefix(record['trace_after']))['result'] == 'passed'- if policy == 'retained_inert':- verify_refusal_closed(record, record['lane'])- return {'result': 'verified', 'reason': 'unsupported_layout', 'no_dispatch': 'verified',- 'compiled_map_invalidation': 'verified', 'keymap_hash': 'not_exposed'}--def verify_refusal_claim(before, after, response, interrupted_lane=None):"""A fresh CLAIM reserves capacity, never TARGET authority or inherited hover.@@ -609,73 +576,6 @@ def verify_refusal_claim(before, after, response, interrupted_lane=None):'owner_pid_in_status': 'not_exposed'}-def verify_refusal_closed(record, interrupted_lane):- closed = record['closure']- assert closed['runtime_pid'] == record['runtime_pid'] and type(closed['exit_code']) is int- assert record['observed_ns'] <= closed['started_ns'] <= closed['reaped_ns'] <= closed['observed_ns']- verify_retained_inert(record['before'], closed['status'], interrupted_lane)- old, new = keymap_lanes(record['after']), keymap_lanes(closed['status'])- for lane in old:- assert all(old[lane][k] == new[lane][k] for k in ('epoch', 'desktop_generation', 'dispatches'))- assert not any(row[5] in (1, 2) for row in trace_interval(record['trace_after'], closed['trace'])), 'probe EOF changed inert pointer or emitted input'- return {'result': 'verified', 'reservation_released': True}---def refuse_new_action(client, observer, victim, spec, stage, trace, config, guard, save):- """Exercise real Driver admission while the compiled physical map is invalid."""- assert victim.process.poll() is not None, 'old runtime must be reaped before refusal probe'- assert victim.process.pid not in assert_distinct_runtimes([client, observer])- fresh = {**spec, 'name': spec['name'] + '-wrong-layout', 'pointer_stage': stage}- assert not client.tool('start_session', {'session': fresh['name']}).get('isError')- app_process_identity(spec['app'], spec['target']['pid'])- prepared_ns = time.monotonic_ns()- snapshot = grounded_snapshot(client, spec['target'], fresh)- arguments, _ = pointer_grounding.action(snapshot, pointer_grounding.read_pixels(snapshot['proof_image']), spec['app'], stage)- tool = pointer_grounding.STAGES[spec['app']][stage]- assert tool in ('click', 'scroll'), 'never replay the interrupted drag'- record = {'outcome': 'unknown', 'replayed': False, 'runtime_pid': client.process.pid,- 'previous_runtime_pid': victim.process.pid, 'tool': tool, 'prepared_ns': prepared_ns,- 'snapshot': snapshot, 'arguments': arguments, 'session': fresh['name'],- 'before': production_status(config['instance'], True), 'trace_before': trace.collect()}- policy = pointer_cleanup(config)- if policy == 'retained_inert':- record.update(pointer_cleanup=policy, lane=config['lane'], target=dict(spec['target']), bounds=dict(spec['bounds']))- verify_retained_inert(record['before'], record['before'], record['lane'])- else:- keymap_lanes(record['before'], cleared=True)- record['keymap_options'] = keymap_options(config['instance'], False)- guard()- _guard(config)- assert file_identity(config['path']) == config['files']['disabled']['identity']- record['dispatch_ns'] = time.monotonic_ns()- assert record['dispatch_ns'] - prepared_ns <= MAX_GROUNDING_AGE_NS- assert record['dispatch_ns'] + 1_000_000_000 < config['deadline_ns'], 'watchdog deadline too near'- save('wrong-layout-action.json', record)- try:- record['response'] = client.tool(tool, {**arguments, **spec['target'], 'session': fresh['name'],- 'delivery_mode': 'background'})- record['outcome'] = 'response'- record['after_snapshot'] = grounded_snapshot(observer, spec['target'], fresh, session=False)- record['after'] = production_status(config['instance'], True)- record['trace_after'] = trace.collect()- record['keymap_options'] = keymap_options(config['instance'], False)- record['observed_ns'] = time.monotonic_ns()- assert record['observed_ns'] < config['deadline_ns'], 'watchdog restored during refusal probe'- guard()- if policy == 'retained_inert':- record['claim'] = verify_refusal_claim(record['before'], record['after'], record['response'], record['lane'])- closed = record['closure'] = {'runtime_pid': client.process.pid, 'started_ns': time.monotonic_ns()}- close_owned(client)- closed.update(reaped_ns=time.monotonic_ns(), exit_code=client.process.poll())- closed.update(status=production_status(config['instance'], True), trace=trace.collect(), observed_ns=time.monotonic_ns())- assert closed['observed_ns'] < config['deadline_ns'], 'watchdog restored during probe closure'- guard()- record['verification'] = verify_layout_refusal(record)- return record- finally:- save('wrong-layout-action.json', record)--def verify_target_snapshots(target, bounds, before, after):for snapshot in (before, after):assert all(type(target.get(key)) is int and target[key] > 0 and@@ -711,26 +611,7 @@ def verify_fault(boundary, record, restoration, action):verify_keymap_options(restoration['keymap_options'], True)assert record['keymap_before'] == restoration['keymap_options'], 'original map options not restored'verify_keymap_transition(record['gate_status'], record['after'], policy, record['lane'])- # Preserve validation of archived pre-private-keymap evidence without- # requiring or producing a fresh unsupported-layout probe today.- if 'wrong_layout' in record:- refusal = record['wrong_layout']- assert pointer_cleanup(refusal) == policy, 'refusal changed pointer cleanup contract'- if policy == 'retained_inert':- assert refusal['lane'] == record['lane'] and refusal['target'] == record['target'] and refusal['bounds'] == record['bounds']- verify_retained_inert(record['after'], refusal['before'], record['lane'])- assert refusal['closure']['observed_ns'] < restoration['started_ns'], 'probe not closed before restoration'- verify_layout_refusal(refusal)- after, before_refusal = keymap_lanes(record['after']), keymap_lanes(refusal['before'])- for lane in after:- assert all(after[lane][key] == before_refusal[lane][key] for key in ('epoch', 'desktop_generation', 'dispatches')), \- 'keymap state changed before fresh refusal'- trace_interval(record['prefix'], refusal['trace_before'])- trace_interval(refusal['trace_after'], boundary)- assert record['acknowledged_ns'] <= refusal['prepared_ns'] <= refusal['observed_ns'] < restoration['started_ns']- verify_keymap_transition(refusal['after'], restoration['status'], policy, record['lane'])- else:- verify_keymap_transition(record['after'], restoration['status'], policy, record['lane'])+ verify_keymap_transition(record['after'], restoration['status'], policy, record['lane'])if policy == 'retained_inert':gate = keymap_lanes(record['gate_status'])initial = idle_lanes(record['before'])@@ -753,8 +634,6 @@ def verify_fault(boundary, record, restoration, action):isolation = verify_cancelled(boundary, record, restoration['started_ns'])result = {'result': 'verified', 'outcome': fault_outcome(action), 'continuous_isolation': isolation,'synthetic_cleanup': 'verified', 'saved_document_effect': 'unproven'}- if record['kind'] == 'keymap' and 'wrong_layout' in record:- result['legacy_wrong_layout'] = verify_layout_refusal(record['wrong_layout'])if policy == 'retained_inert':result['pointer_cleanup'] = {'policy': policy, 'presence_continuity': 'verified','grounded_target_identity': 'verified', 'wayland_surface_identity': 'not_exposed'}diff --git a/libs/cua-driver/hyprland-plugin/tests/production_desktop_fault_proof_test.py b/libs/cua-driver/hyprland-plugin/tests/production_desktop_fault_proof_test.pyindex ff69ffbc7c..0556d7797c 100644--- a/libs/cua-driver/hyprland-plugin/tests/production_desktop_fault_proof_test.py+++ b/libs/cua-driver/hyprland-plugin/tests/production_desktop_fault_proof_test.py@@ -62,20 +62,10 @@ def keymap_status(generation=2):return result-def layout_refusal():- return {'outcome': 'response', 'replayed': False, 'runtime_pid': 103, 'previous_runtime_pid': 100,- 'tool': 'click', 'prepared_ns': 10_100_000, 'dispatch_ns': 10_500_000, 'observed_ns': 11_000_000,- 'snapshot': {'window_bounds': dict(BOUNDS)}, 'after_snapshot': {'window_bounds': dict(BOUNDS)},- 'response': {'isError': True, 'structuredContent': {'effect': 'refused', 'reason': 'unsupported_layout',- 'code': 'background_unavailable', 'detail': 'unsupported_layout', 'route': 'synthetic_events'}},- 'before': keymap_status(), 'after': keymap_status(), 'keymap_options': options(False),- 'trace_before': trace(CANCEL), 'trace_after': trace(CANCEL)}--def keymap_record():return {**record(), 'kind': 'keymap', 'config': {'sha256': proof.digest(proof.KEYMAP_CAPS_CTRL.encode())},'before': keymap_status(1), 'gate_status': keymap_status(1), 'after': keymap_status(2),- 'keymap_before': options(), 'keymap_after': options(False), 'wrong_layout': layout_refusal()}+ 'keymap_before': options(), 'keymap_after': options(False)}def keymap_restoration():@@ -112,20 +102,7 @@ def retained_evidence(kind='keymap'):boundary['events'] += [[7, 8_000_000, 'agent_cancel', 100, 100, 1, 0],[8, 9_000_000, 'pointer_button', 100, 100, 1, 0]]boundary['count'] = len(boundary['events'])- if kind == 'keymap':- refused = candidate['wrong_layout']- refused.update(pointer_cleanup='retained_inert', lane=1,- target=dict(candidate['target']), bounds=dict(BOUNDS),- snapshot=target_snapshot('refusal-before', runtime=103, observed_ns=10_200_000),- after_snapshot=target_snapshot('refusal-after', runtime=101, observed_ns=10_700_000),- before=deepcopy(candidate['after']), after=deepcopy(candidate['after']),- trace_before=deepcopy(boundary), trace_after=deepcopy(boundary))- refused['response']['structuredContent']['lane'] = 0- refused['after']['input']['lanes'][0]['reserved'] = True- refused['closure'] = {'runtime_pid': refused['runtime_pid'], 'exit_code': 0,- 'started_ns': 11_100_000, 'reaped_ns': 11_200_000, 'observed_ns': 11_300_000,- 'status': deepcopy(refused['before']), 'trace': deepcopy(boundary)}- else:+ if kind != 'keymap':candidate['after']['configured'] = Falsecandidate['after']['transport']['ready'] = Falsecandidate['after']['input']['transport_ready'] = False@@ -171,42 +148,6 @@ class RetainedPointerTests(unittest.TestCase):self.assertEqual(fault.record['after']['input']['lanes'][0]['pointer_focus'], True)self.assertEqual(atomic.call_count, int(failure != 'gate_absent'))- def test_fresh_refusal_probe_threads_retained_policy_and_exact_target(self):- for missing_focus in (False, True):- with self.subTest(missing_focus=missing_focus), ExitStack() as stack:- boundary, candidate, _ = retained_evidence()- spec = plan('keymap')['agents'][0]- fresh, observer, victim = client(103), client(101), client(100, alive=False)- fresh.tool.side_effect = [{}, candidate['wrong_layout']['response']]- before = deepcopy(candidate['after'])- if missing_focus:- before['input']['lanes'][0]['pointer_focus'] = False- stack.enter_context(patch.object(proof, 'production_status', side_effect=[before, candidate['wrong_layout']['after'], candidate['after']]))- stack.enter_context(patch.object(proof, 'close_owned', side_effect=lambda c: setattr(c.process.poll, 'return_value', 0)))- stack.enter_context(patch.object(proof, 'app_process_identity'))- stack.enter_context(patch.object(proof, 'grounded_snapshot', side_effect=[- {**target_snapshot('refusal-before', runtime=103, observed_ns=10_200_000), 'proof_image': '/synthetic/image'},- target_snapshot('refusal-after', runtime=101, observed_ns=10_700_000)]))- stack.enter_context(patch.object(proof.pointer_grounding, 'read_pixels', return_value=[]))- stack.enter_context(patch.object(proof.pointer_grounding, 'action', return_value=({'x': 20, 'y': 20}, {})))- stack.enter_context(patch.object(proof, 'keymap_options', return_value=options(False)))- stack.enter_context(patch.object(proof, '_guard'))- stack.enter_context(patch.object(proof, 'file_identity', return_value={'inode': 20}))- stack.enter_context(patch.object(proof.time, 'monotonic_ns', side_effect=[10_100_000, 10_500_000, 11_000_000, 11_100_000, 11_200_000, 11_300_000]))- config = {'instance': 'exact', 'path': '/unused', 'deadline_ns': 12_000_000_000,- 'pointer_cleanup': 'retained_inert', 'lane': 1,- 'files': {'disabled': {'identity': {'inode': 20}}}}- args = (fresh, observer, victim, spec, 'click_b2', Mock(collect=Mock(return_value=boundary)), config, Mock(), Mock())- if missing_focus:- with self.assertRaises(AssertionError):- proof.refuse_new_action(*args)- self.assertEqual(fresh.tool.call_count, 1)- else:- observed = proof.refuse_new_action(*args)- self.assertEqual(observed['pointer_cleanup'], 'retained_inert')- self.assertEqual(observed['target'], spec['target'])- self.assertEqual(observed['verification']['result'], 'verified')-def test_opt_in_and_legacy_default_are_distinct(self):for kind in ('config_disable', 'keymap'):for policy in ('cleared', 'retained_inert', None, True, 'retained', {}, []):@@ -235,14 +176,10 @@ class RetainedPointerTests(unittest.TestCase):('reserved', True), ('reserved', None), ('pointer_focus', False),('pointer_focus', 1), ('pointer_focus', None), ('dispatches', 2)]for kind in ('config_disable', 'keymap'):- stages = ['after', 'restored', 'target_status'] + (['refusal-before', 'refusal-after'] if kind == 'keymap' else [])- for stage in stages:+ for stage in ('after', 'restored', 'target_status'):for key, value in fields:- if stage == 'refusal-after' and key == 'reserved' and value is True:- value = False # This one fresh CLAIM must exist until EOF.boundary, candidate, restored = retained_evidence(kind)- observed = (restored['status'] if stage == 'restored' else- candidate['wrong_layout'][stage.split('-')[1]] if stage.startswith('refusal-') else candidate[stage])+ observed = restored['status'] if stage == 'restored' else candidate[stage]observed['input']['lanes'][0][key] = valuewith self.subTest(kind=kind, stage=stage, key=key, value=value), self.assertRaises(AssertionError):proof.verify_fault(boundary, candidate, restored, action())@@ -251,45 +188,29 @@ class RetainedPointerTests(unittest.TestCase):with self.assertRaisesRegex(AssertionError, 'presence'):proof.verify_fault(boundary, candidate, restored, action())- def test_fresh_claim_is_capacity_only_and_must_disappear_on_probe_eof(self):+ def test_fresh_refusal_claim_is_capacity_only_on_its_exact_lane(self):+ before = keymap_status(2)+ before['input']['lanes'][0]['pointer_focus'] = Truefor claimed in (0, 1):- _, candidate, _ = retained_evidence()- record = candidate['wrong_layout']- record['response']['structuredContent']['lane'] = claimed- for row in record['after']['input']['lanes']:- row['reserved'] = row['lane'] == claimed- self.assertEqual(proof.verify_layout_refusal(record)['result'], 'verified')- for side, lane, key, value in (- ('before', claimed, 'reserved', True), ('after', 1 - claimed, 'reserved', True),- ('after', claimed, 'lease_active', True), ('after', claimed, 'held_keys', 1),- ('after', claimed, 'held_button', 272), ('after', claimed, 'keyboard_focus', True),- ('after', claimed, 'drag_active', True), ('after', claimed, 'dispatches', 99),- ('closure', claimed, 'reserved', True), ('closure', 0, 'pointer_focus', False)):- bad = deepcopy(record)- status = bad['closure']['status'] if side == 'closure' else bad[side]- status['input']['lanes'][lane][key] = value- with self.subTest(claimed=claimed, side=side, key=key), self.assertRaises(AssertionError):- proof.verify_layout_refusal(bad)- _, candidate, _ = retained_evidence()- record = candidate['wrong_layout']+ after = deepcopy(before)+ after['input']['lanes'][claimed]['reserved'] = True+ response = {'structuredContent': {'lane': claimed}}+ self.assertEqual(proof.verify_refusal_claim(before, after, response, 1)['claimed_lane'], claimed)+ for lane, key, value in ((1 - claimed, 'reserved', True), (claimed, 'lease_active', True),+ (claimed, 'held_keys', 1), (claimed, 'held_button', 272),+ (claimed, 'keyboard_focus', True), (claimed, 'drag_active', True),+ (claimed, 'dispatches', 99), (0, 'pointer_focus', False)):+ bad = deepcopy(after)+ bad['input']['lanes'][lane][key] = value+ with self.subTest(claimed=claimed, lane=lane, key=key), self.assertRaises(AssertionError):+ proof.verify_refusal_claim(before, bad, response, 1)+ after = deepcopy(before)+ after['input']['lanes'][0]['reserved'] = Truefor bad_lane in (None, True, -1, 2, '0'):- bad = deepcopy(record)- bad['response']['structuredContent']['lane'] = bad_lane- with self.subTest(lane=bad_lane), self.assertRaises(AssertionError):- proof.verify_layout_refusal(bad)- for key, value in (('runtime_pid', record['runtime_pid'] + 1), ('exit_code', None),- ('reaped_ns', 1), ('observed_ns', 1)):- bad = deepcopy(record)- bad['closure'][key] = value- with self.subTest(key=key), self.assertRaises(AssertionError):- proof.verify_layout_refusal(bad)- for event in ('pointer_leave', 'pointer_enter', 'pointer_motion', 'agent_admitted', 'pointer_button'):- bad = deepcopy(record)- page = bad['closure']['trace']- page['events'].append([9, 11_250_000, event, 100, 100, 1, 0])- page['count'] += 1- with self.subTest(event=event), self.assertRaises(AssertionError):- proof.verify_layout_refusal(bad)+ with self.subTest(lane=bad_lane), self.assertRaisesRegex(AssertionError, 'exact claimed lane'):+ proof.verify_refusal_claim(before, after, {'structuredContent': {'lane': bad_lane}}, 1)+ with self.assertRaises(AssertionError):+ proof.verify_refusal_claim(before, after, {'structuredContent': {'lane': 0}}, 2)def test_retained_trace_cannot_hide_leave_retarget_motion_new_input_or_missing_release(self):for kind in ('config_disable', 'keymap'):@@ -314,14 +235,11 @@ class RetainedPointerTests(unittest.TestCase):def test_target_process_window_geometry_and_snapshot_identity_are_required(self):for kind in ('config_disable', 'keymap'):- for stage in ('target_before', 'target_after', 'snapshot', 'after_snapshot'):- if kind == 'config_disable' and stage in ('snapshot', 'after_snapshot'):- continue+ for stage in ('target_before', 'target_after'):for key, value in (('pid', 21), ('window_id', 201), ('window_id', None),('window_bounds', {**BOUNDS, 'x': 999}), ('snapshot_id', '')):boundary, candidate, restored = retained_evidence(kind)- snapshot = candidate[stage] if stage.startswith('target_') else candidate['wrong_layout'][stage]- snapshot[key] = value+ candidate[stage][key] = valuewith self.subTest(kind=kind, stage=stage, key=key), self.assertRaises(AssertionError):proof.verify_fault(boundary, candidate, restored, action())boundary, candidate, restored = retained_evidence(kind)@@ -331,22 +249,6 @@ class RetainedPointerTests(unittest.TestCase):with self.assertRaisesRegex(AssertionError, 'reused'):proof.verify_fault(boundary, candidate, restored, action())- def test_refusal_snapshot_ids_are_scoped_to_the_observer_and_require_new_observations(self):- for same_runtime in (False, True):- for same_id in (False, True):- _, candidate, _ = retained_evidence()- refusal = candidate['wrong_layout']- if same_runtime:- refusal['after_snapshot']['proof_runtime'] = deepcopy(refusal['snapshot']['proof_runtime'])- if same_id:- refusal['after_snapshot']['snapshot_id'] = refusal['snapshot']['snapshot_id']- with self.subTest(same_runtime=same_runtime, same_id=same_id):- if same_runtime and same_id:- with self.assertRaisesRegex(AssertionError, 'reused'):- proof.verify_layout_refusal(refusal)- else:- self.assertEqual(proof.verify_layout_refusal(refusal)['result'], 'verified')-def test_cross_runtime_counter_collision_cannot_hide_stale_or_invalid_timing(self):for key, value in (('proof_observation_started_ns', None), ('proof_observation_started_ns', True),('proof_observation_started_ns', -1), ('proof_observation_started_ns', 1_000_000),@@ -358,24 +260,13 @@ class RetainedPointerTests(unittest.TestCase):candidate['target_after'][key] = valuewith self.subTest(key=key, value=value), self.assertRaises(AssertionError):proof.verify_fault(boundary, candidate, restored, action())- _, candidate, _ = retained_evidence()- refusal = candidate['wrong_layout']- refusal['after_snapshot']['snapshot_id'] = refusal['snapshot']['snapshot_id']- refusal['after_snapshot']['proof_observation_started_ns'] = refusal['snapshot']['proof_observation_started_ns']+ boundary, candidate, restored = retained_evidence()+ candidate['target_after']['snapshot_id'] = candidate['target_before']['snapshot_id']+ candidate['target_after']['proof_observation_started_ns'] = candidate['target_before']['proof_observation_started_ns']with self.assertRaisesRegex(AssertionError, 'out-of-order'):- proof.verify_layout_refusal(refusal)-- def test_refusal_has_no_synthetic_events_even_with_unchanged_status(self):- for event in ('pointer_enter', 'pointer_leave', 'pointer_motion', 'pointer_button',- 'agent_admitted', 'keyboard_leave'):- _, candidate, _ = retained_evidence()- refusal = candidate['wrong_layout']- refusal['trace_after']['events'].append([9, 10_800_000, event, 100, 100, 1, 0])- refusal['trace_after']['count'] += 1- with self.subTest(event=event), self.assertRaisesRegex(AssertionError, 'synthetic input'):- proof.verify_layout_refusal(refusal)-- def test_gate_epoch_generation_refusal_policy_and_lane_cannot_be_substituted(self):+ proof.verify_fault(boundary, candidate, restored, action())++ def test_gate_epoch_generation_policy_and_lane_cannot_be_substituted(self):for change in ('gate', 'epoch', 'generation', 'policy', 'lane', 'target', 'dispatch'):boundary, candidate, restored = retained_evidence()if change == 'gate':@@ -386,7 +277,7 @@ class RetainedPointerTests(unittest.TestCase):elif change == 'dispatch':candidate['gate_status']['input']['lanes'][0]['dispatches'] = 2else:- candidate['wrong_layout'][{'policy': 'pointer_cleanup', 'lane': 'lane', 'target': 'target'}[change]] = {+ candidate[{'policy': 'pointer_cleanup', 'lane': 'lane', 'target': 'target'}[change]] = {'policy': 'cleared', 'lane': 2, 'target': {'pid': 21, 'window_id': 201}}[change]with self.subTest(change=change), self.assertRaises(AssertionError):proof.verify_fault(boundary, candidate, restored, action())@@ -483,17 +374,11 @@ class MotionGateTests(unittest.TestCase):class KeymapTests(unittest.TestCase):- def test_supported_user_remap_fixtures_keep_us_layout_and_change_only_options(self):- self.assertEqual(set(proof.KEYMAP_REMAPS), {'caps_to_ctrl', 'caps_to_super'})- self.assertIn('kb_layout = "us"', proof.KEYMAP_CAPS_CTRL)- self.assertIn('kb_options = "ctrl:nocaps"', proof.KEYMAP_CAPS_CTRL)- self.assertIn('kb_layout = "us"', proof.KEYMAP_CAPS_SUPER)- self.assertIn('kb_options = "caps:super"', proof.KEYMAP_CAPS_SUPER)- for fixture in proof.KEYMAP_REMAPS.values():- self.assertIn('kb_rules = "evdev"', fixture)- self.assertIn('kb_model = "pc105"', fixture)- self.assertIn('kb_variant = ""', fixture)- self.assertIn('kb_file = ""', fixture)+ def test_fault_fixture_keeps_us_layout_and_changes_only_options(self):+ self.assertIn('kb_options = ""', proof.KEYMAP_US)+ self.assertEqual(proof.KEYMAP_CAPS_CTRL,+ proof.KEYMAP_US.replace('kb_options = ""', 'kb_options = "ctrl:nocaps"'))+ self.assertEqual(proof.fixed_bytes('keymap'), (proof.KEYMAP_US, proof.KEYMAP_CAPS_CTRL))def test_idle_baseline_allows_only_unreserved_inert_hover_on_either_lane(self):for lane in (0, 1):@@ -550,11 +435,10 @@ class KeymapTests(unittest.TestCase):with self.subTest(kind=kind, data=data), self.assertRaises(AssertionError):proof.validate_plan(candidate)- def test_compiled_map_gate_refusal_and_original_map_restoration_pass(self):- self.assertEqual(proof.verify_fault(trace(CANCEL), keymap_record(), keymap_restoration(), action())['result'], 'verified')- result = proof.verify_layout_refusal(layout_refusal())- self.assertEqual(result['no_dispatch'], 'verified')- self.assertEqual(result['keymap_hash'], 'not_exposed')+ def test_compiled_map_gate_and_original_map_restoration_pass(self):+ result = proof.verify_fault(trace(CANCEL), keymap_record(), keymap_restoration(), action())+ self.assertEqual(result['result'], 'verified')+ self.assertNotIn('legacy_wrong_layout', result)def test_exact_option_readback_rejects_labels_variants_options_and_override(self):for key in options():@@ -578,112 +462,25 @@ class KeymapTests(unittest.TestCase):with self.subTest(key=key), self.assertRaises(AssertionError):proof.verify_keymap_transition(keymap_status(1), after)- def test_refusal_rejects_generic_error_unknown_replay_and_stale_runtime(self):- for key, value in (('outcome', 'unknown'), ('replayed', True), ('runtime_pid', 100), ('tool', 'drag'),- ('dispatch_ns', 9_000_000), ('dispatch_ns', 99_000_000_000)):- candidate = layout_refusal()- candidate[key] = value- with self.subTest(key=key), self.assertRaises(AssertionError):- proof.verify_layout_refusal(candidate)- for key, value in (('reason', 'unsupported_operation'), ('detail', 'wrong layout'), ('route', 'foreground'),- ('effect', 'partial'), ('delivery', {'mode': 'background'}), ('code', 'unsupported_layout')):- candidate = layout_refusal()- candidate['response']['structuredContent'][key] = value- with self.subTest(key=key), self.assertRaises(AssertionError):- proof.verify_layout_refusal(candidate)-- def test_refusal_requires_no_dispatch_and_no_primary_disturbance(self):- candidate = layout_refusal()- candidate['after_snapshot']['window_bounds']['x'] += 1- with self.assertRaises(AssertionError):- proof.verify_layout_refusal(candidate)- for kind, lane in (('agent_admitted', 1), ('pointer_button', 1), ('pointer_axis', 2),- ('keyboard_key', 0), ('pointer_focus', 0)):- candidate = layout_refusal()- candidate['trace_after'] = trace(CANCEL + [(11, kind, lane, 0)])- with self.subTest(kind=kind), self.assertRaises(AssertionError):- proof.verify_layout_refusal(candidate)- for key, value in (('dispatches', 2), ('desktop_generation', 3), ('epoch', 'replaced'), ('held_button', 1)):- candidate = layout_refusal()- candidate['after']['input']['lanes'][1][key] = value- with self.subTest(key=key), self.assertRaises(AssertionError):- proof.verify_layout_refusal(candidate)- candidate = layout_refusal()- candidate['trace_after']['events'][0][3] += 1- with self.assertRaises(AssertionError):- proof.verify_layout_refusal(candidate)-def test_restoration_requires_original_options_and_new_generation(self):- for mutate in (lambda r: r.update(keymap_options=options(False)),- lambda r: r.update(status=keymap_status(2)),- lambda r: r.update(config={'sha256': proof.digest(proof.ENABLED.encode())})):+ for mutate, message in ((lambda r: r.update(keymap_options=options(False)), 'keymap option'),+ (lambda r: r.update(config={'sha256': proof.digest(proof.ENABLED.encode())}), ''),+ # These reach the live after-to-restoration keymap transition.+ (lambda r: r.update(status=keymap_status(2)), 'did not invalidate authority'),+ (lambda r: r['status']['input']['lanes'][1].update(epoch='replaced'), 'lane replaced'),+ (lambda r: r['status']['input']['lanes'][0].update(reserved=True),+ 'reservation survived')):restored = keymap_restoration()mutate(restored)- with self.assertRaises(AssertionError):+ with self.subTest(message=message), self.assertRaisesRegex(AssertionError, message):proof.verify_fault(trace(CANCEL), keymap_record(), restored, action())- for mutate in (lambda r: r['wrong_layout'].update(observed_ns=13_000_000),- lambda r: r['wrong_layout'].update(keymap_options=options()),- lambda r: r.update(after=keymap_status(1))):+ for mutate in (lambda r: r.update(after=keymap_status(1)),+ lambda r: r.update(keymap_after=options())):candidate = keymap_record()mutate(candidate)with self.assertRaises(AssertionError):proof.verify_fault(trace(CANCEL), candidate, keymap_restoration(), action())- def test_new_driver_action_is_fresh_guarded_and_preserves_failed_evidence(self):- for failure in (None, 'runtime', 'stale', 'watchdog', 'file', 'held', 'unknown', 'generic', 'dispatch',- 'expired_during_snapshot', 'restored_during_snapshot'):- with self.subTest(failure=failure), ExitStack() as stack:- candidate = plan('keymap')- spec = candidate['agents'][0]- fresh, observer, victim = client(103), client(101), client(100, alive=False)- if failure == 'runtime':- victim.process.poll.return_value = None- response = layout_refusal()['response']- if failure == 'generic':- response['structuredContent']['reason'] = 'unsupported_operation'- fresh.tool.side_effect = [{}, TimeoutError('lost response') if failure == 'unknown' else response]- page = trace(CANCEL + [(11, 'pointer_button', 1, 1)]) if failure == 'dispatch' else trace(CANCEL)- transport = Mock(collect=Mock(side_effect=[trace(CANCEL), page]))- before = keymap_status()- if failure == 'held':- before['input']['lanes'][0]['held_button'] = 272- stack.enter_context(patch.object(proof, 'production_status', side_effect=[before, keymap_status()]))- stack.enter_context(patch.object(proof, 'app_process_identity'))- snapshot = stack.enter_context(patch.object(proof, 'grounded_snapshot', return_value={- 'proof_image': '/synthetic/image', 'window_bounds': dict(BOUNDS)}))- stack.enter_context(patch.object(proof.pointer_grounding, 'read_pixels', return_value=[]))- stack.enter_context(patch.object(proof.pointer_grounding, 'action', return_value=({'x': 20, 'y': 20}, {})))- stack.enter_context(patch.object(proof, 'keymap_options', side_effect=[options(False),- AssertionError('watchdog restored keymap') if failure == 'restored_during_snapshot' else options(False)]))- stack.enter_context(patch.object(proof, '_guard'))- stack.enter_context(patch.object(proof, 'file_identity', return_value={} if failure == 'file' else {'inode': 20}))- stack.enter_context(patch.object(proof.time, 'monotonic_ns', side_effect=[10_100_000,- 99_000_000_000 if failure == 'stale' else 10_500_000,- 13_000_000_000 if failure == 'expired_during_snapshot' else 11_000_000]))- config = {'instance': 'exact', 'path': '/unused', 'deadline_ns': 11_000_000 if failure == 'watchdog' else 12_000_000_000,- 'files': {'disabled': {'identity': {'inode': 20}}}}- saved = {}- def save(name, record):- saved[name] = deepcopy(record)- if failure:- with self.assertRaises((AssertionError, TimeoutError)):- proof.refuse_new_action(fresh, observer, victim, spec, 'click_b2', transport, config, Mock(), save)- else:- result = proof.refuse_new_action(fresh, observer, victim, spec, 'click_b2', transport, config, Mock(), save)- self.assertEqual(result['verification']['no_dispatch'], 'verified')- self.assertEqual(fresh.tool.call_args.args[0], 'click')- self.assertEqual(fresh.tool.call_args.args[1]['session'], spec['name'] + '-wrong-layout')- self.assertEqual(snapshot.call_args_list[0].args[0], fresh)- self.assertEqual(snapshot.call_args_list[1].args[0], observer)- self.assertEqual(snapshot.call_args_list[1].kwargs, {'session': False})- self.assertEqual(result['snapshot']['window_bounds'], result['after_snapshot']['window_bounds'])- if failure in ('runtime', 'stale', 'watchdog', 'file', 'held'):- self.assertFalse(any(call.args[0] == 'click' for call in fresh.tool.call_args_list))- if failure in ('unknown', 'generic', 'dispatch', 'expired_during_snapshot', 'restored_during_snapshot'):- self.assertIn('wrong-layout-action.json', saved)- self.assertNotIn('verification', saved['wrong-layout-action.json'])--class OracleTests(unittest.TestCase):def test_partial_unknown_and_exact_history_pass_without_claiming_app_effect(self):for observed in (action(), {'outcome': 'unknown', 'replayed': False}):@@ -709,9 +506,24 @@ class OracleTests(unittest.TestCase):def test_fault_cancellation_and_release_must_precede_restoration(self):for changes in ({'requested_ns': 9_000_000}, {'gate_ns': 7_000_000},- {'requested_ns': 300_000_000}, {'watchdog_deadline_ns': 12_000_000}):+ {'watchdog_deadline_ns': 12_000_000}):with self.subTest(changes=changes), self.assertRaises(AssertionError):proof.verify_fault(trace(CANCEL), {**record(), **changes}, restoration(), action())+ # Isolate the 250 ms gate-to-request bound; every ordering check still holds.+ for requested_ms, stale in ((255, False), (256, True)):+ late_cancel = ACTIVE + [(requested_ms, 'agent_cancel', 1, 0), (requested_ms + 1, 'pointer_button', 1, 0),+ (requested_ms + 1, 'pointer_leave', 1, 0)]+ candidate = {**record(), 'gate_ns': 5_000_000, 'requested_ns': requested_ms * 1_000_000,+ 'acknowledged_ns': (requested_ms + 1) * 1_000_000, 'watchdog_deadline_ns': 1_000_000_000}+ restored = {**restoration(), 'started_ns': (requested_ms + 2) * 1_000_000,+ 'observed_ns': (requested_ms + 3) * 1_000_000}+ with self.subTest(requested_ms=requested_ms):+ if stale:+ with self.assertRaisesRegex(AssertionError, 'stale fault gate'):+ proof.verify_fault(trace(late_cancel), candidate, restored, action())+ else:+ self.assertEqual(proof.verify_fault(trace(late_cancel), candidate, restored, action())['result'],+ 'verified')late = ACTIVE + [(12, 'agent_cancel', 1, 0), (13, 'pointer_button', 1, 0)]with self.assertRaisesRegex(AssertionError, 'during fault'):proof.verify_fault(trace(late), record(), restoration(), action())diff --git a/libs/cua-driver/hyprland-plugin/tests/production_geometry_fault_proof.py b/libs/cua-driver/hyprland-plugin/tests/production_geometry_fault_proof.pyindex 5a4edc1355..3b79b80328 100644--- a/libs/cua-driver/hyprland-plugin/tests/production_geometry_fault_proof.py+++ b/libs/cua-driver/hyprland-plugin/tests/production_geometry_fault_proof.py@@ -34,7 +34,8 @@ from primary_trace import Trace, analyzefrom production_cancel_proof import (GROUNDING_DISPATCH_RESERVE_NS, MAX_GROUNDING_ATTEMPTS,MAX_GROUNDING_AGE_NS, POINTER_STAGES, PROFILE,RECOVERY_STAGES, active_drags, call_drag, close_owned, grounded_snapshot, validate_app_profile,- poll_active, prepare_drag, stopped_prefix, verify_recovery_cleanup, verify_recovery_trace)+ poll_active, prepare_drag, require_recovery_runtimes, stopped_prefix, verify_recovery_cleanup,+ verify_recovery_trace)from production_mcp import DirectMCP, assert_distinct_runtimes, stop_processimport production_pointer_grounding as pointer_groundingfrom production_realapp_proof import (PRIMARY_LIFETIME_MS, app_process_identity,@@ -217,7 +218,7 @@ def verify_fault(boundary, record, action):assert set(active_drags(prefix)) == {lane}tail = trace_interval(prefix, boundary)assert record['gate_ns'] <= record['requested_ns'] <= record['acknowledged_ns'] <= record['after']['observed_ns']- assert 0 <= record['requested_ns'] - record['gate_ns'] <= 250_000_000+ assert 0 <= record['requested_ns'] - record['gate_ns'] <= 250_000_000, 'stale fault gate'assert prefix['events'][-1][1] <= record['requested_ns'], 'trace clock is incompatible'synthetic = [row for row in tail if row[5] in (1, 2)]assert all(row[5] == lane for row in synthetic), 'cleanup crossed lanes'@@ -292,6 +293,7 @@ def recover(client, observer, victim, spec, stage, trace, boundary, lane, guard,result['app_effect'] = pointer_grounding.verify(after, pointer_grounding.read_pixels(after['proof_image']), oracle)page = trace.collect()result['trace'] = verify_recovery_trace(boundary, page, lane, tool)+ require_recovery_runtimes(client, observer)guard()result['result'] = 'verified'return pagediff --git a/libs/cua-driver/hyprland-plugin/tests/production_geometry_fault_proof_test.py b/libs/cua-driver/hyprland-plugin/tests/production_geometry_fault_proof_test.pyindex 5323d6ff2f..994ea10e0c 100644--- a/libs/cua-driver/hyprland-plugin/tests/production_geometry_fault_proof_test.py+++ b/libs/cua-driver/hyprland-plugin/tests/production_geometry_fault_proof_test.py@@ -102,12 +102,25 @@ class OracleTests(unittest.TestCase):proof.verify_fault(trace(rows), record(), action())def test_unchanged_geometry_stale_gate_and_invalid_timestamps_fail(self):- for field, value in [('result', 'unproven'), ('requested_ns', 300_000_000),+ for field, value in [('result', 'unproven'),('acknowledged_ns', 4_000_000), ('gate_ns', 7_000_000),('after', {'bounds': BOUNDS, 'observed_ns': 11_000_000}),('before_bounds', record()['expected_bounds'])]:with self.subTest(field=field), self.assertRaises(AssertionError):proof.verify_fault(trace(CANCEL), {**record(), field: value}, action())+ # Isolate the 250 ms gate-to-request bound; every ordering check still holds.+ for requested_ms, stale in ((255, False), (256, True)):+ rows = ACTIVE + [(requested_ms, 'agent_cancel', 1, 0), (requested_ms + 1, 'pointer_button', 1, 0),+ (requested_ms + 1, 'pointer_leave', 1, 0)]+ candidate = {**record(), 'gate_ns': 5_000_000, 'requested_ns': requested_ms * 1_000_000,+ 'acknowledged_ns': (requested_ms + 1) * 1_000_000,+ 'after': {**record()['after'], 'observed_ns': (requested_ms + 2) * 1_000_000}}+ with self.subTest(requested_ms=requested_ms):+ if stale:+ with self.assertRaisesRegex(AssertionError, 'stale fault gate'):+ proof.verify_fault(trace(rows), candidate, action())+ else:+ self.assertEqual(proof.verify_fault(trace(rows), candidate, action())['result'], 'verified')class OwnershipTests(unittest.TestCase):@@ -281,7 +294,8 @@ class RecoveryTests(unittest.TestCase):def test_fresh_runtime_fresh_grounding_single_new_action_and_unknown_never_replayed(self):for app in ('calc', 'inkscape'):- for failure in (None, 'slow_discovery', 'alive', 'reused', 'stale', 'unknown', 'guard', 'effect'):+ for failure in (None, 'slow_discovery', 'alive', 'reused', 'stale', 'unknown', 'guard', 'effect',+ 'fresh_exited', 'observer_exited'):with self.subTest(app=app, failure=failure), ExitStack() as stack:spec = plan(app=app)['agents'][0]stage = plan(app=app)['recovery']['pointer_stage']@@ -290,6 +304,16 @@ class RecoveryTests(unittest.TestCase):if failure == 'reused':fresh.process.pid = 100fresh.tool.side_effect = [{}, TimeoutError('lost reply') if failure == 'unknown' else DELIVERED]+ if failure in ('fresh_exited', 'observer_exited'):+ # The runtime dies after its one action; the saved result must not verify.+ exiting = fresh if failure == 'fresh_exited' else observer+ replies = iter(fresh.tool.side_effect)+ def reply(*_args, exiting=exiting, replies=replies):+ value = next(replies)+ if value is DELIVERED:+ exiting.process.poll.return_value = 1+ return value+ fresh.tool.side_effect = replybefore, after = {'proof_image': 'before.png', 'proof_observation_started_ns': 100}, {'proof_image': 'after.png'}dispatch_ns = 101if failure == 'slow_discovery':@@ -304,7 +328,11 @@ class RecoveryTests(unittest.TestCase):stack.enter_context(patch.object(proof, 'verify_recovery_trace', return_value={'result': 'verified'}))result, save = {}, Mock()guard = Mock(side_effect=AssertionError('primary expired') if failure == 'guard' else None)- if failure not in (None, 'slow_discovery'):+ if failure in ('fresh_exited', 'observer_exited'):+ with self.assertRaisesRegex(AssertionError, 'runtime exited during recovery'):+ proof.recover(fresh, observer, victim, spec, stage, Mock(), trace(CANCEL), 1, guard, save, result)+ self.assertNotIn('result', result)+ elif failure not in (None, 'slow_discovery'):with self.assertRaises(AssertionError):proof.recover(fresh, observer, victim, spec, stage, Mock(), trace(CANCEL), 1, guard, save, result)else:diff --git a/libs/cua-driver/hyprland-plugin/tests/production_idle_reconnect_proof.py b/libs/cua-driver/hyprland-plugin/tests/production_idle_reconnect_proof.pyindex ea77d04ea2..25b94ddb2f 100644--- a/libs/cua-driver/hyprland-plugin/tests/production_idle_reconnect_proof.py+++ b/libs/cua-driver/hyprland-plugin/tests/production_idle_reconnect_proof.py@@ -70,7 +70,7 @@ def calc_identity(spec):identity = app_process_identity(spec['app'], pid)document = Path(spec['document']).resolve(strict=True)assert str(document).encode() in Path(f'/proc/{pid}/cmdline').read_bytes().split(b'\0'), \- 'Calc process is not bound to the synthetic document'+ 'app process is not bound to the synthetic document'return {key: identity[key] for key in ('pid', 'executable', 'sha256')} | {'start_ticks': process_birth(pid), 'document': str(document)}@@ -155,7 +155,7 @@ def click_once(client, observer, spec, stage, runtime, identity, trace, boundary"""Exactly one click invocation; unknown outcomes remain failures without replay."""assert stage in (INKSCAPE_STAGES if spec['app'] == 'inkscape' else STAGES)require_runtime(client, runtime)- assert calc_identity(spec) == identity, 'Calc process identity changed'+ assert calc_identity(spec) == identity, 'app process identity changed'fresh = {**spec, 'pointer_stage': stage}before = grounded_snapshot(client, spec['target'], fresh)pixels = grounding.read_pixels(before['proof_image'])@@ -167,7 +167,7 @@ def click_once(client, observer, spec, stage, runtime, identity, trace, boundarysave(stage + '-grounding.json', result)guard()require_runtime(client, runtime)- assert process_birth(spec['target']['pid']) == identity['start_ticks'], 'Calc process identity changed'+ assert process_birth(spec['target']['pid']) == identity['start_ticks'], 'app process identity changed'dispatch_ns = time.monotonic_ns()assert 0 <= dispatch_ns - before['proof_observation_started_ns'] <= MAX_GROUNDING_AGE_NS, \'snapshot grounding expired; no input sent'@@ -187,9 +187,9 @@ def click_once(client, observer, spec, stage, runtime, identity, trace, boundaryafter_pixels = grounding.read_pixels(after['proof_image'])result['app_effect'] = grounding.verify(after, after_pixels, oracle)after_digest = grid_digest(after, after_pixels, spec['app'])- assert before_digest != after_digest, 'Calc grid pixels did not change'+ assert before_digest != after_digest, 'app pixels did not change'result['pixels'] = {'before': before_digest, 'after': after_digest, 'changed': True}- assert calc_identity(spec) == identity, 'Calc process identity changed'+ assert calc_identity(spec) == identity, 'app process identity changed'require_runtime(client, runtime)page = trace.collect()lane = capacity_lane(boundary, page, tool)@@ -276,16 +276,16 @@ def episode(args, plan, client, observer, runtime, identity, stage, save, resultdef run(args):if not __debug__:raise RuntimeError('assertions must be enabled')- plan = json.loads(args.plan.read_text())- validate_plan(plan)args.evidence.mkdir(parents=True, exist_ok=False)def save(name, value):(args.evidence / name).write_text(json.dumps(value, indent=2))- save('plan.json', plan)report = {'result': 'failed', 'scope': 'native-production-idle-reconnect','full_desktop_matrix': False, 'actions': []}clients = []try:+ plan = json.loads(args.plan.read_text())+ save('plan.json', plan)+ validate_plan(plan)assert args.trace_socket.name in ('cua-input-v3.sock', 'cua-input-v3-2.sock')origin = provenance(args, plan)for name in ('production_idle_reconnect_proof.py', 'production_idle_reconnect_proof_test.py',diff --git a/libs/cua-driver/hyprland-plugin/tests/production_idle_reconnect_proof_test.py b/libs/cua-driver/hyprland-plugin/tests/production_idle_reconnect_proof_test.pyindex 95fc65dcf4..54e4571042 100644--- a/libs/cua-driver/hyprland-plugin/tests/production_idle_reconnect_proof_test.py+++ b/libs/cua-driver/hyprland-plugin/tests/production_idle_reconnect_proof_test.py@@ -294,6 +294,25 @@ class RunnerTests(unittest.TestCase):self.assertEqual(events, ['click_b2', 'expiry', 'click_a1'] if expires else ['click_b2', 'expiry'])first_client.tool.assert_called_once_with('start_session', {'session': 'idle-proof'})+ def test_invalid_plan_records_failed_result_without_runtime_or_status_reads(self):+ import json+ for name, text in (('invalid_plan', json.dumps({**plan(), 'idle_timeout': 1})), ('malformed_json', '{')):+ with self.subTest(name=name), tempfile.TemporaryDirectory() as directory, ExitStack() as stack:+ path = Path(directory) / 'plan.json'+ path.write_text(text)+ args = SimpleNamespace(plan=path, evidence=Path(directory) / 'proof',+ trace_socket=Path('/synthetic/cua-input-v3.sock'))+ spawn = stack.enter_context(patch.object(proof, 'DirectMCP'))+ status_read = stack.enter_context(patch.object(proof, 'read_input_status'))+ stack.enter_context(patch('sys.stdout', new_callable=io.StringIO))+ self.assertEqual(proof.run(args), 1)+ spawn.assert_not_called()+ status_read.assert_not_called()+ report = json.loads((args.evidence / 'result.json').read_text())+ self.assertEqual(report['result'], 'failed')+ self.assertEqual(report['cleanup_errors'], [])+ self.assertIn('error', report)+if __name__ == '__main__':unittest.main()diff --git a/libs/cua-driver/hyprland-plugin/tests/production_policy_proof.py b/libs/cua-driver/hyprland-plugin/tests/production_policy_proof.pyindex 218eb0f941..65334295ce 100644--- a/libs/cua-driver/hyprland-plugin/tests/production_policy_proof.py+++ b/libs/cua-driver/hyprland-plugin/tests/production_policy_proof.py@@ -41,7 +41,9 @@ import zipfilefrom driver_input_live import wait_for, wmfrom primary_trace import Trace, analyze-from production_app_smoke import NS, ground, provenance, rectangle, verify_calc, verify_inkscape+from production_app_smoke import (+ APP_PROFILES, NS, ground, profile_packages, provenance, rectangle, verify_calc, verify_inkscape,+)from production_mcp import DirectMCPfrom production_realapp_proof import (SMOKE_STEPS, app_process_identity, assert_no_dispatch, capacity_lane,@@ -62,9 +64,12 @@ POLICY_SNAPSHOT_LIMITS = {'inkscape': {'max_elements': 2500}}def validate_plan(plan):- assert set(plan) <= {'case', 'mode', 'app', 'target', 'document', 'disposable'}+ assert set(plan) <= {'case', 'mode', 'app', 'target', 'document', 'disposable', 'app_profile'}assert plan.get('disposable') is True, 'requires a prepared disposable desktop'assert plan['case'] in CASES and plan['app'] in SMOKE_STEPS+ if 'app_profile' in plan:+ profile_packages(plan['app_profile'])+ assert plan['app'] in APP_PROFILES[plan['app_profile']], 'app is outside the selected app profile'assert plan.get('mode', 'unrestricted') in ('standard', 'bounded', 'unrestricted')assert plan['case'] != 'no_manifest_allow' or plan.get('mode', 'unrestricted') != 'bounded', \'bounded cannot admit an action without a manifest'diff --git a/libs/cua-driver/hyprland-plugin/tests/production_policy_proof_test.py b/libs/cua-driver/hyprland-plugin/tests/production_policy_proof_test.pyindex 76056aa04b..4c29f59ac0 100644--- a/libs/cua-driver/hyprland-plugin/tests/production_policy_proof_test.py+++ b/libs/cua-driver/hyprland-plugin/tests/production_policy_proof_test.py@@ -287,6 +287,29 @@ class OracleTests(unittest.TestCase):self.assertIn('source differs', report['error']['message'])+ def test_inkscape_only_profile_is_accepted_and_selects_profile_provenance(self):+ candidate = {**plan(app='inkscape'), 'app_profile': 'inkscape-only'}+ validate_plan(candidate)+ for profile, app, message in (('inkscape-only', 'calc', 'outside the selected app profile'),+ ('bogus', 'inkscape', 'unknown app qualification profile'),+ (['inkscape-only'], 'inkscape', 'unknown app qualification profile')):+ with self.subTest(profile=profile, app=app), self.assertRaisesRegex(AssertionError, message):+ validate_plan({**plan(app=app), 'app_profile': profile})+ with tempfile.TemporaryDirectory() as temporary, patch.dict(os.environ, {}, clear=True):+ directory = Path(temporary)+ path = directory / 'plan.json'+ path.write_text(json.dumps(candidate))+ args = SimpleNamespace(plan=path, evidence=directory / 'evidence')+ with patch('production_policy_proof.provenance',+ side_effect=AssertionError('profile provenance reached')) as provenance, \+ patch('production_policy_proof.DirectMCP') as spawn:+ self.assertEqual(run(args), 1)+ provenance.assert_called_once_with(args, app_profile='inkscape-only')+ spawn.assert_not_called()+ report = json.loads((args.evidence / 'result.json').read_text())+ self.assertIn('profile provenance reached', report['error']['message'])++class OrchestrationTests(unittest.TestCase):def exercise(self, directory, failure=None, *, app='calc', case='managed_deny',missing_grounding=None):diff --git a/libs/cua-driver/hyprland-plugin/tests/production_primary_conflict_proof.py b/libs/cua-driver/hyprland-plugin/tests/production_primary_conflict_proof.pyindex a9365bda07..62d31f6960 100644--- a/libs/cua-driver/hyprland-plugin/tests/production_primary_conflict_proof.py+++ b/libs/cua-driver/hyprland-plugin/tests/production_primary_conflict_proof.py@@ -264,12 +264,14 @@ def run(args):assert checked['result'] == 'passed' and released_synthetic_input(stopped), checkedassert [row[2] for row in stopped['events'] if row[2] in ('start', 'stop')] == ['start', 'stop'], \'trace restarted within an action phase'- boundary = report['phases'][phase]['trace_after']- assert stopped['events'][:boundary['count']] == boundary['events'], 'final trace history changed'if phase == 'refusal':assert not any(row[5] in (1, 2) for row in stopped['events']), 'refusal dispatched or teardown sent input'- else:- checked = verify_recovery_cleanup(report['phases'][phase]['trace_after'], stopped)+ # A lost start acknowledgement or failed action leaves no post-action boundary.+ boundary = report['phases'].get(phase, {}).get('trace_after')+ assert boundary is not None, f'{phase} trace boundary was never recorded; final history is unverifiable'+ assert stopped['events'][:boundary['count']] == boundary['events'], 'final trace history changed'+ if phase != 'refusal':+ checked = verify_recovery_cleanup(boundary, stopped)guard()report['phases'][phase]['final_status'] = desktop.status(unreserved=True, allow_passive=phase == 'recovery')report['phases'][phase]['isolation'] = checkeddiff --git a/libs/cua-driver/hyprland-plugin/tests/production_primary_conflict_proof_test.py b/libs/cua-driver/hyprland-plugin/tests/production_primary_conflict_proof_test.pyindex cf8eea6cd2..87310f1f9f 100644--- a/libs/cua-driver/hyprland-plugin/tests/production_primary_conflict_proof_test.py+++ b/libs/cua-driver/hyprland-plugin/tests/production_primary_conflict_proof_test.py@@ -417,6 +417,11 @@ class RunTests(unittest.TestCase):self.assertEqual(report['error']['message'], 'unexpected refusal reservation')if failure == 'reserved_after_close':self.assertEqual(len(launched), 2, 'recovery followed an unreleased reservation')+ if failure == 'start_lost':+ self.assertEqual(report['error']['message'], 'trace start acknowledgement lost')+ self.assertIn({'operation': 'finish_trace',+ 'error': 'refusal trace boundary was never recorded; final history is unverifiable'},+ json.loads((args.evidence / 'cleanup.json').read_text())['errors'])if __name__ == '__main__':diff --git a/libs/cua-driver/hyprland-plugin/tests/production_session_fault_proof.py b/libs/cua-driver/hyprland-plugin/tests/production_session_fault_proof.pyindex 81f5fae318..f58833bf37 100644--- a/libs/cua-driver/hyprland-plugin/tests/production_session_fault_proof.py+++ b/libs/cua-driver/hyprland-plugin/tests/production_session_fault_proof.py@@ -488,11 +488,14 @@ def prepare_actions(clients, spec, stage, save):def refuse(client, spec, prepared, fault, trace, guard, save):- record = {**prepared, 'outcome': 'unknown', 'replayed': False, 'runtime_pid': client.process.pid,- 'pointer_cleanup': pointer_cleanup(fault.config),- 'deadline_ns': fault.config['deadline_ns'], 'before': production_status(fault.config),- 'monitors_before': fault.unavailable(), 'trace_before': trace.collect()}+ record = {**prepared, 'outcome': 'unknown', 'replayed': False, 'runtime_pid': client.process.pid}try:+ # Every pre-action read can fail; keep the partial record for the finally-save.+ record['pointer_cleanup'] = pointer_cleanup(fault.config)+ record['deadline_ns'] = fault.config['deadline_ns']+ record['before'] = production_status(fault.config)+ record['monitors_before'] = fault.unavailable()+ record['trace_before'] = trace.collect()if pointer_cleanup(record) == 'retained_inert':record['lane'] = fault.record['lane']verify_stable_inert(fault.record['after'], record['before'], record['lane'])diff --git a/libs/cua-driver/hyprland-plugin/tests/production_session_fault_proof_test.py b/libs/cua-driver/hyprland-plugin/tests/production_session_fault_proof_test.pyindex fbdeae80cf..b13fd24ee1 100644--- a/libs/cua-driver/hyprland-plugin/tests/production_session_fault_proof_test.py+++ b/libs/cua-driver/hyprland-plugin/tests/production_session_fault_proof_test.py@@ -357,6 +357,28 @@ class GroundingTests(unittest.TestCase):self.assertEqual(save.call_args.args[1]['outcome'], 'unknown')self.assertFalse(save.call_args.args[1]['replayed'])+ def test_failed_pre_action_reads_still_save_partial_refusal_evidence(self):+ for failure in ('status', 'monitors', 'trace'):+ with self.subTest(failure=failure):+ client, save = Mock(process=Mock(pid=100)), Mock()+ fault = Mock(config={'deadline_ns': 1_000_000_000},+ unavailable=Mock(side_effect=AssertionError('monitors read failed') if failure == 'monitors'+ else None, return_value=[{**MONITOR, 'dpmsStatus': False}]))+ collector = Mock(collect=Mock(side_effect=AssertionError('trace read failed') if failure == 'trace'+ else None, return_value=trace(CANCEL)))+ with patch.object(proof, 'production_status',+ side_effect=AssertionError('status read failed') if failure == 'status' else None,+ return_value=status(2)), \+ self.assertRaisesRegex(AssertionError, failure + ' read failed'):+ proof.refuse(client, plan()['agents'][0], {'prepared_ns': 100}, fault, collector, Mock(), save)+ client.tool.assert_not_called()+ save.assert_called_once()+ name, saved = save.call_args.args+ self.assertEqual(name, 'unavailable-action.json')+ self.assertEqual((saved['outcome'], saved['replayed'], saved['runtime_pid']), ('unknown', False, 100))+ self.assertEqual('before' in saved, failure != 'status')+ self.assertNotIn('trace_before', saved)+class WatchdogTests(unittest.TestCase):def test_injection_is_gated_by_fresh_pending_drag_and_acks_exact_power(self):diff --git a/libs/cua-driver/hyprland-plugin/tests/production_target_lifetime_proof.py b/libs/cua-driver/hyprland-plugin/tests/production_target_lifetime_proof.pyindex f6062a0e71..128aa3a4f8 100644--- a/libs/cua-driver/hyprland-plugin/tests/production_target_lifetime_proof.py+++ b/libs/cua-driver/hyprland-plugin/tests/production_target_lifetime_proof.py@@ -248,8 +248,12 @@ class TargetLifetime(ExactDesktop):self.record['last_status'] = observedtry:verify_cleared(before, observed, lane)- except AssertionError:+ except (AssertionError, KeyError) as error:+ # Not yet cleared, including a sample without resource counters.+ # Retain why; the bounded wait fails closed if it never clears.+ self.record['last_clear_error'] = f'{type(error).__name__}: {error}'return None+ self.record.pop('last_clear_error', None)return observedself.record['after'] = wait_for(cleared, timeout=3)self.record['observed_ns'] = time.monotonic_ns()diff --git a/libs/cua-driver/hyprland-plugin/tests/production_target_lifetime_proof_test.py b/libs/cua-driver/hyprland-plugin/tests/production_target_lifetime_proof_test.pyindex 568a6e8a5f..39d2b23da6 100644--- a/libs/cua-driver/hyprland-plugin/tests/production_target_lifetime_proof_test.py+++ b/libs/cua-driver/hyprland-plugin/tests/production_target_lifetime_proof_test.py@@ -294,6 +294,40 @@ class InjectionTests(unittest.TestCase):with self.assertRaisesRegex(AssertionError, 'one termination'):fault.inject(Mock(), trace(ACTIVE[:1]), pending, Mock())+ def test_status_without_resource_counters_is_not_yet_cleared_and_never_fatal(self):+ def bounded(check, timeout):+ for _ in range(3):+ value = check()+ if value:+ return value+ raise AssertionError('bounded evidence wait expired')+ for eventually_cleared in (True, False):+ with self.subTest(eventually_cleared=eventually_cleared), ExitStack() as stack:+ fault = object.__new__(proof.TargetLifetime)+ fault.fd, fault.sent, fault.record = 77, False, {}+ fault.guard, fault.spec = Mock(), plan()['agents'][0]+ before, after = statuses()+ partial = deepcopy(after)+ del partial['input']['lanes'][0]['pointer_resources']+ samples = [partial, after, after] if eventually_cleared else [partial] * 3+ fault.status = Mock(side_effect=[before, *samples])+ fault.gone = Mock(return_value={'pidfd_exited': True, 'window_absent': True, 'observed_ns': 9_000_000})+ stack.enter_context(patch.object(proof, 'poll_active', return_value=(trace(ACTIVE), {1: 2})))+ stack.enter_context(patch.object(proof, 'saved_document'))+ stack.enter_context(patch.object(proof.time, 'monotonic_ns', side_effect=[5_000_000, 6_000_000, 10_000_000]))+ stack.enter_context(patch.object(proof.signal, 'pidfd_send_signal', create=True))+ stack.enter_context(patch.object(proof, 'wait_for', side_effect=bounded))+ pending = Mock(done=Mock(return_value=False))+ if eventually_cleared:+ self.assertEqual(fault.inject(Mock(), trace(ACTIVE[:1]), pending, Mock()), 1)+ self.assertEqual(fault.record['after'], after)+ self.assertNotIn('last_clear_error', fault.record)+ else:+ with self.assertRaisesRegex(AssertionError, 'bounded evidence wait expired'):+ fault.inject(Mock(), trace(ACTIVE[:1]), pending, Mock())+ self.assertEqual(fault.record['last_status'], partial)+ self.assertEqual(fault.record['last_clear_error'], "KeyError: 'pointer_resources'")+def test_gone_requires_pidfd_exit_and_old_address_absence(self):for exited, windows in ((False, []), (True, [{'pid': 21, 'address': '0xc8'}]),(True, [{'pid': 20, 'address': '0xff'}]), (True, [])):