session-matrix
Goal
All the protocol logic above the bytes and below the sockets, in
MWBCore with no I/O: the per-connection Session state machine
(handshake, trust, dedup, heartbeats, liveness — docs/protocol.md §1.4,
§3.2–§3.3), the machine model (Matrix, MachinePool, live matrix,
Matrix packet replication — §4.1–§4.2), switching (desMachineID, ALL
mode, MachineSwitched, NextMachine) and the pure geometry of edge
detection and coordinate normalisation (§4.3–§4.4). The control-channel
lane feeds sockets into Session; the input-capture lane feeds cursor
points into Edge. Both must be able to use this code without reading
the Windows source again.
Assumptions
- Sans-I/O.
Sessionowns no socket, timer or thread. The caller hands it decrypted packet bytes (feed), asks what to send (drain() -> [Data], already framed and ready forCipherWriter) and what happened (events), and callstick(now:)from its own timer. Time is aTimeIntervalin seconds that the caller supplies; nothing in this lane reads a clock. Windows counts milliseconds (Common.GetTick), so every ported constant is divided by 1000 and cited with its millisecond value. - One
Sessionper TCP connection, client or server side — Windows runs the sameMainTCPRoutinefor both (SocketStuff.cs:1261-1565). Which of a peer's two connections is kept is the net lane's policy (SocketStuff.cs:1980-2004), not this lane's. - The duplicate-client check is not here. Windows drops a second
client socket to the same peer inside
MainTCPRoutine(SocketStuff.cs:1421-1428) using state only the socket layer has. This lane emits.connected(peerName:peerID:)and thecontrol-channellane applies its own policy, as this README already said it would. - Trust is per connection and gates everything. Until the
HandshakeAcknonce check passes, the only packetsSessionacts on areHandshake/HandshakeAck; other packets are counted and after 10 the session reports.invalidKeyand asks to close (SocketStuff.cs:1387-1406). Application packets are surfaced to the caller only from a trusted session (CLAUDE.md invariant 2). - A failed read is a packet. Windows builds a
PackageType.Error(0 bytes read) orPackageType.Invalid(short read) package out of the read itself (SocketStuff.cs:574-578, 588-593) and runs it through the whole loop body, so a malformed read spends the same untrusted budget as a garbage packet; only the 0-byte kind also feeds the six-in-a-row close (:1330-1364). The caller therefore passes the byte count —noteReceiveError(bytesReceived:)— and must not translate a short read into a 0-byte one (docs/protocol.md §10.2 note 10). - Sequence numbers and the replay ring are process-wide, as on
Windows (
Common.cs:906,Receiver.cs:40-82): aPacketSequencerand aReplayFilterare created once by the app and shared by everySession. The sequencer's start value comes from the persistedPackageIDsetting and the app stores it back; this lane exposescurrentfor that. - Sequence once, distribute unchanged (contracts C1). Application
packets are stamped by the app — one
Idfrom the process-widePacketSequencer— and the identicalPacketis handed to each target session viaforward(_:), which never re-stamps.Sessionstamps ids itself only for the packets it originates (Handshake,HandshakeAck, heartbeats,Hi,ByeBye), which are per-connection on Windows too; that path isprivate func originate(_:). This is enforced by the API, not by convention: as of 2026-09-16 there is no publicSession.send-style entry point, so a caller cannot send an unstamped application packet on one connection even by mistake. - Each
Sessionbeats for its own connection. Windows broadcasts one heartbeat from a global timer to every socket, so a peer pair's two connections carry the sameIdand the receiver's replay ring collapses the second (Common.cs:906-916). Ours stamps a freshIdper session, so a peer processes both copies.AddToMachinePoolis idempotent, so the observable behaviour is identical; it costs one extra 32-byte packet per peer per minute. - Heartbeats follow the 100 ms timer cadence exactly:
count % 600 == 0(60 s) whenBlockScreenSaveris on, elsecount % 3000(300 s) (frmScreen.cs:566-575);AwakewhenBlockScreenSaveris on and the raw real-input counter moved since this session's own previous beat, elseHeartbeat(SendAwakeBeat,Common.cs:542-559; counterEvent.cs:51-55). Machine liveness is 25 min (MachineStuff.cs:32).Heartbeat_exkey propagation is not ported (README D6); those packets are accepted and ignored. MatrixandMachinePoolare value types with the exact persisted string forms (MachineMatrixStringcomma-joined,Name:Id,Name:Id,Name:Id,Name:Id,MachinePoolHelpers.cs:16-43,MachinePool.cs:287-301), soSettingscan round-trip them unchanged from a PowerToys machine.- Learning peers from
Heartbeat/Hello/Awake(MachineStuff.cs:712-777) adds to the pool and, when the name is new, rebuilds the matrix from the pool slot-for-slot so control is bidirectional at once, then queues the fourMatrixpackets — reported asSwitchActions, the app decides to persist and reconnect. A peer that is already known produces no actions: Windows returns from that branch atMachineStuff.cs:737, before theUpdateMachinePoolStringSetting()at:755, so a heartbeat from a known machine refreshes the in-memory id and timestamp and writes nothing. This lives onSwitcher, not onSession: the pool and matrix are app-wide and a session is per-connection. - Geometry uses
CGRect/CGPointfrom Foundation (no CoreGraphics import) in the Windows convention: top-left origin, y down, integer pixels. Theinput-capturelane converts from CoreGraphics display bounds, which use the same convention. Foundation gives the types but none of CoreGraphics' members — there is no.zero, nominX, noEquatable— soCoordinatesprovidespoint,rect,bounds,centreandemptyRect, and nothing inMWBCoreextends a CG type (an extension would shadow the real API inMWBMac). All the maths is done in 64-bitIntand truncated, matching C#'sintdivision for every realistic screen while never trapping. - Edge decisions are pure:
Edge.evaluate(point:now:)on a struct holding the rectangles, the mode flags and the last-jump time returnsnilor aJumpnaming the direction and the universal 0..65535 landing point, computed by the four-case rule of §4.4. The debounce (100 ms,MachineStuff.cs:217) lives here, not in the tap. - Relative-move biases (
MOVE_MOUSE_RELATIVE = 100000,XY_BY_PIXEL = 300000,Event.cs:32-33) are encoded/decoded inCoordinates; nothing else in the app should know the numbers.
Handshakes
Consumed
wire-core:Packet,PackageType,Framing,MachineID, exactly as published indocs/features/wire-core/README.mdHandshakes.
Promised (to control-channel, input-capture, input-inject, app-shell)
As shipped 2026-09-16. Later lanes code against this, not against the
sketch this section used to hold. Seven files in MWBCore; nothing here
does I/O, reads a clock or logs.
// Sequencing.swift — the two process-wide counters (§1.4)
public final class PacketSequencer { // not Sendable: app-wide, one queue
public init(start: Int32 = 0) // resumes the PackageID setting
public func next() -> Int32 // pre-increment, wrapping
public var current: Int32 { get } // persist this back
}
public final class ReplayFilter {
public static let windowSize = 50
public init()
public func isDuplicate(_ packet: Packet) -> Bool // 4 exempt types
}
// Session.swift — one TCP control connection (§3.2-§3.3)
public enum SocketStatus: Int, Sendable {
case na = 0, resolving, connecting, handshaking, error, forceClosed,
invalidKey, timeout, sendError, connected
}
public enum InvalidKeyReason: Sendable, Equatable {
case tooManyUntrustedPackets, handshakeAckMismatch
}
public enum SessionEvent: Sendable, Equatable {
case status(SocketStatus)
case connected(peerName: String, peerID: UInt32)
case packet(Packet) // trusted, framed, de-duplicated
case invalidKey(InvalidKeyReason)
case selfConnection
case close // always the last event
}
public struct SessionConfig: Sendable {
public var localName: String, magic: UInt32, localID: UInt32
public var blockScreenSaver: Bool // 60 s vs 300 s heartbeats
public var peerNameHint: String? // DNS name; HandshakeAck wins
public init(localName:localID:magic:blockScreenSaver:peerNameHint:)
}
public final class Session { // not Sendable: one per connection
public static let fastHeartbeat: TimeInterval = 60
public static let slowHeartbeat: TimeInterval = 300
public static let untrustedPacketLimit = 10
public init(config:sequencer:replay:isClient:)
public func start(now: TimeInterval) // queues 10 Handshake packets
public func feed(_ plaintext: Data) // 32-then-32 reassembly inside
public func noteReceiveError(bytesReceived: Int) // a 0-byte / short read
public func report(_ new: SocketStatus) // .resolving, .sendError, …
public func tick(now: TimeInterval, inputEventCount: UInt64)
public func forward(_ packet: Packet) // app-stamped: Src + framing only
public func probe() // Hi
public func sayGoodbye() // ByeBye
public func drain() -> [Data] // write these through CipherWriter
public func events() -> [SessionEvent]
public var status: SocketStatus { get }
public var peerName: String? { get }
public var peerID: UInt32? { get }
public var isOutbound: Bool { get }
}
// MachinePool.swift — who is out there (§4.1)
public struct MachineInfo: Sendable, Equatable { public var name: String
public var id: UInt32; public var lastSeen: TimeInterval }
public struct MachinePool: Sendable, Equatable {
public static let maxMachines = 4
public static let heartbeatTimeout: TimeInterval = 1500 // 25 min
public init(); public init(string: String, now: TimeInterval)
public var string: String { get } // "Name:Id,…"
public var all: [MachineInfo] { get }
public func machine(named: String) -> MachineInfo? // case-insensitive
public func resolveID(name: String) -> UInt32? // nil for ID.NONE
public func name(for id: UInt32) -> String?
public mutating func learn(_ name: String, keeping matrix: Matrix) -> Bool
public mutating func updateID(name:id:updateTimestamp:now:) -> Bool
public mutating func setDisconnected(name:now:) -> Bool
public mutating func setDisconnected(id:now:) -> Bool
public func isAlive(_ info:, now:, connectedIDs: Set<UInt32>) -> Bool
public mutating func resetDeadMachineIDs(localName:matrix:now:connectedIDs:firstLoaded:)
}
// Matrix.swift — the four slots and their packets (§4.1-§4.2)
public enum Direction: Sendable, Equatable { case left, right, up, down }
public struct Matrix: Sendable, Equatable {
public static let slotCount = 4
public private(set) var names: [String] // always exactly 4
public var oneRow: Bool // MatrixOneRow
public var wrap: Bool // MatrixCircle / WrapMouse
public init(names: [String] = [], oneRow: Bool = true, wrap: Bool = true)
public init(string: String, oneRow: Bool = true, wrap: Bool = true)
public var string: String { get }
public mutating func setName(_ name: String, at slot: Int)
public func slot(of name: String) -> Int?
public func contains(_ name: String) -> Bool
public func live(connectedNames: Set<String>) -> [String] // must include us
public func neighbour(of: String, direction: Direction, live: [String],
isReachable: (String) -> Bool) -> String?
}
public enum MatrixPackets {
public static func encode(_ matrix: Matrix) -> [Packet] // 4, slot order
public static func apply(_ packet: Packet, to: inout Matrix) -> Bool // true on slot 4
}
// Coordinates.swift — pixels ↔ 0..65535, and the two biases (§4.4)
public struct UniversalPoint: Sendable, Equatable { public var x, y: Int32 }
public enum Coordinates {
public static let universalMax: Int32 = 65535
public static let relativeBias: Int32 = 100_000 // MOVE_MOUSE_RELATIVE
public static let pixelBias: Int32 = 300_000 // XY_BY_PIXEL
public static func toUniversal(_ p: CGPoint, in rect: CGRect) -> UniversalPoint
public static func fromUniversal(_ u: UniversalPoint, in rect: CGRect) -> CGPoint
public static func mouseMove(_ p: CGPoint, primary: CGRect) -> UniversalPoint
public static func absoluteMove(_ u:, desktop:, primary:) -> UniversalPoint
public static func tagRelative(dx: Int32, dy: Int32) -> UniversalPoint
public static func isRelative(_ u: UniversalPoint) -> Bool
public static func untagRelative(_ u: UniversalPoint) -> UniversalPoint
public static func tagPixels(_ p: CGPoint) -> UniversalPoint
public static func isPixels(_ u: UniversalPoint) -> Bool
public static func untagPixels(_ u: UniversalPoint) -> CGPoint
// CG helpers, because Foundation gives the types without the members:
public static func point(_ x: Int, _ y: Int) -> CGPoint
public static func rect(left: Int, top: Int, right: Int, bottom: Int) -> CGRect
public static func bounds(_ rect: CGRect) -> (left: Int, top: Int, right: Int, bottom: Int)
public static func centre(of rect: CGRect) -> CGPoint
public static let emptyRect: CGRect
}
// Edge.swift — did the cursor leave, and where does it land (§4.3-§4.4)
public struct EdgeConfig: Sendable { // not Equatable: CGRect is not
public var desktop, primary: CGRect
public var corners: [CGPoint] // every monitor's four corners
public var blockCorners, moveRelatively: Bool
public init(desktop:primary:corners:blockCorners:moveRelatively:)
}
public struct Edge: Sendable {
public static let skipPixels = 1, jumpPixels = 2, cornerRadius = 100
public static let jumpDebounce: TimeInterval = 0.1
public var config: EdgeConfig
public private(set) var lastX, lastY: Int32 // the LastX/LastY settings
public init(config: EdgeConfig)
public mutating func crossing(at point: CGPoint, cursorIsLocal: Bool,
broadcasting: Bool, lastJump: TimeInterval, now: TimeInterval) -> Direction?
public func landing(direction:, from point:, targetIsLocal:, cursorIsLocal:)
-> UniversalPoint
}
// Switching.swift — which machine has the keyboard and mouse
public struct Jump: Sendable, Equatable {
public var direction: Direction; public var targetID: UInt32
public var targetName: String; public var landing: UniversalPoint
}
public enum SwitchAction: Sendable, Equatable {
case send(Packet) // already addressed
case parkCursor(destinationIsRemote: Bool, byHideMouseMessage: Bool)
case moveCursor(UniversalPoint) // pixel-tagged means pixels
case releaseAllKeys
case desMachineChanged(id: UInt32, name: String?)
case persistMatrix, persistMachinePool, reopenSockets
case remoteClipboardWanted
}
public final class Switcher { // not Sendable: app-wide
public init(localName:localID:matrix:pool:edge:sequencer:)
public let localName: String; public let localID: UInt32
public private(set) var matrix: Matrix
public private(set) var pool: MachinePool
public var edge: Edge // app updates .config on display change
public var connectedIDs: Set<UInt32> // maintained by control-channel
public var connectedNames: Set<String>
public private(set) var desMachineID: UInt32
public private(set) var desMachineName: String?
public private(set) var newDesMachineID: UInt32
public var isBroadcasting: Bool { get }
public var destinationIsRemote: Bool { get } // the HideMouseCursor gate
public func isConnected(to id: UInt32) -> Bool
public func crossing(at point: CGPoint, now: TimeInterval) -> Jump?
public func prepareToSwitch(to:landing:now:) -> [SwitchAction]
public func switchToMachine(named:now:) -> [SwitchAction]
public func switchToBroadcast(_ on: Bool, centerCursor: Bool) -> [SwitchAction]
public func nextMachinePacket(toController:target:landing:now:) -> Packet?
public func learn(from packet: Packet, now:) -> [SwitchAction]
public func applyMatrix(_ packet: Packet) -> [SwitchAction]
public func handleByeBye(_ packet: Packet, now:) -> [SwitchAction]
public func handleHideMouse() -> [SwitchAction]
public func connectionLost(id:now:) -> [SwitchAction]
public func setMatrix(_ new: Matrix) -> [SwitchAction]
}
Rules the consuming lanes must honour:
- Nothing reaches
.packetbefore the handshake.Sessiondelivers application packets only from a trusted connection, afterFraming.openand after the replay ring (CLAUDE.md invariant 2)..closeis always the last event a session emits; close the socket and drop the session. - One
PacketSequencerand oneReplayFilterper process, shared by everySession, as on Windows. Neither isSendable; nor areSessionandSwitcher. Everything in this lane lives on one queue. Switchernever does I/O. It returns[SwitchAction]; the app performs them in order. A.sendpacket is already sequenced and addressed, so it goes to every connection throughSession.forward(_:)— the only application-traffic entry point there is. One broadcast must keep oneIdacross a peer's two connections or the receiver's replay ring will not collapse the duplicate (contracts C1).- Anything else the app originates is stamped once, by the app. Input,
HideMouse,MachineSwitched,NextMachine,Matrixand clipboard chunks take anIdfrom the singlePacketSequencerand are thenforwarded to each target session unchanged.Sessionsequences only its own handshake, heartbeats,HiandByeBye. .parkCursorrecords a position; it moves the OS cursor only whendestinationIsRemote || byHideMouseMessage.Switcherpre-evaluates both halves of theHideMouseCursorgate (Common.cs:1488) so no consumer needsdesMachineID, anddestinationIsRemoteis computed after the switch, asSwitchToMachinedoes (MachineStuff.cs:1025). The hidden position (primary screen, horizontal centre,y = 4withHideMouseon, else vertical centre) is remembered asLastPosevery time, because that is what the cursor is restored to. An injector that moves unconditionally will jerk the local cursor to the top of the screen every time control comes home — on everyByeByeand every peer disconnect (Common.cs:622-625).tick(now:inputEventCount:)takes the raw process-wide real-input counter, not a verdict.inputEventCountis ourEvent.RealInputEventCount(Event.cs:51-55, bumped by the hooks atInputHook.cs:223, 345): the caller increments it on every real input event and hands the same value to every session on a tick. EachSessionremembers the value it saw at its own previous beat and sendsAwake (21)instead ofHeartbeat (20)iff the counter moved since then andblockScreenSaveris on, re-recording it either way (SendAwakeBeat,Common.cs:545-559). A caller must not pre-compute that comparison on a clock of its own: sessions beat on independent schedules (nextHeartbeatis seeded from each connection's ownstart(now:)), so a shared boundary in the caller is generally out of phase with a connection's beat and can reportHeartbeatfor input that postdates that connection's previous beat — which silently disables the peer'sBlockScreenSaver(Receiver.cs:245-248→Common.HumanBeingDetected). Signature changed 2026-09-16, requested by control-channel; it wastick(now:userActive:).Matrix.live(connectedNames:)must be given the local machine's own name, because the WindowsIsConnectedToanswers yes for it without a socket.Switcher.crossingadds it; a direct caller must too.Edge.crossingreadslastJumpbut never writes it. The debounce clock isSwitcher's, set byprepareToSwitch.
Requested of control-channel (open)
- The duplicate-client-socket policy (
SocketStuff.cs:1980-2004) and the ">10 failed attempts from one endpoint ⇒ quit" counter (SocketStuff.cs:1482-1499) are keyed by remote endpoint and belong to the channel;Sessionreports.invalidKeyand.closeand counts nothing across connections.
Status / TODO
Sources/MWBCore/Sequencing.swift:PacketSequencer,ReplayFilter(Common.cs:906,Receiver.cs:40-82).Sources/MWBCore/Session.swift: state machine, handshake, trust guards, 32-then-32 reassembly with the invalid-is-64-bytes rule (protocol §10.1), heartbeats/liveness,Hi/ByeBye(SocketStuff.cs:1261-1565,Common.cs:499-513, 662-676, 822-847,Receiver.cs:200-270).Sources/MWBCore/Matrix.swift:Matrix,MatrixPackets, live matrix (MachineStuff.cs:883-1006, 935-945).Sources/MWBCore/MachinePool.swift: pool, learning, liveness (MachinePool.cs,MachinePoolHelpers.cs,MachineStuff.cs:712-777). Learning itself lives onSwitcher(it touches the matrix too); the pool owns the storage, the string form and the timeouts.Sources/MWBCore/Switching.swift:desMachineID/ ALL mode /MachineSwitched/HideMouseemission /NextMachine(MachineStuff.cs:1030-1050,Common.cs:559-585,Event.cs:212-231,Receiver.cs:156-170, 284-291, 383-388).Sources/MWBCore/Edge.swift+Coordinates.swift: §4.3–§4.4 (MachineStuff.cs:181-283, 325-478,Event.cs:105-113,InputSimulation.cs:160-173,Receiver.cs:147-153).docs/protocol.md: append a §10.2 with anything learned, cited.
Not done, deliberately:
Heartbeat_exkey propagation (Receiver.cs:210-243): out of scope per README D6 — the key is typed on both sides.Heartbeat_exis accepted, refunds the untrusted budget exactly asHeartbeatdoes, and is delivered to the app, which ignores it.- The
Hireceive path: nothing to port. Windows never processes aHipacket at all (protocol §10.2 note 2);Session.probe()exists for the send side, which is the part that has an effect. SwitchLocation.Count(MouseLocation.cs,InputHook.cs:267-283): the counter that makes the next hook callback report the switch location instead of the real cursor is a property of the event tap, not of this lane.SwitchAction.moveCursorcarries the location; how many callbacks consume it isinput-capture's to decide.ReleaseAllKeys's 2 s rate limit (InitAndCleanup.cs:214-221): it guards aSendInputburst, so it belongs with the injector ininput-inject. This lane only says.releaseAllKeys.
Work log
2026-09-16 — dev (Opus)
Ported all seven files; tools/gates.sh green. One sentence each:
Sequencing.swift(83) — the two process-wide counters that decide a packet's identity.Session.swift(386) — one connection's handshake, trust gate, reassembly and heartbeat.MachinePool.swift(208) — who is out there, in the persistedName:Id,…form.Matrix.swift(242) — the four slots, the neighbour search and the fourMatrixpackets.Coordinates.swift(201) — pixels ↔ 0..65535 and the two biases.Edge.swift(144) — did the cursor leave the screen, and where does it land.Switching.swift(345) — which machine has the keyboard and mouse.
Decisions and deviations:
Switcheris a new type the plan did not name. The plan put switching inSwitching.swiftwithout saying what owned it. Matrix, pool anddesMachineIDare one piece of state on Windows (three sets ofMachineStuffstatics behind one lock), and every switch reads all three, so they are one class here. It returns[SwitchAction]and performs nothing, which is what keepsMWBCoreI/O-free.Sessionis per-connection; the pool and matrix are not. Windows runsAddToMachinePoolfrom inside the receive loop against global state. Splitting it this way is the only change of shape in the lane and it is the one CLAUDE.md asks for:Session.feedclassifies and reports,Switcherdecides.Receiver.cs's bigswitchis therefore not ported as a switch — the app dispatches.packetevents toSwitcher, to the injector, or to the clipboard lane later.- Heartbeats are per session, not per broadcast — see Assumptions.
Session.forward(_:)was added so the app can still send one sequenced broadcast to several connections where that matters (matrix replication,HideMouse,MachineSwitched). CGRect/CGPointunder Foundation alone are bare C structs: no.zero, nominX, noEquatable, though they areSendable. Rather than extend a CoreGraphics type fromMWBCore(which would shadow the real API inMWBMac) the five helpers live onCoordinates.EdgeConfigconsequently cannot beEquatable. This is a change to topo.md handshakes 4 and 6 in spelling only — the coordinate convention is unchanged — and is flagged for the lead.Edge.crossingreturns aDirection, not aJump. The planning sketch hadEdge.evaluatetake the matrix and the live names. KeepingEdgeto pure geometry made both it andMatrix.neighbourtestable by eye against the Windows source, and put the one place that needs all three (Switcher.crossing) in the file that owns the state.- The two-row neighbour chains stop at the first matching arm. Found
while porting: the arms are
else if, so an arm whose target has no id ends the search, whereas the one-row loops step over such a slot. Also found:MoveDownis two chains whereMoveUpis one. Both reproduced, both written up as protocol §10.2 notes 5 and 6. Hiis dead on the receive side (§10.2 note 2) and aHandshake'sId/Src/Desare random (§10.2 note 1). The second one matters: a receiver that learned the peer id from aHandshakewould learn garbage.- Time is seconds. Windows counts milliseconds; every constant is divided by 1000 in the code and cited with its millisecond original.
Verified by hand (no test suites, per CLAUDE.md — the user tests the app).
A throwaway swiftc build of MWBCore plus a 64-assertion scratchpad
program, all passing: matrix string round-trips and the one-row/two-row
neighbour search including wrap, empty and unreachable slots; the four
Matrix packets replicating a two-row wrapping matrix into a fresh
Matrix; pool string round-trip, case-insensitive resolution, duplicate-id
reset and the 25-minute liveness rule; universal-value scaling against the
C# integer expression written out by hand, the Point.Empty quirk and both
bias round-trips; every branch of crossing (desktop vs primary rectangle,
ALL mode, the 100 ms debounce, corner blocking) and a landing point two
pixels inside the far edge; a two-Session loopback that reaches
Connected both ways, learns both names and ids, delivers a Mouse packet
once and drops its replay; a wrong-key loopback that ends in
InvalidKey + .close having delivered no .packet at all; a
self-connection closing; heartbeat timing at 59 s / 61 s / 130 s with
Awake vs Heartbeat; and a Switcher edge crossing that moves control,
emits MachineSwitched, comes home with HideMouse, and rate-limits
NextMachine to 100 ms with the target id in WheelDelta.
No macOS permission was requested, no CGEvent was posted, no pasteboard
was touched. Nothing in these files logs, so no key material can leak
through one.
2026-09-16 — dev (Opus), rework round
tools/gates.sh green. One commit per item; no wire-core file, no
docs/topo.md, no TODO.md section but §2 was touched.
QA finding 1 — read errors must spend the untrusted budget. Confirmed
and ported exactly. The mechanism QA identified is real and is worse than
"a separate counter": TcpReceiveData never signals a bad read out of
band, it overwrites the type byte of the buffer it was filling —
PackageType.Error when the read returned 0 bytes, PackageType.Invalid
when it returned a short count, for both the 32-byte and the 64-byte half
(SocketStuff.cs:574-578, 588-593). The result is an ordinary package and
MainTCPRoutine runs it through the whole loop body. So three things had
to change, not one:
errCountcounts only theError(0-byte) kind and closes withSocketStatus.Erroron the sixth in a row (:1332-1364); any other type resets it, including a short read'sInvalid(:1366-1368).- Whatever
errCountdid, the package then falls throughType == Handshakeinto the untrusted branch (:1370-1529) and spends apackageCount, so five malformed reads raise.invalidKeyand ten send the tenInvalidpackets and close. - The trusted branch is guarded by
receivedCount > 0(:1531), so a 0-byte read never reachesReceiver.ProcessPackageat all.
Session now has one private receive(_:bytesReceived:) that is the
loop body; feed and the renamed noteReceiveError(bytesReceived:) both
go through it, the latter by building the same synthetic .error /
.invalid packet Windows builds. The public signature changed (it takes
the byte count now) — flagged to control-channel in Handshakes, and the
caller must pass the real count rather than collapsing a short read into
a 0-byte one. Written up as protocol §10.2 note 10. Two consequences
worth stating plainly because they are counter-intuitive: a run of
short reads ends in .invalidKey, while a run of six empty reads
still ends in .error (the errCount limit is reached first) — both are
Windows behaviour and both now fall out of the same code.
QA finding 2 — learn persisted on every heartbeat. Confirmed, and
the citation is exact: AddToMachinePool returns inside the
TryFindMachineByName branch at MachineStuff.cs:737, and the
UpdateMachinePoolStringSetting() at :755 sits after the whole
if/else, reachable only by falling through the new-machine branch. The
known-machine branch now returns []. It still refreshes the id and
timestamp in memory and still re-points desMachineID when the machine
being controlled changed id (:731-735) — that part is not persistence
and Windows does it there. The "5th machine" refusal already returned
[] and is unchanged.
QA finding 3 — parkCursor did not carry the gate. Confirmed; the
consequence QA described (the local cursor jerking to the top of the
screen every time control comes home, e.g. on every ByeBye via
Common.cs:622-625) is exactly what a naive consumer would have built.
Took the stronger of the two remedies QA offered: the action's shape
changed rather than only its doc comment, to
.parkCursor(destinationIsRemote: Bool, byHideMouseMessage: Bool). Both
halves of Common.cs:1488 are now pre-evaluated by Switcher (new
public destinationIsRemote, desMachineID != localID && != ALL), read
after the switch is applied because SwitchToMachine calls
HideMouseCursor(false) after setting DesMachineID
(MachineStuff.cs:1025). The rule "record the position always, move the
OS cursor only when destinationIsRemote || byHideMouseMessage" is now a
consumer rule in Handshakes, so input-inject can implement
HideMouseCursor without opening the Windows source.
Contract C1 — the API cannot send an unstamped application packet.
Session.send(_:) is gone. The per-connection stamp survives only as
private func originate(_:), used by exactly the four things Windows
also sends per connection (Handshake/HandshakeAck via sendDirect,
the heartbeat on tick and the one written on a fresh connection at
SocketStuff.cs:1451, Hi, ByeBye). Application traffic has one way
in — forward(_:), which fills Src if it is NONE and frames, and
never touches Id. This is now enforced by the type rather than by a
README sentence. Added protocol §10.2 note 11 recording why: SkSend
increments Package.PackageID once, before the socket loop
(Common.cs:914), and hands the same DATA to every matching socket
(:919-929), which is the whole reason the receiver's 50-entry replay
ring collapses a peer pair's duplicate delivery. A per-connection stamp
would give the duplicate a fresh Id and defeat the ring — so this was
a latent wire-behaviour bug, not only an API-shape preference.
Compliance re-read of all seven files. No force-unwrap, try!,
fatalError or precondition anywhere (the risky constructs are
try? packet.setMachineName(...), deliberate: an over-long or non-ASCII
name is dropped from its field rather than failing the send, README D7).
Longest file is Session.swift at 422 lines, longest function
countUntrusted at 26 — both well inside the CLAUDE.md targets. Nothing
logs. Four stale SocketStuff.cs line citations were off by one or two
against the reference checkout (:1390→:1389, :1441→:1439,
the untrusted branch :1386-1500→:1387-1529) and were corrected;
xcrun swift-format format -i made no further changes.
No macOS permission was requested, no CGEvent posted, no pasteboard
touched.
QA log
2026-09-16 — QA (Sonnet)
Process: tools/gates.sh (green — swift-format lint --strict, MWBCore
layering, swift build -Xswiftc -warnings-as-errors), then every
Status/TODO tick read against the cited Windows source
(SocketStuff.cs MainTCPRoutine 1261-1565, Receiver.cs,
Common.cs, MachineStuff.cs, MachinePool.cs/MachinePoolHelpers.cs,
Event.cs, Helper.cs, frmScreen.cs), then all seven files read
top to bottom for CLAUDE.md size/layering/naming/force-unwrap/dead-code
concerns, then a check that nothing logs key material or acts on a
packet before trust.
Verified faithful, worth recording since they were the areas flagged
for special attention: the nonce-complement handshake and trust gate
(Session.swift:159-169, 267-339 vs SocketStuff.cs:1269-1480 —
Handshake always answered regardless of trust, HandshakeAck after
trust silently skipped, self-connection close); the untrusted-packet
give-back for Mouse/Heartbeat/Heartbeat_ex past 5
(Session.swift:303-313 vs :1502-1521); the 32-then-32 reassembly
including the invalid-is-64-bytes rule (Session.swift:174-190); the
dedup ring's four exemptions (Sequencing.swift:76-82 vs
Receiver.cs:58-61); the one-row vs two-row neighbour search,
including the ascending/descending asymmetry between MoveRight and
MoveLeft, the "arm chosen before reachability is tested" two-row
quirk, and MoveDown's wrap-overwrites-straight quirk
(Matrix.swift:108-190 vs MachineStuff.cs:288-673, byte-for-byte
arm order checked); LiveMachineMatrix blanking in one-row mode only
(Matrix.swift:94-99 vs :935-945); the four-case landing rectangle
rule and the per-direction opposite-edge landing offsets
(Edge.swift:125-135 vs MachineStuff.cs:385-421 and the identical
arms in MoveRight/Left/Up/Down); the square (not circular)
100 px corner block and the 100 ms debounce ordering
(Edge.swift:82-100 vs :203-234); the relative-move and pixel
biases including the asymmetric >/>= bias tests
(Coordinates.swift:109-150 vs Event.cs:32-33, InputHook.cs:271-312,
Helper.cs:107-110); NextMachine's id-in-WheelDelta and 100 ms
rate limit (Switching.swift:229-239 vs Common.cs:516-539); the
Matrix packet slot/flags encoding and the slot-4 commit rule
(Matrix.swift:210-241 vs MachineStuff.cs:952-1006). No key material
or decrypted keystroke is logged anywhere in these seven files (grepped
for log/Log/print); Session.deliver is reached only from the
trusted branch, and nothing else in Session/Switcher synthesizes
input or touches a pasteboard (both are sans-I/O by construction).
swift-format, layering and file/function sizes are all within the
CLAUDE.md targets; no force-unwraps, try!, fatalError or
precondition in any of the seven files.
Three findings, none touching wire bytes or the trust boundary itself:
-
The 10-untrusted-packets rule doesn't count read errors, unlike Windows.
SocketStuff.cs:1330-1338gives a bad/short read its ownerrCount(closes after 6), but thatError-typed package then also falls through theif (package.Type == PackageType.Handshake)check (false) into the untrustedpackageCountbranch (:1379-1521, reached for any non-Handshaketype includingError) — so on Windows a run of malformed reads during handshake also spends the same 10-packet budget as garbage packets, and can tripInvalidKey(oncepackageCount > 5) or the full ">=10⇒ send 10Invalid, close" path before 6 read errors accumulate.Session.noteReceiveError()(Sources/MWBCore/Session.swift:192-199) is wired to a separate counter that never touchescountUntrusted/untrustedCount, so the port always closes a bad-read run via.errorafter 6, never via.invalidKey, and never spends any of the 10-packet budget on it. Not a trust-boundary or wire bug — the connection still closes either way — but it is a real behavioural divergence in the exact rule the brief called out for special attention. -
Switcher.learnpersists the pool on every heartbeat from an already-known peer; Windows does not.AddToMachinePool(MachineStuff.cs:712-745) returnsmachineInfo.Nameimmediately inside theTryFindMachineByNamebranch, before reachingMachineStuff.UpdateMachinePoolStringSetting()(the call sits after the whole if/else, reachable only from the "new machine" branch that falls through).Switching.swift:251-258(Switcher.learn) returns[.persistMachinePool]for the known-machine branch too, so the port asks the app to writeMachinePoolto disk on every heartbeat cadence tick from a peer it already knows (every 60 s or 300 s, per connection), not just when a new machine is learned. Harmless (idempotent, no wire effect) but extra I/O Windows doesn't do, and worth a one-line fix (drop.persistMachinePoolfrom that branch) or a documented deviation. -
SwitchAction.parkCursordoesn't carry what Windows needs to decide whether to actually move the OS cursor.HideMouseCursor(Common.cs:1482-1496) only callsSetCursorPoswhen(desMachineID != Common.MachineID && desMachineID != ID.ALL) || byHideMouseMessage.SwitchToMachine(MachineStuff.cs:1008-1028) callsHideMouseCursor(false)after settingCommon.DesMachineID = id, so on Windows the real cursor is parked only when switching control to a remote machine — switching control back to the local machine (exactly whatProcessByeByeMessage,Common.cs:622-625, does by callingSwitchToMachine(MachineName.Trim())when the controlling peer says goodbye) leaves the local cursor alone.Switcher.switchToMachine(Switching.swift:189-203) always appends.parkCursor(byHideMouseMessage: false), and neither the action's payload nor its doc comment (Switching.swift:31-34) tells a consumer it must additionally checkdesMachineID != localID && != ALLbefore actually moving the OS cursor. A straightforwardinput-injectimplementation — built, per this README's stated goal, "without reading the Windows source again" — would park the real cursor at the primary screen's top-centre every time control returns home (e.g. on every peer disconnect), which is a visible, incorrect cursor jump for the local user. Recommend either adding atargetIsLocal/shouldMoveCursorflag to the action, or spelling out the gating condition in the doc comment and in acontrol-channel"consumers must" rule alongside the existing ones in Handshakes.
Verdict: REWORK
2026-09-16 — QA (Sonnet), round 2
Process: tools/guard.sh -t 300 -- tools/gates.sh (green — swift-format lint
--strict, MWBCore layering, swift build -Xswiftc -warnings-as-errors), then
git diff 08b243a..HEAD and git log --oneline 08b243a..HEAD read against
the reference checkout at 3104d5c (SocketStuff.cs, Common.cs,
MachineStuff.cs), then a fresh top-to-bottom read of Session.swift and
Switching.swift, then xcrun swift-format format on both files diffed
against the working tree (no drift). Scope: only Sources/MWBCore/Session.swift,
Sources/MWBCore/Switching.swift, docs/features/session-matrix/README.md
and docs/protocol.md changed — no wire-core file, no docs/topo.md, no
TODO.md touched (§2 was already done before this round, correctly).
Finding 1 — read-error counting. Verified line-for-line against
SocketStuff.cs: errCount++ at :1334, the six-in-a-row close at
:1344, the reset (any non-Error type, including Invalid) at :1368,
the fall-through past Type == Handshake at :1371, ++packageCount >= 10
at :1389 (the untrustedPacketLimit doc comment's citation, corrected
from round 1's :1390), the give-back for Mouse/Heartbeat/
Heartbeat_ex at :1501-1519, and the receivedCount > 0 guard on the
trusted branch at :1531. Traced both counters through Session.swift's
new receive(_:bytesReceived:): a 0-byte read increments receiveErrors
and, past 5, closes with .error before handle ever runs; every read
(0-byte, short, or a real packet) still reaches handle/countUntrusted
via the same path, so .error- and .invalid-typed synthetic packets
spend untrustedCount exactly like Windows spends packageCount — the
6th non-exempt untrusted packet reports .invalidKey status only (no
close, no event — matches Windows's UpdateTcpSockets call with no
break), the 10th sends ten Invalid packets, emits
.invalidKey(.tooManyUntrustedPackets), and closes. When trusted,
bytesReceived > 0 is required before deliver, and a short read's
synthetic .invalid packet reaches deliver but is dropped there
(packet.type == .invalid), matching PreProcess at Receiver.cs:42-50.
Confirmed.
Finding 2 — learn persistence. Switching.swift:277 now returns []
for the known-machine branch, matching MachineStuff.cs:737's early
return machineInfo.Name; ahead of UpdateMachinePoolStringSetting() at
:755. The in-memory refresh (id/timestamp update, and re-pointing
desMachineID when the controlled machine's id changed, :731-735) is
correctly kept — that part runs before the early return on Windows too.
Confirmed.
Finding 3 — parkCursor gate. SwitchAction.parkCursor now carries
destinationIsRemote; Switcher.destinationIsRemote computes
desMachineID != localID && != MachineID.all, matching the first half of
Common.cs:1488's gate. Checked call order at both sites:
switchToMachine calls setDesMachine(id) before appending .parkCursor
(Switching.swift:207-215), and handleByeBye routes through
switchToMachine(named: localName, ...) (:312), so on the exact scenario
QA round 1 raised — control coming home on ByeBye — destinationIsRemote
evaluates to false after the switch and the OS cursor stays put, matching
MachineStuff.cs:1025's HideMouseCursor(false) running after
DesMachineID is set. handleHideMouse also passes destinationIsRemote
alongside byHideMouseMessage: true; harmless since that gate is an ||.
Confirmed.
Contract C1. Session.send(_:) is gone; grepped the whole of
Sources/ for .send( and the only matches are the unrelated
SwitchAction.send case. The only path that stamps an Id is the private
originate(_:), reachable solely from tick (heartbeat), sayGoodbye
(ByeBye), start (handshake, via sendDirect directly — random bytes,
not originate, correctly per SocketStuff.cs:1269-1289) and
acceptAck's initial heartbeat — the same four/five per-connection sends
Windows makes outside SkSend. forward(_:) calls sendDirect only,
which never touches p.id. Common.cs:901-935 (SkSend) confirms the
mechanism: one Interlocked.Increment(ref Package.PackageID) at :916
before the socket loop, the same DATA hand to every matching TcpSend.
protocol.md §10.2 note 11 cited this increment as Common.cs:914 — off by
two against the reference checkout; fixed directly (see below). Confirmed
otherwise.
Handshakes section vs shipped API. Read Session.swift and
Switching.swift top to bottom against the Handshakes code block: the
noteReceiveError(bytesReceived:) signature, the removed send(_:) line,
forward's updated comment, SwitchAction.parkCursor's two-argument case
and Switcher.destinationIsRemote all match the actual public surface
exactly. No public member exists that the block omits and no member the
block lists is missing.
CLAUDE.md compliance of the changed files. swift-format format on
both .swift files produced no diff against the working tree.
Session.swift is 422 lines, Switching.swift 371 — both within the
300–600 target. No force-unwrap, try!, fatalError or precondition in
either file (grepped). MWBCore imports only Foundation in both files
(gate 2 confirms no AppKit/CoreGraphics/Network anywhere in MWBCore).
Nothing logs. Scope held: only the four files listed above changed.
One trivial finding, fixed directly per the QA remit: docs/protocol.md
§10.2 note 11 cited Common.cs:914 for SkSend's PackageID increment;
the reference checkout (3104d5c) has it at line 916. Fixed in this
commit (qa: …); no behavioural content changed.
No other findings survive. The three round-1 findings are each fixed at the wire-behaviour level, not just papered over in a comment, and are cross-checked line-for-line against the reference checkout rather than against the Work log's own citations.
Verdict: PASS
Review
- 2026-09-16 (lead): inspected per
docs/loop.md§5 after one rework round. Gates green run by me; diff limited to the lane's seven files, TODO §2, protocol §10.2 and this README. ReadSession.swiftin full: trust gate delivers nothing beforeacceptAck, the untrusted budget and the six-empty-reads counter followMainTCPRoutine,forwardnever stamps,originateis private (contracts C1), heartbeat cadence andAwakerule cited. QA round 2 verified the three findings and C1 against the source. Verdict: merge. Carry into the next brief: (1)noteReceiveError(bytesReceived:)— the channel must pass the byte count, not collapse errors; (2)SwitchAction.parkCursor(destinationIsRemote:byHideMouseMessage:)consumer rule for input-capture/inject; (3)CGRect/CGPointunder Foundation alone lack.zero/minX/Equatable, so helpers live onCoordinates— topo handshakes 4 and 6 updated accordingly.