# input-capture ## Goal The Mac's side of `InputHook.cs`: a `CGEventTap` that sees every key, modifier, mouse and scroll event, decides *synchronously* whether the event stays on this Mac or is swallowed for a remote one, turns it into the Windows encoding (`docs/protocol.md` §5), matches the hotkeys (§4.5) and hands everything to the Engine through a bounded queue (contracts C3). With it come the pieces the tap needs and the injector will share: the Windows-VK ↔ macOS-keycode table, the screen geometry that feeds `Edge`, the cursor parking/decoupling that keeps the real pointer still while a remote machine is controlled, and the permission preflight/ request wrapper. Invariants 3 and 4 (CLAUDE.md) and contract C2 are this lane's. ## Assumptions Written at planning time, revised 2026-09-16 to what shipped. Anything the code does not enforce is here. - **One tap, on its own thread.** `CGEvent.tapCreate(tap: .cgSessionEventTap, place: .headInsertEventTap, options: .defaultTap, …)` for key down/up, flagsChanged, mouse moved/dragged, all button down/up and scroll wheel. The run-loop source is added to the `CFRunLoop` of a dedicated `Thread` at `.userInteractive`, never the main thread (contracts C3). A `.defaultTap` needs Accessibility; listening to keys needs Input Monitoring (README §Permissions). `tapDisabledByTimeout` / `tapDisabledByUserInput` arrive whatever the mask says, so they are not in it. - **The callback does five things and returns**: (1) handle a disabled tap; (2) if the event carries the injected tag (`CGEventField.eventSourceUserData == InputTypes.injectedEventTag`) return it untouched — the Windows `RealData` flag (`InputHook.cs:213-220, 340-343`); (3) read the `RoutingSnapshot`; (4) match hotkeys — the escape set flips the snapshot to local *inside the callback* and is swallowed, other hotkeys are queued and swallowed; (5) if the destination is remote, convert to `CapturedInput`, push and swallow (`InputHook.cs:361-368` keyboard, `:322-325` mouse); if local, push mouse *moves only* so `Edge` can watch for a crossing, and pass everything through. No allocation on any of it (invariant 4). - **Four locks are reachable from the callback**, all uncontended `OSAllocatedUnfairLock`s held only for a struct copy: `EventTap.counters`, `RoutingState`'s box (the snapshot *and* the virtual cursor share it), `Screens`' layout and `CaptureQueue`'s ring. Counted from the code, per event, on the four paths that matter: - **local key**: 2 — `counters`, snapshot read. An unmapped key adds one `counters`; a matched hotkey adds one ring push, and an escape hotkey one more `RoutingState` write. - **local mouse move**: 3 — `counters`, snapshot read, virtual-cursor write; 4 when Easy Mouse lets the move be offered as an `.edgeCandidate` (one ring push). `Screens` is not read on this path. - **remote key**: 3 — `counters`, snapshot read, one ring push. A `flagsChanged` pushes once per modifier transition instead, and twice more for a Caps Lock toggle. - **remote mouse move**: 6 — `counters`, snapshot read, virtual-cursor advance, `Screens`' layout, then two ring pushes (`.mouse` and `.edgeCandidate`); 5 when the candidate is suppressed. This is the worst path in the file. - **Swallowing is a separate flag from the destination.** ALL-machines mode sends input to every peer *and* keeps it locally (`InputHook.cs:361`), so `swallowKeys`/`swallowMouse` are set by the Engine, not derived here. - **The queue is a bounded ring of 4096 `CapturedInput`s** in `MWBMac/CaptureQueue.swift` (it needs a lock, which `MWBCore` may not import). Motion is coalesced on push against either of the last two entries — two, because one physical move queues a `.mouse` *and* an `.edgeCandidate` while a peer is controlled — stopping at the first entry that is not motion, so a transition is never reordered past. Latest position wins for an absolute move, deltas are **summed** for a relative one, and wheel deltas of the same axis are summed. A push that cannot be satisfied routes control local and raises `.overflow`, which `drain()` reports even when the ring is full (contracts C3). - **Keyboard encoding**: `wVk` from `KeyMap.vk(forKeycode:)`; `dwFlags` = `LLKHF` bits (`WM.cs:47-54`): `UP 0x80` on key-up, `EXTENDED 0x01` for the keys Windows marks extended (right Ctrl/Alt, arrows, Ins/Del/Home/End/ PgUp/PgDn, numpad Enter and divide, Num Lock, both Windows keys), `ALTDOWN 0x20` while either Option is down. Autorepeat (`CGEventField.keyboardEventAutorepeat`) is sent as repeated key-downs, which is what the Windows hook sees; hotkeys are **not** matched on repeats. - **Modifiers come from `flagsChanged`**, diffed against the previous device-specific flag word (`NX_DEVICELCTLKEYMASK 0x01`, `LSHIFT 0x02`, `RSHIFT 0x04`, `LCMD 0x08`, `RCMD 0x10`, `LALT 0x20`, `RALT 0x40`, `RCTL 0x2000`) into down/up pairs of `VK_LCONTROL 0xA2`/`RCONTROL 0xA3`, `LSHIFT 0xA0`/`RSHIFT 0xA1`, `LWIN 0x5B`/`RWIN 0x5C` (⌘ = Win, README D4), `LMENU 0xA4`/`RMENU 0xA5` (⌥ = Alt). Caps Lock is `VK_CAPITAL 0x14` as a down+up pair on each toggle of `NX_ALPHASHIFTMASK 0x10000`; `fn` is ignored. - **`KeyMap` is a static table in `MWBCore`** keyed by macOS virtual keycode (the `kVK_*` numbers written as literals with their names in comments — `Carbon` may not be imported there) for a US ANSI layout: letters, digits, F1–F20, arrows, editing keys, keypad, punctuation, volume, Return/Tab/Space/Escape/Delete/ForwardDelete and the eight modifiers. Keys with no VK are passed through to this Mac and counted (`EventTap.unmappedKeyCount`). The reverse map is what `input-inject` uses. - **Mouse encoding** (`InputHook.cs:245-260`, `WM.cs:27-40`): `dwFlags` = the `WM_*` id; buttons 0/1/2 = L/R/M, buttons 3/4 = `WM_XBUTTON*` with `WheelDelta` = 1/2, higher buttons stay local; dragging is a move, as the Windows hook reports it. Moves are absolute 0..65535 against the **primary** display (`Event.cs:112-113`) — or, in `MoveMouseRelatively` mode, `mouseEventDeltaX/Y` tagged by `Coordinates.tagRelative` (§4.4). Scroll: the fixed-point line delta × 120 accumulated into a per-axis remainder so trackpad scrolling emits whole 120-unit notches (`WM_MOUSEWHEEL` axis 1, `WM_MOUSEHWHEEL` axis 2). **The axis-2 sign against Windows' "positive means scroll right" is unverified** — a CP1 question (docs/protocol.md §10.4 note 10). - **The virtual cursor.** While a remote machine is controlled the real pointer is frozen, so the tap keeps its own position: seeded from the real pointer on every local move, advanced by `mouseEventDeltaX/Y`, clamped to `primary ± 1 px` exactly as `InputHook.cs:293-309` does. That is what goes on the wire and what edge detection sees. - **Hotkeys** (`InputHook.cs:539-658`, `MouseWithoutBordersProperties.cs`): switch-machine = ⌃⌥ + `HotKeySwitchMachine` VK offset by slot (F1..F4 → slots 0..3); lock = ⌘⌃⌥L (twice within 500 ms ⇒ ALL + lock); reconnect = ⌘⌃⌥R; toggle Easy Mouse = ⌘⌃⌥E; switch-to-all = disabled by default; switch-machine is ignored when Shift or ⌘ is also held (`InputHook.cs:604-610`). Escape set (contracts C2): switch-machine naming the local slot while control is remote, and ⌃⌥⌘Escape, which is checked first so no veto can shadow it. **Switch-to-all is the one hotkey that is not always swallowed**: its branch in `ProcessHotKeys` (`InputHook.cs:518-522`) falls through instead of returning `false`, so on Windows a chord that does not itself hold Ctrl+Alt toggles ALL mode *and* reaches the OS. `HotkeyMatch.swallows` reproduces that: true unless `switchToAll` requires neither ⌃ nor ⌥, in which case the tap queues the action and then handles the key as an ordinary keystroke. app-shell inherits this the moment it exposes a hotkey editor — the shortcut ships empty (`MouseWithoutBordersProperties.cs:30`) and an empty hotkey never matches (`Common.cs:127-129`), so nothing reaches it today. Windows' own swallow is narrower still (the fall-through is caught only when the VK also lands in the switch-machine range, `:611-620`); the ⌃⌥ test is the honest approximation and the residual case is a hotkey editor's problem, not the wire's. - **Easy Mouse** (`EasyMouseOption.cs`, `InputHook.cs:467-473`): the tap pushes `.edgeCandidate(point:now:)` on moves only when the mode allows it — always for `Enable`, while ⌃ / ⇧ is held for those modes, never for `Disable` — and never while controlling a remote in relative mode (`Event.cs:73`). The fullscreen rule is the extras lane's. - **Screens** (`WinAPI.cs:70-80, 115-184`): `CGGetActiveDisplayList` + `CGDisplayBounds`; primary = `CGMainDisplayID()`; desktop = union; corner points = every display's four corners, half-open as `SensitivePoints` is. Refreshed on `NSApplication.didChangeScreenParametersNotification`; `ScreenLayout.edgeConfig(blockCorners:moveRelatively:)` hands the Engine a ready `EdgeConfig`. - **Cursor** (`Common.cs:1482-1496`, `InputHook.cs:293-309`): while a remote is controlled, `CGAssociateMouseAndMouseCursorPosition(false)` keeps the real pointer parked (deltas still arrive) and `CGDisplayHideCursor` hides it; parking = warp to (primary centre-x, y = 4) when `HideMouse` is on, else primary centre; on return, show, re-associate, warp to the last local position — in that order, so a queued delta cannot beat the warp. `Cursor.park` applies the `destinationIsRemote || byHideMouseMessage` gate itself, so a `SwitchAction.parkCursor` maps onto it one-to-one (session-matrix Handshakes). - **Permissions**: `preflight()` stays; `request()` calls `CGRequestListenEventAccess()` / `CGRequestPostEventAccess()` and is invoked only from a UI action the user clicks (app-shell); a 5 s health check re-preflights and reports any change (contracts C2). Agents never call `request()`. - **Tap loss** (contracts C2): on `tapDisabledByTimeout`/`ByUserInput` the callback re-enables the tap with `CGEvent.tapEnable` **and** flips the snapshot to local, forgets the modifier state, then raises `.tapLost`; the Engine releases keys. - **Clocks.** `.edgeCandidate` timestamps come from `EventTap.now()` (`mach_absolute_time`). The Engine must use the same function for `Switcher`/`Edge`, or the 100 ms jump debounce compares two clocks. ## Handshakes ### Consumed - `session-matrix`: `Coordinates` (universal/relative encoding, the CG helpers), `EdgeConfig`, `Direction`, the `SwitchAction.parkCursor` consumer rule. - `wire-core`: `MouseData` for the values `CapturedInput` carries. ### Promised (to input-inject, app-shell, extras) As shipped 2026-09-16. Later lanes code against this, not against the sketch this section used to hold. ```swift // MWBCore/InputTypes.swift public enum InputTypes { public static let injectedEventTag: Int64 } // C4 public enum WindowsMessage { // WM.cs:27-40 static let mouseMove, leftDown, leftUp, leftDoubleClick, rightDown, rightUp, rightDoubleClick, middleDown, middleUp, middleDoubleClick, wheel, extraDown, extraUp, horizontalWheel: Int32 static let wheelDelta: Int32 // 120 } public enum KeyFlag { static let extended, injected, altDown, up: Int32 } // WM.cs:47-54 public enum Destination: Sendable, Equatable { case local, remote(UInt32); var isRemote: Bool } public enum EasyMouseMode: Int, Sendable, Equatable { case disable, enable, ctrl, shift } public struct ModifierState: Sendable, Equatable { var command, control, option, shift: Bool } public struct Hotkey: Sendable, Equatable { var vk: Int32; var command, control, option, shift: Bool var isEmpty: Bool func matches(vk: Int32, modifiers: ModifierState) -> Bool } public struct HotkeyConfig: Sendable, Equatable { var switchMachineVK: Int32; var lock, reconnect, toggleEasyMouse, switchToAll: Hotkey static let switchMachineSlots: Int // 4 static let escape: Hotkey // ⌃⌥⌘Escape, mac-only } public enum HotkeyAction: Sendable, Equatable { case switchToSlot(Int), lockMachine, lockAllMachines, reconnect, toggleEasyMouse, toggleSwitchToAll, escapedToLocal } public enum CapturedInput: Sendable { case key(vk: Int32, flags: Int32) case mouse(MouseData) case edgeCandidate(point: CGPoint, now: TimeInterval) case hotkey(HotkeyAction) case tapLost case overflow } public struct RoutingSnapshot: Sendable, Equatable { var destination: Destination var swallowKeys, swallowMouse: Bool var easyMouse: EasyMouseMode var moveMouseRelatively: Bool var hotkeys: HotkeyConfig var localSlot: Int? func routedLocal() -> RoutingSnapshot } // MWBCore/KeyMap.swift public enum KeyMap { static let back, `return`, capital, escape, leftWin, rightWin, leftShift, rightShift, leftControl, rightControl, leftMenu, rightMenu: Int32 static let keypadEnterKeycode: Int64 static func vk(forKeycode: Int64) -> Int32? static func keycode(forVK: Int32) -> Int64? static func isExtended(vk: Int32, keycode: Int64) -> Bool static let leftControlMask, leftShiftMask, rightShiftMask, leftCommandMask, rightCommandMask, leftOptionMask, rightOptionMask, rightControlMask, capsLockMask: UInt64 // NX_DEVICE* / NX_ALPHASHIFT static func modifiers(from flags: UInt64) -> ModifierState static func forEachModifierTransition(old: UInt64, new: UInt64, _ body: (Int32, Bool) -> Void) static func modifierTransitions(old: UInt64, new: UInt64) -> [(vk: Int32, down: Bool)] static func capsLockToggled(old: UInt64, new: UInt64) -> Bool } // MWBMac public final class RoutingState: Sendable { init(_ snapshot: RoutingSnapshot = .init(), virtualCursor: CGPoint = …) func read() -> RoutingSnapshot func write(_ snapshot: RoutingSnapshot) func update(_ body: @Sendable (inout RoutingSnapshot) -> Void) @discardableResult func routeLocal() -> Bool var virtualCursor: CGPoint { get set } func advanceVirtualCursor(dx: Double, dy: Double, clampedTo primary: CGRect) -> CGPoint } public enum CaptureNotice: Sendable { case tapLost, overflow } public final class CaptureQueue: Sendable { static let defaultCapacity: Int // 4096 init(capacity: Int = defaultCapacity) @discardableResult func push(_ input: CapturedInput) -> Bool func signal(_ notice: CaptureNotice) func drain() -> [CapturedInput] var depth: Int { get } } public struct CaptureConfig: Sendable, Equatable { var hotkeys: HotkeyConfig; var easyMouse: EasyMouseMode var moveMouseRelatively: Bool; var localSlot: Int? } public enum EventTapError: Error, Equatable { case creationFailed, runLoopSourceFailed } public final class EventTap: @unchecked Sendable { init(routing: RoutingState, queue: CaptureQueue, screens: Screens, config: CaptureConfig = .init(), onWake: @escaping @Sendable () -> Void) func start() throws func stop() var isRunning: Bool { get } func reconfigure(_ config: CaptureConfig) var realInputEventCount: UInt64 { get } // Session.tick takes this var unmappedKeyCount: UInt64 { get } static func now() -> TimeInterval // the lane's clock } public struct HotkeyMatch: Sendable, Equatable { var action: HotkeyAction; var routesLocal: Bool; var swallows: Bool } public struct HotkeyMatcher: Sendable { static let lockDoublePressWindow: TimeInterval // 0.5 var config: HotkeyConfig mutating func match(vk: Int32, modifiers: ModifierState, localSlot: Int?, destinationIsRemote: Bool, now: TimeInterval) -> HotkeyMatch? mutating func resetLockTimer() } public struct ScreenLayout: Sendable { var displays: [CGRect]; var primary, desktop: CGRect; var corners: [CGPoint] static func current() -> ScreenLayout func edgeConfig(blockCorners: Bool, moveRelatively: Bool) -> EdgeConfig } public final class Screens: @unchecked Sendable { init(onChange: (@Sendable () -> Void)? = nil) var layout: ScreenLayout { get } func refresh() func startObserving() // main thread func stopObserving() // main thread } public final class Cursor: Sendable { static func parkPosition(hideMouse: Bool, in layout: ScreenLayout) -> CGPoint @discardableResult func park(hideMouse: Bool, layout: ScreenLayout, destinationIsRemote: Bool, byHideMouseMessage: Bool) -> CGPoint @discardableResult func decouple(parkHidden: Bool, layout: ScreenLayout) -> CGPoint func recouple(to point: CGPoint?) func warp(to point: CGPoint) func hide(); func show() // balanced var isDecoupled: Bool { get } func restoreEverything() // atexit / signal handler } public struct PermissionState: Equatable, Sendable { public init(listen: Bool, post: Bool) let listen, post: Bool; var isComplete: Bool } public enum Permissions { static let healthCheckInterval: TimeInterval // 5 static func preflight() -> PermissionState @discardableResult static func request() -> PermissionState // user-initiated only static func startHealthCheck(interval: TimeInterval = healthCheckInterval, onChange: @escaping @Sendable (PermissionState) -> Void) -> PermissionHealthCheck } public final class PermissionHealthCheck: @unchecked Sendable { func cancel() } ``` Five deviations from the shape sketched at planning time, all deliberate: - **`isExtended` takes the keycode as well as the VK.** The keypad's Enter and Return share `VK_RETURN`, and the extended bit is the only thing that tells them apart (docs/protocol.md §10.4 note 6); a `vk`-only predicate cannot. - **`RoutingSnapshot` carries `easyMouse`, `moveMouseRelatively`, `hotkeys` and `localSlot`** as well as the routing. The callback needs all of them and there is no second lock; `reconfigure(_:)` writes that half and leaves the routing half alone. - **`Screens.onChange` is an init parameter, not a settable property**, so the class needs no lock around a closure. - **`CapturedInput` is not `Equatable`.** `CGPoint` is not, in a Foundation-only target. - **The tap owns the two counters `Event.InputEventCount`/`RealInputEventCount` stand for** — `realInputEventCount` is the value `Session.tick` wants (docs/protocol.md §10.4 note 8). ### Requested of input-inject (open) 1. `Injector` must stamp `CGEventField.eventSourceUserData` with `InputTypes.injectedEventTag` on **every** event it posts, including the synthetic key-ups of `releaseAll()`. An untagged event is captured and echoed straight back to the peer. 2. `Injector` performs `HotkeyAction.lockMachine` / `.lockAllMachines` by sending the chord — the tap swallowed the keys, so nothing reaches the peer otherwise (`InputHook.cs:548-562`). ### Requested of app-shell (open) 1. The Engine must timestamp `Switcher`/`Edge` with `EventTap.now()`. 2. The Engine owns `swallowKeys`/`swallowMouse`: set them false in ALL-machines mode, true for a single remote destination. 3. On `.tapLost`, `.overflow` and `.hotkey(.escapedToLocal)` the tap has already routed local; the Engine still owes `releaseAllKeys`, `Cursor.recouple` and the `HideMouse`/`MachineSwitched` housekeeping (contracts C2). 4. `Screens.startObserving()` and `stopObserving()` must be called on the main thread, after `NSApplication.shared` exists. ## Status / TODO - [x] `Sources/MWBCore/InputTypes.swift`: tag, `RoutingSnapshot`, `CapturedInput`, `HotkeyConfig`, `Hotkey`, `EasyMouseMode` (C3, C4). - [x] `Sources/MWBCore/KeyMap.swift`: keycode ↔ VK table, extended set, modifier transitions (`VK.cs`, `WM.cs:47-54`, `InputHook.cs:371-473`). - [x] `Sources/MWBMac/CaptureQueue.swift`: bounded ring, coalescing, overflow policy (C3). `Sources/MWBMac/RoutingState.swift`: the snapshot lock. - [x] `Sources/MWBMac/EventTap.swift`: the tap on its own run loop, callback per Assumptions, mouse/keyboard/scroll encoding (`InputHook.cs:110-133, 213-368`), tap-loss handling (C2). - [x] `Sources/MWBMac/Hotkeys.swift`: matching, double-press lock rule, the ignore-with-Shift/⌘ rule, escape set (`InputHook.cs:539-658`). - [x] `Sources/MWBMac/Screens.swift`, `Cursor.swift`: layout, corners, change notification; decouple/park/recouple (`WinAPI.cs:70-184`, `Common.cs:1482-1496`, `InputHook.cs:293-309`). - [x] `Sources/MWBMac/Permissions.swift`: add `request()` and the health check. - [x] `docs/protocol.md`: append §10.4 with anything learned, cited. - Not done, deliberately: the `SwitchLocation.Count` mechanic (`InputHook.cs:268-284`). See the work log. - Not done, deliberately: Ctrl+Alt+Delete as a switch-to-local trigger (`InputHook.cs:427-448`). See the work log. - Not done, deliberately: `HotKeyExitMM` (`InputHook.cs:588-603`), disabled by default on Windows and not in TODO §4. ## Work log ### 2026-09-16 — dev (Opus), the whole lane Nine files: two in `MWBCore` (`InputTypes.swift`, `KeyMap.swift`), seven in `MWBMac` (`RoutingState.swift`, `CaptureQueue.swift`, `Screens.swift`, `Cursor.swift`, `Hotkeys.swift`, `EventTap.swift`, `Permissions.swift`). `tools/gates.sh` green; nothing in this lane was *run*, by instruction — no event tap was created, no `CGEvent` posted, no cursor warped, no permission requested. The user tests. Decisions, in the order they were made: 1. **Config lives in the routing snapshot.** The callback needs `easyMouse`, `moveMouseRelatively`, `hotkeys` and `localSlot` on every event, and a second lock for them would double the per-event cost for no gain. `reconfigure(_:)` writes only those fields, so a settings change cannot race a switch. 2. **The virtual cursor is explicit.** Windows gets it for free: its hook sees the real pointer, which the OS keeps moving, and it clamps a copy (`InputHook.cs:287-309`). On macOS the pointer is frozen by `CGAssociateMouseAndMouseCursorPosition(false)`, so the same clamped position is kept in `RoutingState` and advanced from `mouseEventDeltaX/Y`. It is seeded on every *local* mouse move from the real pointer, which means the Engine does not have to seed it at a switch. 3. **`SwitchLocation.Count` is not ported.** On Windows the first couple of mouse events after a switch have their coordinates replaced by the landing point (`InputHook.cs:268-284`). Because the virtual cursor is ours, the same effect is reached by the Engine writing `RoutingState.virtualCursor` to the landing point when it applies `SwitchAction.moveCursor`, and the next move packet then carries landing + delta rather than landing exactly. One packet differs by one mouse delta; nothing else does. The counter, its reset and the `Event.cs:97` suppression all disappear with it. 4. **Easy Mouse is read from the live modifier state**, not from the "last key event was a Ctrl/Shift down" latch of `InputHook.cs:375, 467-473`. Windows clears the latch on *any* key-up, so on Windows typing while holding Ctrl in Ctrl mode silently disables edge switching until Ctrl is released and pressed again. Reading `modifiers.control` is simpler and strictly better; the wire is unaffected. 5. **Hotkeys are not matched on auto-repeat.** Windows matches every repeated `WM_KEYDOWN`, so holding ⌘⌃⌥L there reads as the 500 ms double press (`InputHook.cs:544`) and locks every machine. Skipping repeats costs nothing and removes an accident. 6. **Overflow always routes local, transition or not.** contracts C3 only demands it for transitions, but a ring that cannot take a *coalesced* motion event means the Engine has stopped draining entirely, and the safe state for a Mac whose Engine is stuck is to have its own keyboard back (invariant 3). 7. **Ctrl+Alt+Delete is not special.** On Windows it is a switch-to-local trigger (`InputHook.cs:427-448`) because the secure attention sequence is about to take the desktop away. macOS has no equivalent; ⌃⌥⌘Escape is the mac escape, and it is checked before every veto so nothing can shadow it. 8. **`Cursor.park` applies the gate itself.** The session-matrix Handshakes require the `destinationIsRemote || byHideMouseMessage` test (`Common.cs:1488`) before the pointer moves, and pushing it into the one function that moves the pointer means no consumer can forget it. `park` returns the position either way, because Windows records `LastPos` unconditionally. 9. **A relative move is coalesced by summing.** The first version replaced the older entry, which is right for an absolute position and loses motion for a `MOVE_MOUSE_RELATIVE` delta. Fixed in the same lane. 10. **Coalescing looks back two entries.** The first version matched only the last one, and in remote mode every physical move queues a `.mouse` followed by an `.edgeCandidate`, so the kinds alternate and nothing ever merged — the ring would have filled at two entries per move under a stalled Engine, which is precisely the case coalescing exists to survive. The scan stops at the first non-motion entry, so a button or key transition is never reordered past. Deviations from the brief: the brief listed the device masks 0x01..0x40 and omitted `NX_DEVICERCTLKEYMASK 0x2000`, without which the right Control key never produces a transition; it is in `KeyMap` and in §10.4 note 10. The brief also asked for `isExtended(vk:)`; it takes the keycode too, for the reason in Handshakes. Unverified, for CP1: the sign of `scrollWheelEventFixedPtDeltaAxis2` against Windows' `WM_MOUSEHWHEEL` (§10.4 note 10), and the `kVK_Help` → `VK_INSERT` and `kVK_ANSI_KeypadClear` → `VK_NUMLOCK` choices, which map by physical position rather than by label. ### 2026-09-16 — dev (Opus), rework after the QA verdict Four commits, one per finding, build-only verification again: no tap was created, no `CGEvent` posted, no cursor moved, no permission requested or preflighted. `xcrun swift-format format -i --recursive Sources Package.swift` then `tools/guard.sh -m 8 -t 900 -- tools/gates.sh` — green on each commit. 1. **`EventTap.thread` is now locked.** `runLoopLock` is renamed `stateLock` and guards `runLoopStorage` *and* `thread`, so the class comment's claim that every cross-thread field is behind a lock is true and `stop()` really is callable from any thread — including the contracts-C2 signal-handler path. `start()`'s check-and-claim is one critical section rather than a plain read of a `var`, so two concurrent starts cannot both install a tap; the failure path clears the field under the same lock. Nothing else moved: `machPort`, the modifier bookkeeping and the wheel remainders are still tap-thread-only. 2. **`handleMouse` reads `screens.layout` only when the destination is remote.** The read moved inside the `isRemote` branch — the only code that uses it — so the local branch, which is what runs for every mouse event on a Mac that is not controlling a peer, no longer pays for a discarded lock acquisition (invariant 4). This is the shape `handleScroll` already had. 3. **The lock claim is now counted, not asserted.** The old "three acquisitions at most (snapshot, virtual cursor, counters)" named two of the four reachable lock objects and undercounted every path. Replaced by a bullet listing all four (`EventTap.counters`, `RoutingState`'s box, `Screens`' layout, `CaptureQueue`'s ring) and the per-event count on each path: local key 2, local move 3 (4 with an edge candidate), remote key 3, remote move 6 (5 when the candidate is suppressed) — with the extras (unmapped key, matched hotkey, escape, one push per modifier transition) spelled out. The counts are post-fix-2; the remote-move worst case is unchanged because that path did need the layout. 4. **Switch-to-all is no longer unconditionally swallowed.** `ProcessHotKeys` (`InputHook.cs:518-522`) is the one branch that does not return `false` on a match, so the key reaches the OS unless the chord itself holds Ctrl+Alt and the `if (CtrlDown && altDown)` block below catches it. `HotkeyMatch` gains `swallows`; the `switchToAll` branch sets it from `control && option`, and `handleKey` queues the action and then falls through to ordinary key encoding when it is false — which mirrors `ProcessHotKeys` returning `true` and leaving the key to `KeyboardEvent` plus `CallNextHookEx`. Written up in docs/protocol.md §4.5 and in the Hotkeys assumption, together with the one narrowing that remains: Windows' actual swallow additionally requires the VK to sit in the switch-machine range (`:611-620`), which the ⌃⌥ test approximates. Nothing reaches this today — `Switch2AllPCShortcut` ships empty (`MouseWithoutBordersProperties.cs:30`) and an empty hotkey never matches (`Common.cs:127-129`) — so it is app-shell's hotkey editor that inherits it. `HotkeyMatch` gained a field, so the Handshakes block was updated with it. No other promised signature changed; no other lane's files were touched. ## QA log ### 2026-09-16 — QA (Sonnet) `tools/guard.sh -m 8 -t 600 -- tools/gates.sh` green (swift-format lint --strict, MWBCore layering, `swift build -Xswiftc -warnings-as-errors`). No event tap was created, no `CGEvent` posted, no cursor warped, no permission requested or preflighted — build/read-only per instruction. Checked every Status/TODO tick against its Windows source (`Class/InputHook.cs` whole file, `Core/Event.cs`, `Core/VK.cs`, `Core/WM.cs`, `Core/WinAPI.cs:70-184`, `Core/Common.cs:1482-1496`, `Class/EasyMouseOption.cs`, `MouseWithoutBordersProperties.cs`) and against docs/protocol.md §4.3–§4.5, §5, §10.4 and docs/contracts.md C2–C4: - Spot-checked 30+ `KeyMap` entries against `VK.cs` and the standard Win32 VK list (letters, digits, punctuation/OEM keys, F1–F20, keypad, volume, all eight modifiers, Insert/Delete/Help, Num Lock) — all correct, including the ones VK.cs itself doesn't define (OEM_4/5/6/7/102, F13–F20, volume), which are real Win32 constants InputSimulation.cs would still accept. - Hotkey defaults (`HotkeyConfig.init`) cross-checked against `MouseWithoutBordersProperties.cs:33-39,188,192` and `HotkeySettings(win,ctrl,alt,shift,code)` at `HotkeySettings.cs:51-59` — Win+Ctrl+Alt (no Shift) for lock/reconnect/toggle-EasyMouse, `0x70` for switch-machine, Switch2AllPC disabled — all match. - Modifier device masks, `rightControlMask 0x2000`, Caps Lock toggle, wheel×120 accumulation and sign, absolute-move formula (`Event.cs:112-113`), Easy Mouse gating (`Event.cs:71-79`, `InputHook.cs:467-473`), the Shift/⌘ veto scoped to the switch-machine family only (`InputHook.cs:604-610` vs `Common.HotkeyMatched`, `Common.cs:127-129`), the 500 ms double-press lock rule, `Cursor.park`'s `HideMouseCursor` gate (`Common.cs:1482-1496,1488`), and `Screens`' corner half-open convention vs `MonitorEnumProc` (`WinAPI.cs:70-113`) — all reproduce the cited Windows behaviour. Nothing in the nine files logs a keystroke, a VK, or a modifier state. Four findings, none of them wire/protocol breaks — all host-side Mac code-quality issues, listed most to least severe: 1. **`EventTap.thread` is unguarded shared state, and the class's own safety comment says otherwise.** `EventTap.swift:82` declares `private var thread: Thread?`, read at `:112` and written at `:118, :122` (both in `start()`) and `:133` (in `stop()`) — none of it behind a lock. `stop()` is documented "Safe to call from any thread" (`:127`), which is exactly the shape of the contracts-C2 crash/signal-handler recovery row ("best effort: re-associate the cursor and release keys" — the handler would call `EventTap.stop()`/`Cursor.restoreEverything()` off the tap thread), and the class-level comment at `:60-67` asserts "every field that crosses a thread boundary is behind a lock" — true of `runLoopStorage` (guarded by `runLoopLock`) but not of `thread`, which sits right next to it and isn't. A `start()` racing a signal-handler `stop()` is a genuine, if narrow, data race on a plain `var`, not proven safe by anything in this file. Fix: fold `thread` into `runLoopLock` (or its own lock) the same way `runLoopStorage` already is. 2. **`screens.layout` is fetched unconditionally on the single hottest path through the callback, for a value the majority case never reads.** `EventTap.swift:346` calls `screens.layout` (a locked read of `Screens`' `OSAllocatedUnfairLock`) before branching on `snapshot.destination.isRemote`; `layout` is only actually used inside that `isRemote` branch (`:352-353`). The `else` (local) branch (`:361-367`) — which is what runs for essentially every mouse move on a Mac that isn't currently controlling a peer, i.e. most of the time this tap is live — never touches `layout`, so it pays for a lock acquisition it throws away. `handleScroll` gets this right: it checks `snapshot.destination.isRemote` at `:438` *before* reading `screens.layout` at `:441`. Move the `handleMouse` read inside the `isRemote` branch to match. 3. **The README's per-event lock-count claim doesn't match the code.** `docs/features/input-capture/README.md:40` says "Three uncontended `OSAllocatedUnfairLock` acquisitions per event at most (snapshot, virtual cursor, counters)." A remote mouse-move event actually acquires: `counters` (1), `RoutingState`'s box lock twice (`routing.read()` + `routing.advanceVirtualCursor`), `Screens`' lock (finding 2), and `CaptureQueue`'s ring lock once or twice (`.mouse` and, on a move, `.edgeCandidate` are two separate `enqueue()` calls) — up to 6 acquisitions across 4 distinct lock objects, two of which (`Screens`, `CaptureQueue`) the claim never mentions at all. Not a functional bug (all four locks are uncontended, per-process, non-blocking), but it's a concrete, checkable claim in a feature README that CLAUDE.md's own perf rule ("Budget is measured, not asserted") says should be either accurate or removed. 4. **A Windows quirk this port doesn't reproduce, reachable only with a non-default `Switch2AllPCShortcut`.** `InputHook.ProcessHotKeys` (`InputHook.cs:518-522`) never returns `false` for a matched `HotKeySwitch2AllPC`, unlike every other hotkey branch — so on Windows, if that hotkey is configured to something that doesn't *also* require Ctrl+Alt, the key reaches the OS (`CallNextHookEx`) in addition to toggling ALL-machines mode. `HotkeyMatcher.match` (`Hotkeys.swift:65-67`) and `EventTap.handleKey` (`EventTap.swift:280-284`) always swallow a matched hotkey. Unreachable today — `Switch2AllPCShortcut` ships disabled (`Code=0`, `MouseWithoutBordersProperties.cs:30`) and `Common.HotkeyMatched` requires `!hotkey.IsEmpty()` (`Common.cs:127-129`) — so this only matters once app-shell exposes a hotkey editor and a user picks a non-default, non-Ctrl+Alt combo for it. Worth a one-line note in the Assumptions section so app-shell doesn't have to rediscover it. No typos or trivially-wrong comments found to fix directly; all four findings need an actual code or prose change, so none were applied here. Verdict: REWORK ## Review - 2026-09-16 (lead): inspected per `docs/loop.md` §5 after one rework round. Gates green run by me; nine files in the brief's list plus TODO §4, protocol §10.4 and this README. Read the tap callback in full: injected tag passes through first, tap-loss re-enables and routes local before anything else, hotkeys matched on press only, escape flips routing inside the callback, unmapped keys stay local and are counted, `swallowKeys`/`swallowMouse` decide the return. QA spot-checked 30+ VK values and the encodings. Verdict: **merge**. Carry into input-inject: tag every posted event via the source's `userData`, including `releaseAll()` key-ups; perform the lock hotkeys by chord; `isExtended(vk:keycode:)` exists because keypad Enter shares `VK_RETURN`. Carry into app-shell: the open requests in this README (`EventTap.now()` timestamps, ownership of the swallow flags, `releaseAll` + `Cursor.recouple` after `.tapLost`/`.overflow`/ `.escapedToLocal`, `Screens.startObserving()` on the main thread). Unverified until CP1: horizontal wheel sign, `kVK_Help→VK_INSERT`, `KeypadClear→VK_NUMLOCK` (protocol §10.4 note 10).