Files
2026-09-16 04:01:06 -07:00

698 lines
41 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# app-engine
## Goal
The part of the app that makes the pieces a running program: the
`Engine` actor that contracts C1–C3 name as the owner of all shared
state, the `Settings` model in the PowerToys schema, the mapping from
settings to every lane's config struct (C4), the wiring
tap → edge → switcher → channel → injector, and every recovery row of
C2 implemented end-to-end. It ships `mwb` as a real `NSApplication`
(LSUIElement) with a placeholder status item — just enough to run —
so the lead can smoke it headless before the `app-ui` lane builds the
real menu and settings window. This is the lane that finally answers
the open requests lanes 3, 4 and 5 left for "app-shell".
## Assumptions
- **`Engine` is one `actor` in the `mwb` target.** It owns: `Switcher`,
`PacketSequencer`, `ReplayFilter`, `ControlChannel`, `EventTap`,
`RoutingState`, `CaptureQueue`, `Injector`, `Cursor`, `Screens`,
`Settings`. Nothing else holds a reference to those except through
the Engine. **As shipped**, the sinks do not hop with `Task { await …
}` at all: the channel's `EngineSink`, the tap's wake-up, the 1 s
timer, the permission health check, `NSWorkspace.didWakeNotification`,
the display-change observer and the settings file watcher all push an
`EngineEvent` into **one** `AsyncStream`, and a single
`Task` started *inside* the actor (so it inherits its isolation)
drains that stream in order. Four callback queues are therefore
serialised exactly once.
- **Draining the capture ring**: `EventTap`'s `onWake` closure bumps a
`DispatchSourceUserDataAdd` (the shape input-capture asked for: no
allocation, no blocking, invariant 4); that source's handler yields
`.capturedInput`, and the actor calls `queue.drain()` and handles each
`CapturedInput` in order: `.edgeCandidate` → `switcher.crossing(...)`
timestamped with `EventTap.now()`; `.key`/`.mouse` → stamp once with
the sequencer and forward to `.peer(desMachineID)` or `.all` in ALL
mode (C1); `.hotkey` → the actions below; `.tapLost`/`.overflow` →
`recoverLocal(reason:)`. One drain that saw any real input calls
`channel.noteUserActivity()` once — the sessions only ask whether the
counter *moved* since their own previous beat (`Common.cs:545-559`),
so one bump per drain says exactly what `SendAwakeBeat` needs.
- **`SwitchAction` dispatch** (`EngineActions.swift`) is the port of what
`MachineStuff.SwitchToMachine` / `Helper.HelperThread` / `Event.cs`
do around a switch: `.send(packet)` → forwarded unchanged (`Switcher`
already stamped it); `.parkCursor` → `Cursor.park` per the consumer
rule (move only when `destinationIsRemote || byHideMouseMessage`);
`.moveCursor` → **recorded, and applied only when the machine being
switched to is this one**, which is what `Helper.HelperThread` does
(protocol §10.6 note 1); the routing snapshot is rewritten with
`destination` and `swallowKeys`/`swallowMouse` = remote and not ALL
mode (input-capture request 2); `channel.markControlled(peerID:)` on
**every** switch including back to local (control-channel request 2);
`injector.releaseAll()` on every switch that lands control back on this
Mac — the tail of `perform(_ actions:)`, so the `ByeBye`, edge-crossing
and `NextMachine` paths are covered as well as the hotkeys
(`Helper.cs:120-123`, `MachineStuff.cs:1047`,
`InitAndCleanup.cs:214-243`) — and on every lock and mode change; `.persistMatrix`
/ `.persistMachinePool` → `SettingsStore.update`.
- **Hotkeys**: `.switchToSlot(n)` → `releaseAll()` then
`switcher.switchToMachine` (`InputHook.cs:626-655`); `.lockMachine` →
forward `Injector.lockChord(for:)` to the machine in control as
sequenced `Keyboard` packets (input-inject request 1);
`.lockAllMachines` → ALL mode, chord, back out of ALL mode, then
`Injector.lockThisMac()` (`InputHook.cs:544-566`); `.reconnect` →
`channel.reopenAll()`; `.toggleEasyMouse` → flip the setting between
Disable and Enable only, save, re-apply the configs; `.toggleSwitchToAll`
→ ALL mode; `.escapedToLocal` → `recoverLocal(.escapeHotkey)`.
- **Recovery** (`Recovery.swift`, C2): one `recoverLocal(reason:)` on the
actor. It routes the snapshot local, and — when control was remote —
performs `switcher.switchToMachine(named: localName)`, which is what
Windows does on a `ByeBye` (`Common.cs:626`), so the machine we were
driving is told to park and our own pointer lands in the middle of the
primary screen. Windows reaches the same place more slowly on a plain
socket error — `SocketStuff.cs:1561-1563` only marks the machine dead
and the 100 ms timer takes control home once nothing is connected
(`frmScreen.cs:442`) — but contracts C2 requires it at once, which is
what `Switcher.connectionLost` already does. Then
`injector.releaseAll()`, `cursor.recouple(to: nil)` (show and
re-associate **without moving** — a `.tapLost` while control was
already local must not jerk the user's pointer), `markControlled(nil)`
and a log line. Called from: the escape hotkeys, `.tapLost`,
`.overflow`, a disconnect of the controlled peer for any reason
(`.closed`, `.readError`, `.sendError`, `.invalidKey`, `.stall`,
`.timeout`, …), Input Monitoring being revoked, and `Engine.stop()`.
The quit/crash path is `AppLifecycle.swift`'s `EmergencyRelease`:
`applicationWillTerminate`, an `atexit` handler and a
`DispatchSourceSignal` for SIGTERM/SIGINT/SIGHUP, all of which call
`Cursor.restoreEverything()` and `Injector.releaseAll()`
**synchronously, without the actor** — both are documented safe from
any thread by their own lanes. The three signal handlers then call
`EmergencyRelease.sayGoodbye()`, which queues `ByeBye` on the channel
and waits 150 ms for it, so contracts C2's last row holds on that path
too: `ControlChannel` is `Sendable` and hops to its own queue, so it is
the one piece of Engine-owned state a handler may touch.
`Engine.stop()` does the same thing on the graceful path, waiting
150 ms for the wire (`InitAndCleanup.cs:192-215`) before it closes.
- **Reopen countdown** (control-channel request 1): a 1 s timer on the
actor; while nothing is connected, `channel.reopenAll()` every **30 s**,
which is both Windows' cadence (`frmScreen.cs:425-427`, `count % 300`
on a 100 ms timer) and the channel's own connect budget. Also
immediately on `NSWorkspace.didWakeNotification` and on a display
change.
- **`Settings`** (`MWBCore/Settings.swift`): the raw `properties` tree is
what is stored, with typed accessors over it, so properties this port
does not implement round-trip untouched and a file shared with a
Windows machine never loses the Windows side's settings. Exact
PowerToys names, `{"value": …}` boxing, `HotkeySettings` shape and
defaults (protocol §10.6 note 5). Stored at
`~/Library/Application Support/mwb-mac/settings.json`, mode 0600,
written to a temp file and renamed, with the mode set again on the
final path afterwards so a file that arrived from elsewhere at 0644
does not stay there. First run generates `SecurityKey`
(`SecurityKey.random()`), `MachineID` (`Int32.random(in: 1...max)`,
`Setting.cs:1048-1070`) and `DeviceID` (UUID). `PackageID`, `LastX`,
`LastY`, the pool and the matrix are written on exit. A
`DispatchSource` file watcher reloads on external change
(`Setting.cs:197-207`); a key, port, name or id change reopens the
sockets, a matrix change is replicated to the peers, everything else
rewrites the configs.
- **Hostname** (D7): `gethostname()` with the domain suffix stripped,
ASCII, ≤ 32. A name that fails is not fatal to the *process* — the
status item says why — but the Engine starts nothing, because a
machine nobody can resolve cannot usefully join a matrix.
- **Placeholder UI**: `NSStatusItem` with a title-only first item
("mwb 0.1.0-dev — running — 1 connected — controlling …", or
"— permissions missing: …", or "— host name unusable: …"), "Request
Permissions…" (the only call to `Permissions.request()` in the
repository, on the user's click), "Reconnect" and Quit. `app-ui`
replaces it.
- **Logging** (`MWBMac/Log.swift`): `os.Logger` plus a rotating file at
`~/Library/Logs/mwb-mac/mwb.log` (1 MB × 3). No API in the file can
take a `KeyboardData` or a key string; peer names and statuses are all
that is written.
- **Single instance**: `flock` on
`~/Library/Application Support/mwb-mac/mwb.pid`; a second launch
writes one line to stderr and exits 1.
## Handshakes
### Consumed
Everything published by wire-core, session-matrix, control-channel,
input-capture and input-inject, as their Handshakes sections read on
2026-09-16. Two gaps found while consuming them are filed below.
### Promised (to app-ui, clipboard, extras)
As shipped 2026-09-16. Later lanes code against this, not against the
sketch this section used to hold.
```swift
// MWBCore/Settings.swift
public enum JSONValue: Sendable, Equatable, Codable { case null, bool, int, double, string, array, object }
public enum SettingsError: Error, Equatable { case malformed(String) }
public struct Settings: Sendable, Equatable, Codable {
public static let schemaName: String // "MouseWithoutBorders"
public static let schemaVersion: String // "1.1"
public init() // the PowerToys defaults
// scalars, all PowerToys names:
public var securityKey, machinePoolString, name2IP, deviceID: String
public var wrapMouse, shareClipboard, transferFile, hideMouseAtScreenEdge: Bool
public var validateRemoteMachineIP, sameSubnetOnly, blockScreenSaverOnOtherMachines: Bool
public var moveMouseRelatively, blockMouseAtScreenCorners: Bool
public var showClipboardAndNetworkStatusMessages, disableEasyMouseWhenFullscreen: Bool
public var matrixOneRow: Bool
public var easyMouse: EasyMouseMode
public var easyMouseFullscreenExcludedApps, machineMatrixNames: [String]
public var machineID, lastX, lastY, packageID, hotKeySwitchMachine: Int32
public var tcpPort: UInt16
public var toggleEasyMouseShortcut, lockMachineShortcut, reconnectShortcut,
switch2AllPCShortcut: Hotkey
// derived:
public var matrix: Matrix // get and set
public func pool(now: TimeInterval) -> MachinePool
public mutating func setPool(_ pool: MachinePool)
public var hotkeys: HotkeyConfig // read-only, for CaptureConfig
@discardableResult public mutating func generateMissingIdentities() -> Bool
public static func defaultURL() -> URL
public static func load(from url: URL) throws -> Settings
public func save(to url: URL) throws // atomic, 0600
}
public final class SettingsStore: @unchecked Sendable {
public init(url: URL = Settings.defaultURL()) throws
public var fileURL: URL { get }
public var current: Settings { get } // any thread
public func update(_ body: (inout Settings) -> Void) throws
public func onExternalChange(_ handler: @escaping @Sendable (Settings) -> Void)
public func startWatching(); public func stopWatching()
}
// MWBMac/Log.swift
public struct Log: Sendable {
public static let engine, app, settings: Log
public static let subsystem: String
public init(category: String)
public func info(_ message: String); public func error(_ message: String)
public func debug(_ message: String) // os.Logger only, never the file
public static func fileURL() -> URL
public static func startFileLogging(); public static func stopFileLogging()
}
// mwb/Engine.swift
public enum RecoveryReason: Sendable, Equatable {
case escapeHotkey, tapLost, captureOverflow, controlledPeerLost(String?),
permissionsLost, quitting
public var text: String
}
public struct RecoveryNote: Sendable, Equatable { public var reason: RecoveryReason; public var at: Date }
public struct EngineSnapshot: Sendable {
public var peers: [PeerStatus]; public var controlled: String?; public var broadcasting: Bool
public var permissions: PermissionState; public var tapRunning, canInject: Bool
public var easyMouse: EasyMouseMode; public var localName: String
public var hostnameProblem: String?; public var lastRecovery: RecoveryNote?
}
public actor Engine {
public init(store: SettingsStore, localName: String, hostnameProblem: String? = nil)
public func start()
public func stop() async
public func observe(_ handler: @escaping @Sendable (EngineSnapshot) -> Void)
public var snapshot: EngineSnapshot { get }
public func apply(_ new: Settings) // after an external settings change
public func switchTo(slot: Int); public func switchToAll()
public func reconnect(); public func toggleEasyMouse()
public func lockControlledMachine(); public func lockAll()
public func recoverLocal(reason: RecoveryReason)
// `let` properties of Sendable type, so they read without `await`:
let injector: Injector; let cursor: Cursor; let screens: Screens
}
```
Six deviations from the shape sketched at planning time, all deliberate:
- **`Engine.init` takes `localName` and `hostnameProblem`, not just the
store, and does not `throw`.** Resolving and validating the host name
is the *process's* job (D7) and its failure has to be reportable in
the menu bar; an Engine that threw would leave nothing to report with.
`SettingsStore.init` is the throwing part, and `AppDelegate` catches it.
- **`Settings.pool` is `pool(now:)` + `setPool(_:)`, not a `var`.**
`MachinePool(string:now:)` needs a clock and `MWBCore` has none.
- **`SettingsStore.onExternalChange` is a method, not a settable
property**, so the store needs no lock discipline at the call site.
- **`Engine.stop()` is `async`** — it waits 150 ms between `sayGoodbye()`
and `stop()` so the `ByeBye` reaches the wire, which is the Windows
order (`InitAndCleanup.cs:192-215`).
- **`observe(_:)` replaces `var onSnapshotChange`**: a settable closure
property on an actor is `await`-only to set and awkward to call.
- **`lastRecovery` is a `RecoveryNote` struct, not a tuple**, so the
snapshot stays `Sendable` and printable.
Rules the consuming lanes must honour:
- **Nothing but the Engine stamps a packet `Id`** (contracts C1). A lane
that wants to send something adds an Engine method; it does not reach
for the sequencer or the channel.
- **`Settings` round-trips unknown properties.** Never rebuild the
properties dictionary from a fixed list — adding a property means
adding an accessor, and the Windows side's settings survive.
- **`Permissions.request()` may be called from exactly one place**, the
menu item the user clicks (CLAUDE.md, Workflow).
### Requested of session-matrix (answered 2026-09-16)
1. **`PacketSequencer` is used from two queues by design and was not
thread-safe.** Contracts C1 says the process has one sequencer and
that the app stamps application packets; the Engine therefore calls
`sequencer.next()` on the actor while each `Session` calls it on the
channel's queue for its own `Handshake`/heartbeat/`Hi`/`ByeBye`
(`Session.swift:402-403`). `next()` was `value = value &+ 1` with no
synchronisation, so a lost update could hand two packets the same `Id`
and the receiver's replay ring would drop the second.
**Done**, as a cross-lane edit the lead authorised: `next()` and
`current` hold an `NSLock` (Foundation only, so MWBCore's layering
holds) and `PacketSequencer` is `@unchecked Sendable`
(`Sources/MWBCore/Sequencing.swift`). The session-matrix Handshakes
section says so. `ReplayFilter` is only ever touched on the channel's
queue and is unchanged.
### Requested of input-capture (1 answered 2026-09-16, 2 open)
1. **`PermissionState` had no public initialiser.** It declared
`public let listen` / `public let post` and no `init`, so the
memberwise one was `internal` and no other target could build a value —
`EngineSnapshot`'s default had to call `Permissions.preflight()`,
which is a TCC query. **Done**, as a cross-lane edit the lead
authorised: `public init(listen: Bool, post: Bool)`
(`Sources/MWBMac/Permissions.swift`), and `EngineSnapshot.permissions`
now defaults to `PermissionState(listen: false, post: false)`.
2. **`Cursor` publishes no "where is the pointer now".** The relative-mode
`NextMachine` path needs `GetCursorPos` on the *receiving* side
(`Receiver.cs:154`, protocol §10.6 note 3), so `Engine.pointerPosition()`
reads it with `CGEvent(source: nil)?.location`. A `Cursor.position`
would keep the one remaining CoreGraphics call out of `mwb`.
### Requested of control-channel (open)
1. **No way to send a `Heartbeat` on demand.** `Receiver.cs:253` answers a
peer's `Hello` with `Common.SendHeartBeat()` so the peer learns us
immediately. Our `Session` already sends one right after the handshake
(`Session.swift:381`), so nothing is broken today, but the `Hello`
case in `Engine.dispatch` is a no-op where Windows replies.
### Requested of app-ui (open)
1. The matrix, the pool and the security key are edited through
`SettingsStore.update`; the Engine notices through the file watcher
and re-applies everything. There is no second path, and there must
not be one.
2. `EngineSnapshot.hostnameProblem`, `.permissions` and `.canInject` are
the three states that mean "this app cannot do its job" and all three
want a visible colour, not a log line.
### Answering the earlier lanes' open requests
| request | answer |
|---|---|
| control-channel 1: reopen countdown | `Recovery.reopenCountdown()`, 30 s while `connectedIDs` is empty, plus wake and display change |
| control-channel 2: `markControlled` on every switch | `EngineActions.syncRouting()`, which every `perform(_:)` ends with — including back to local (`nil`) |
| input-capture 1: `EventTap.now()` timestamps | every `Switcher`/`Edge` call in the Engine uses it |
| input-capture 2: Engine owns the swallow flags | `syncRouting()`: `swallowKeys`/`swallowMouse` = `destinationIsRemote`, so false in ALL mode |
| input-capture 3: `releaseAll` + `recouple` + housekeeping after `.tapLost`/`.overflow`/`.escapedToLocal` | all three land in `recoverLocal(reason:)` |
| input-capture 4: `Screens.startObserving()` on the main thread | `AppDelegate.startEngine()`, after `NSApplication.shared` exists |
| input-inject 1: lock chord forwarding | `EngineActions.forwardLockChord(to:)`, single press and double press |
| input-inject 2: `releaseAll()` on every C2 row, switch, mode change and lock | `recoverLocal`, `SwitchAction.releaseAllKeys`, `switchTo(slot:)` |
| input-inject 3: `ScreenLayout` into every `inject` | `Engine.dispatch` passes `screens.layout` |
| input-inject 4: `HotKeyLockMachine` → `InjectorConfig.lockMachine` | `applyConfiguration()`, re-applied on every settings change |
| input-inject 5: show `canInject` | `EngineSnapshot.canInject`, rendered in the status item |
## Status / TODO
- [x] `Sources/MWBCore/Settings.swift`: schema, defaults, load/save,
first-run generation, matrix/pool round-trip, config mapping (C4)
(`MouseWithoutBordersProperties.cs:165-206`, `Setting.cs:479-511,
1048-1083`, `Common.cs:906`). The `ChannelConfig`/`CaptureConfig`/
`InjectorConfig` half of the mapping lives in
`mwb/EngineActions.swift`, because those types are in `MWBNet` and
`MWBMac` and `MWBCore` may not import either.
- [x] `Sources/MWBMac/Log.swift`: logger + rotating file.
- [x] `Sources/mwb/Engine.swift`: the actor, sink stream, drain loop,
C1 forwarding, packet dispatch (`Receiver.cs` `ProcessPackage`
cases for Mouse, Keyboard, HideMouse, MachineSwitched,
NextMachine, Matrix, Heartbeat/Awake/Hello learning, ByeBye).
**Not done, deliberately**, with reasons: `MachineSwitched` and
every `Clipboard*` case are the clipboard lane's; `Awake` does not
yet call the equivalent of `Common.HumanBeingDetected()` (it needs
`IOPMAssertionDeclareUserActivity`, i.e. IOKit, which this lane may
not import, and the receive half of
`BlockScreenSaverOnOtherMachines` is the extras lane, CP3);
`Heartbeat_ex`/`_l2`/`_l3` key propagation is out of scope
(README D6).
- [x] `Sources/mwb/EngineActions.swift`: `SwitchAction` and hotkey
dispatch per Assumptions (`MachineStuff.cs:1008-1050`,
`InputHook.cs:516-655`).
- [x] `Sources/mwb/Recovery.swift`: `recoverLocal`, every C2 trigger
wired, reopen countdown (`frmScreen.cs:425-449`).
- [x] `Sources/mwb/AppLifecycle.swift` + `main.swift`: `NSApplication`
delegate, placeholder status item, single instance, signal/atexit
handlers, wake/screen notifications, `--check-permissions` and
`--version` kept.
- [x] `docs/protocol.md`: appended §10.6 with six findings, cited.
## Work log
- **2026-09-16 (dev)** — lane built in one pass on `main` from `ca9be2e`;
three commits. Gates green on the last one.
*What was built.* `MWBCore/Settings.swift` (the PowerToys schema over a
raw property tree, plus `SettingsStore`), `MWBMac/Log.swift`
(`os.Logger` + a 1 MB × 3 file), and the four `mwb` files: `Engine.swift`
(the actor, the single `AsyncStream` every callback funnels through, the
capture drain, and the `ProcessPackage` port), `EngineActions.swift`
(`SwitchAction`, the hotkeys, and `Settings` → every lane's config),
`Recovery.swift` (C2 and the reopen countdown) and `AppLifecycle.swift`
(single instance, `NSApplication`, the placeholder status item and the
emergency release), with `main.swift` gaining the no-argument "run the
app" case.
*Key decisions.*
1. **One `AsyncStream`, not per-callback `Task`s.** The brief allowed
`Task { await engine.… }` hops; an unbounded `AsyncStream` plus a
pump `Task` started *inside* the actor is strictly better — it
inherits the actor's isolation, so ordering across the channel
queue, the tap thread, two timers and three notification observers
is guaranteed by construction rather than by hope.
2. **The tap wake-up goes through a `DispatchSourceUserDataAdd`.**
`AsyncStream.Continuation.yield` allocates; `source.add(data: 1)` is
an atomic add. That is the shape input-capture asked for and keeps
invariant 4 honest, and it coalesces many wake-ups into one drain.
3. **`.moveCursor` is recorded, not obeyed.** Reading
`Helper.HelperThread` closely (protocol §10.6 note 1) showed the
Windows pointer only goes to `SwitchLocation` when the machine being
switched to is the local one; obeying it unconditionally would throw
the user's pointer at the *remote* landing coordinates on every
switch away. `noteCursorLanding` therefore stores a target and
`syncRouting` applies it when it recouples.
4. **`syncRouting()` is the tail of every `perform(_:)`.** The routing
snapshot, `markControlled` and the cursor's coupling are three things
that must always agree with `Switcher.desMachineID`; deriving all
three in one place after the actions have run is the only way to be
sure a new `SwitchAction` cannot forget one of them.
5. **`recoverLocal` ends with `cursor.recouple(to: nil)`.** An early
draft recoupled to the remembered park position, which would have
jerked the pointer to the top of the screen whenever `.tapLost` or a
revoked grant fired while control was already local. `nil` means
"show and re-associate, do not move", and it is idempotent.
6. **The permission health check installs the tap, not just reports it.**
The 5 s check already had to notice a *revoked* grant (C2); noticing
the grant arriving and retrying `EventTap.start()` costs four lines
and means the user does not have to restart the app after ticking
the box in System Settings.
7. **`DispatchSourceSignal`, not `signal(2)`.** A C signal handler may
only call async-signal-safe functions, and the emergency release
does `queue.sync` and posts `CGEvent`s. A dispatch signal source
runs the same code on an ordinary queue, which is both safe and
still catches SIGTERM/SIGINT/SIGHUP. `atexit` keeps the C handler
because `atexit` handlers do not run in signal context.
*Deviations from the brief and the Assumptions as written.*
- **Reopen countdown is 30 s, not the 10 s this README sketched.**
Windows checks `count % 300` on a 100 ms timer (`frmScreen.cs:427`)
and the control-channel lane's request 1 says 30 s explicitly; 30 s
also coincides with the channel's own connect budget, so the
countdown fires exactly as the budget expires instead of resetting a
live one every 10 s.
- **`Engine.init` signature** and five smaller API shapes: listed under
Handshakes with reasons.
- **`NextMachine` is accepted only while `EasyMouse == Enable`.**
Windows also accepts it while the Ctrl/Shift Easy-Mouse key is held
(`Event.IsSwitchingByMouseEnabled`), but that flag lives inside the
tap and is not published. Affects only the two non-default Easy Mouse
modes combined with `MoveMouseRelatively`; noted in protocol §10.6
note 3 and worth a line in the extras lane.
- **An empty matrix is seeded with this Mac's own name in slot 0** at
first start, so the settings file is self-explanatory. Windows shows
its setup form instead; a peer's name still has to be added by hand
(or by app-ui) before anything is dialled.
- **`Settings.swift` and `Engine.swift` are both a little over 600
lines** — over the 300–600 target, well under the 800 "consider
splitting" line. (No count is quoted here on purpose: the last one
went stale within a commit. `wc -l` is the authority.) Splitting
either would mean a file outside this lane's list.
*Verification.* `tools/gates.sh` green (lint --strict, MWBCore
layering, build with warnings-as-errors); `.build/debug/mwb --version`
and `--check-permissions` both behave as before (the latter exits 3 on
this machine, which has neither grant). **The app itself was not
launched**: doing so would create an event tap, post events and trigger
TCC prompts (CLAUDE.md invariant 5 and the lane brief). Everything from
`NSApplication.run()` inwards — the status item, the tap, the channel,
every C2 row — is unexercised and is CP1's job.
- **2026-09-16 (dev, rework)** — the QA verdict's three findings, the two
cross-lane requests the lead authorised, and the stale number. Six
commits, one per item; gates green on the last.
1. **Finding 1, `settings.json` mode.** `Settings.save(to:)` now passes
`.usingNewMetadataOnly` to `replaceItemAt` *and* sets
`.posixPermissions: 0o600` on the path it actually wrote, with the
reason in a comment. QA was right about the mechanism: without the
option `replaceItemAt` copies the original item's metadata onto the
replacement, so a file copied in from a PC (README D3) kept its mode
for the life of the install, `SecurityKey` and all. The belt-and-
braces `setAttributes` afterwards means the guarantee no longer
depends on which of the two branches wrote the file, nor on
Foundation's documented behaviour staying documented.
(`Sources/MWBCore/Settings.swift`.)
2. **Finding 2, `releaseAll()` on the other switch-to-local paths.**
Fixed rather than documented. `perform(_ actions:)` remembers
`desMachineID`/`isBroadcasting` before running the actions and calls
`injector.releaseAll()` afterwards when the destination moved and
the new destination is this Mac — which is what
`Helper.HelperThread` does (`Helper.cs:120-123`), since its event is
set by `SwitchToMachine` (`MachineStuff.cs:1024`) *and*
`PrepareToSwitchToMachine` (`Event.cs:203`). That covers the
received `ByeBye`, the edge crossing and the `NextMachine` packet.
The one deliberate narrowing, in the doc comment: it fires only when
the destination actually moved. Our `releaseAll()` releases the keys
*this Mac injected*, so an unconditional call on a switch that left
control local — a matrix edit while a peer is driving us — would
drop that peer's modifiers mid-keystroke. Windows has no equivalent
hazard because its release is physical-key based.
(`Sources/mwb/EngineActions.swift`.)
3. **Finding 3, `ByeBye` on the signal path.** Implemented, not
documented away, and it is the few lines the lead hoped for:
`EmergencyRelease` gains `arm(channel:)` and `sayGoodbye()`, the
Engine arms it in `startChannel()` and disarms it in `stop()`, and
the SIGTERM/SIGINT/SIGHUP handler calls `run()` then `sayGoodbye()`
then exits. Nothing here wakes the actor: `ControlChannel` is
`Sendable` and every method hops to its own serial queue, which is
precisely the property the rest of the Engine's state lacks. The
150 ms wait is the same grace `Engine.stop()` gives the packet
(`InitAndCleanup.cs:192-215`); keys and pointer are already back
before it starts, so invariant 3 is not traded for it. Best effort
by construction — a stuck channel queue loses the packet and the
peer falls back to socket-level detection
(`SocketStuff.cs:1561-1563`). `docs/contracts.md` needed no
amendment. (`Sources/mwb/AppLifecycle.swift`, `Engine.swift`.)
4. **Request 1, `PacketSequencer`.** Cross-lane edit, authorised: the
counter is under an `NSLock` and the class is `@unchecked Sendable`
(`Sources/MWBCore/Sequencing.swift`). `NSLock` is Foundation, so
MWBCore's layering gate is untouched. The session-matrix README's
Handshakes signature block and its "one sequencer per process" rule
both now say it is thread-safe, and why (C1: one sequencer, two
queues).
5. **Request 2, `PermissionState.init`.** Cross-lane edit, authorised:
`public init(listen:post:)` added (`Sources/MWBMac/Permissions.swift`),
and the workaround removed — `EngineSnapshot.permissions` defaults to
`PermissionState(listen: false, post: false)` instead of running a
TCC query to obtain a value. The input-capture README's signature
line carries the new init.
6. **The stale "598 lines".** Replaced with prose and no number at all;
quoting a count in a work log guarantees it is wrong by the next
commit, and the judgement it supported (both files under 800, no
split) is unchanged. Today's counts, for the record only:
`Settings.swift` 644, `Engine.swift` 611.
*Verification.* `xcrun swift-format format -i --recursive Sources
Package.swift` then `tools/gates.sh` green (lint --strict, MWBCore
layering, build with warnings-as-errors). `.build/debug/mwb --version`
still prints its line. **The app was not launched** — unchanged from
the first pass, and for the same reason (CLAUDE.md invariant 5): every
path touched here (the signal handlers, the switch tail, the channel
arming) posts events or opens sockets when exercised, so it is CP1's
job with the user present. `Settings.save` was not exercised against a
real file either; the reasoning is Foundation's documented
`replaceItemAt` behaviour plus QA's own empirical check, and the
`setAttributes` line is there so the result does not depend on that
reasoning being right.
## QA log
- **2026-09-16 (QA)** — reviewed against CLAUDE.md, `docs/contracts.md` C1–C5,
`docs/protocol.md` §10.6, and the Windows source (`Core/Receiver.cs`,
`Core/MachineStuff.cs:1007-1050`, `Core/Helper.cs`, `Class/InputHook.cs:539-658`,
`Form/frmScreen.cs:285-300, 425-461`, `Class/Setting.cs`,
`MouseWithoutBordersProperties.cs:165-206`, `MouseWithoutBordersSettings.cs`).
No test suite exists for this lane yet (`swift test` not run — none of the
gates call for it); build-only per CLAUDE.md invariant 5. The app itself was
never launched; only `.build/debug/mwb --version` and `--check-permissions`
were run (confirmed both create no settings file, log file or tap — checked
`~/Library/Application Support/mwb-mac/` and `~/Library/Logs/mwb-mac/` stay
absent after both).
*Gates.* `tools/gates.sh` green: `swift-format lint --strict` clean, `MWBCore`
layering clean, `swift build -Xswiftc -warnings-as-errors` clean.
*Verified clean.* Every Status/TODO tick has code behind it. C1 (single
`PacketSequencer`/`ReplayFilter`, ids stamped once in `Switcher`/`Engine.
stampAndForward`, `Session` re-stamps only its own connection packets) holds;
the open thread-safety request against session-matrix is correctly filed, not
silently worked around. C3's actor/routing-snapshot/queue shape matches, and
`swift build -warnings-as-errors` (Swift 6 strict concurrency) accepting the
file rules out illegal actor-isolation escapes; the only two `@unchecked
Sendable` types (`SettingsStore`, `LogFile`) are lock- or queue-disciplined
and justified in a doc comment, matching `EmergencyRelease`. No force-unwrap,
`try!`, `fatalError` or `precondition` in any changed file. No log call in
`Log.swift`/`Engine.swift`/`EngineActions.swift`/`Recovery.swift` takes a
`KeyboardData` or key string — grepped every `Log.*` call site by hand.
`Permissions.request()` has exactly one call site (`AppLifecycle.swift:271`,
the status-item click). C4's config mapping is complete: `ChannelConfig`,
`CaptureConfig`, `EdgeConfig` and `InjectorConfig` each have every field
populated from `Settings` in `EngineActions.swift`/`Engine.init`, matched
field-by-field against the struct definitions. Settings JSON matches
`MouseWithoutBordersProperties.cs:165-206` and `HotkeySettings.cs:121-136`
property-by-property (envelope, `{"value":…}` boxing, the bare-array
exception for `MachineMatrixString`, lower-case hotkey field names,
non-negative `MachineID`). Hostname validation (D7) matches the table exactly
and gates `Engine.start()`. Single instance (`flock`) runs before anything
else touches the tap or a socket.
*Findings.*
1. **[correctness/security, CONFIRMED] `Settings.save(to:)` does not
reliably enforce 0600 on a pre-existing file.**
`Sources/MWBCore/Settings.swift:437-438` calls
`FileManager.default.replaceItemAt(url, withItemAt: temp)` with no
options. `FileManager.replaceItemAt`'s documented default behaviour is to
preserve the *original* item's metadata (permissions included) onto the
replacement unless `.usingNewMetadataOnly` is passed — I confirmed this
empirically with a standalone Swift snippet (create a 0644 file, replace
it with a 0600 temp file via `replaceItemAt` with no options: the result
stays 0644). The first-ever write for a brand-new install goes through
the `moveItem` branch instead (no pre-existing destination), so a fresh
install does end up at 0600 and *stays* 0600 on every later `update()`,
because the file `replaceItemAt` is "preserving metadata from" is by then
already 0600. But README's own §Settings advertises copying
`settings.json` between a Mac and a PC as a supported way to share a
`SecurityKey` and matrix (D3) — a file arriving that way (scp, AirDrop, a
shared drive, restored from a backup) will generally not already be
0600, and every subsequent `SettingsStore.update()` (a matrix edit, a
pool update, `persistOnExit`, `replaceMachineID`, …) will silently keep
whatever permissive mode it arrived with, forever, because
`replaceItemAt` keeps re-propagating the old mode forward. The file
stores `SecurityKey` in the clear. Fix is one line:
`.usingNewMetadataOnly` on the `replaceItemAt` call, or an explicit
`setAttributes` on `url` after it.
Windows side: `Setting.cs` writes the file with no special ACL either,
but that is a difference worth having on our side, not a reason to drop
the 0600 promise this port's own README (`## Assumptions`, "Stored at
… mode 0600") makes.
2. **[correctness, PLAUSIBLE] the third place Windows releases held keys on
a switch (`Helper.cs:120-123`, cited by this lane's own
`docs/protocol.md` §10.6 note 1) is wired for some switch-to-local paths
and not others.** `injector.releaseAll()` runs on the hotkey path
(`EngineActions.swift:136`, `switchTo(slot:)`), on the broadcast toggle
(`Switching.swift:236`, `switchToBroadcast`'s `.releaseAllKeys` action)
and unconditionally in `recoverLocal` (`Recovery.swift:43`). It does
**not** run when a received `ByeBye` packet ends control locally
(`Engine.swift:509-510`, `case .byeBye: perform(switcher.
handleByeBye(packet, now: now))` → `Switching.swift:307-313` →
`switchToMachine`, which never appends `.releaseAllKeys`), nor when an
edge crossing or a `NextMachine` packet lands the target back on this
machine (`Engine.swift:460-464` `considerCrossing`, `:489-497` the
`.nextMachine` case → `Switching.swift:172-197` `prepareToSwitch`, same
gap). On Windows, `SwitchToMachine` and `PrepareToSwitchToMachine` both
call `Common.EvSwitch.Set()` unconditionally (`MachineStuff.cs:1024`,
`Event.cs:203`), which always wakes `Helper.HelperThread`, which always
calls `ReleaseAllKeys()` once `NewDesMachineID == MachineID` — i.e. on
every one of these paths, not just three of five. Two mitigating facts
keep this from being a CONFIRMED finding: the `ByeBye`-packet gap is
almost always covered moments later when the socket actually closes and
`noteDisconnected` calls `recoverLocal` (idempotent); and this port's
`Injector.releaseAll()` only clears state *this Mac itself injected*
(`Injector.swift:44-49` doc comment — it is the controlled-side release,
not a Windows-style `GetAsyncKeyState`-based physical-key release), so on
the edge-crossing path there is normally nothing for it to release
anyway. Still, the asymmetry is undocumented (no line in "Deviations
from the brief" says this is intentional) and inconsistent with the
belt-and-braces style the rest of `Recovery.swift` uses (e.g.
`cursor.recouple(to: nil)` unconditionally, "Idempotent" in the doc
comment) — worth either a one-line call or a documented reason not to.
3. **[completeness, PLAUSIBLE, low] contracts C2's last row ("sockets send
ByeBye" on the atexit/signal path) is not implemented for
SIGTERM/SIGINT/SIGHUP.** `AppLifecycle.swift:199-213`
(`installSignalHandlers`) only calls `EmergencyRelease.shared.run()`
(cursor + injector, synchronous, no actor — correctly matches CLAUDE.md
invariant 3 and this file's own header comment) and then `exit(0)`; it
never attempts `channel?.sayGoodbye()`. This looks architecturally
forced rather than an oversight — `channel` is actor-isolated state and
the header comment is explicit that this path must not touch the actor
— but the contract table literally promises ByeBye on this row and
nothing in the README flags the gap as a deliberate deviation the way
other trade-offs in the Work log are flagged. A peer that was being
driven when the app receives SIGTERM (e.g. a `kill`, or logout sending
SIGTERM to background apps) will only learn we're gone via its own
socket-level detection, not a `ByeBye`. Worth either attempting
`NSApp.terminate(nil)` (the graceful path already sends `ByeBye` and has
150 ms of headroom) for the three catchable signals, or amending
`docs/contracts.md` C2 to say so.
4. **[docs, trivial, not fixed] stale line count.** The Work log says
"`Engine.swift` 598" lines; `wc -l` on the reviewed tree gives 606. Both
numbers are well under the 800-line "consider splitting" line CLAUDE.md
sets, so the judgment the entry draws from it (no split needed) still
holds — the number is just stale, most likely from a commit after the
one the prose was written against. Not fixed (not a comment, and the
line the instructions permit me to fix without a finding is typos/wrong
comments, not a work-log narrative number); left for the dev to correct
or drop.
*Judgement on the two >600-line files.* `Sources/MWBCore/Settings.swift`
(628) and `Sources/mwb/Engine.swift` (606) are both under the 800-line
"consider splitting" mark, so CLAUDE.md does not require a reason to be
written down at all, let alone a split — the README documents the choice
anyway. Read top to bottom, both pass the one-sentence test: `Settings.
swift` is "the settings schema and the file that stores it" (mostly
mechanical get/set pairs, one per PowerToys property — a split by property
group would just scatter that repetition across files without changing what
a reader needs to hold in their head); `Engine.swift` is "the actor plus its
event pump and packet dispatch" (the `EngineActions.swift`/`Recovery.swift`
extension-file split already pulled the two things that *do* read as
separate responsibilities — switch/hotkey handling and C2 recovery — out of
it). No split recommended.
Verdict: REWORK
## Review
- 2026-09-16 (lead): inspected per `docs/loop.md` §5 after one rework
round. Gates green run by me; diff limited to the brief's files plus
the three authorised cross-lane edits (`Sequencing.swift` lock,
`PermissionState.init`, two README lines), TODO §6, protocol §10.6.
Read the drain loop, `stampAndForward`, `inputDestination`,
`considerCrossing`, `reportEdgeToController` and `Switcher.
nextMachinePacket`: every application packet is stamped exactly once
(Engine or Switcher, both through the one locked sequencer) and
forwarded unchanged — C1 holds. Sink, tap wake, ticker and watchers
funnel through one `AsyncStream` — C3 holds. QA walked C2's rows and
C4's mappings. Files at 644/611 lines are under the 800 mark with
reasons recorded. Verdict: **merge**. Carry into app-ui: settings are
edited only through `SettingsStore.update`; `Engine.observe` is the
one feed for the UI; `Permissions.request()` only on a click.
Unexercised until CP1: everything from `NSApplication.run()` inwards.