# 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.** `Session` owns no socket, timer or thread. The caller hands it decrypted packet bytes (`feed`), asks what to send (`drain() -> [Data]`, already framed and ready for `CipherWriter`) and what happened (`events`), and calls `tick(now:)` from its own timer. Time is a `TimeInterval` the caller supplies; nothing reads the clock. - **One `Session` per TCP connection**, client or server side — Windows runs the same `MainTCPRoutine` for 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. - **Trust is per connection and gates everything.** Until the `HandshakeAck` nonce check passes, the only packets `Session` acts on are `Handshake`/`HandshakeAck`; other packets are counted and after 10 the session reports `.invalidKey` and asks to close (`SocketStuff.cs:1387-1406`). Application packets are surfaced to the caller only from a trusted session (CLAUDE.md invariant 2). - **Sequence numbers and the replay ring are process-wide**, as on Windows (`Common.cs:906`, `Receiver.cs:40-82`): a `PacketSequencer` and a `ReplayFilter` are created once by the app and shared by every `Session`. The sequencer's start value comes from the persisted `PackageID` setting and the app stores it back; this lane exposes `current` for that. - **Heartbeats follow the 100 ms timer cadence** exactly: `count % 600 == 0` (60 s) when `BlockScreenSaver` is on, else `count % 3000` (300 s) (`frmScreen.cs:566-575`); `Awake` if the user was active within the window, else `Heartbeat` (`Common.cs:499-513`). Machine liveness is 25 min (`MachineStuff.cs:32`). `Heartbeat_ex` key propagation is **not** ported (README D6); those packets are accepted and ignored. - **`Matrix` and `MachinePool` are value types** with the exact persisted string forms (`MachineMatrixString` comma-joined, `Name:Id,Name:Id,Name:Id,Name:Id`, `MachinePoolHelpers.cs:16-43`, `MachinePool.cs:287-301`), so `Settings` can round-trip them unchanged from a PowerToys machine. - **Learning peers** from `Heartbeat`/`Hello`/`Awake` (`MachineStuff.cs:712-777`) adds to the pool and, if the matrix has a free slot and the name is new, to the matrix, then requests a matrix re-send — reported as an event, the app decides to persist. - **Geometry uses `CGRect`/`CGPoint` from Foundation** (no CoreGraphics import) in the Windows convention: top-left origin, y down, integer pixels. The `input-capture` lane converts from CoreGraphics display bounds, which use the same convention. - **Edge decisions are pure**: `Edge.evaluate(point:now:)` on a struct holding the rectangles, the mode flags and the last-jump time returns `nil` or a `Jump` naming 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 in `Coordinates`; nothing else in the app should know the numbers. ## Handshakes ### Consumed - `wire-core`: `Packet`, `PackageType`, `Framing`, `MachineID`, exactly as published in `docs/features/wire-core/README.md` Handshakes. ### Promised (to control-channel, input-capture, input-inject, app-shell) ```swift public final class PacketSequencer { public init(start: Int32); public func next() -> Int32; public var current: Int32 } public final class ReplayFilter { public init(); public func isDuplicate(_ p: Packet) -> Bool } // ring of 50, 4 exemptions public enum SocketStatus: Int, Sendable { case na = 0, resolving, connecting, handshaking, error, forceClosed, invalidKey, timeout, sendError, connected } public struct SessionConfig: Sendable { localName: String; localID: UInt32; magic: UInt32; blockScreenSaver: Bool } public enum SessionEvent: Sendable { case status(SocketStatus) case connected(peerName: String, peerID: UInt32) case packet(Packet) // trusted application packet, framing already checked, dedup applied case invalidKey // close the socket case selfConnection // peer name == our name: close case close } public final class Session { public init(config: SessionConfig, sequencer: PacketSequencer, replay: ReplayFilter, isClient: Bool) public func start(now: TimeInterval) // queues the 10 Handshake packets public func feed(_ plaintext: Data) // decrypted socket bytes; handles the 32-then-32 rule internally public func send(_ p: Packet) // stamps Id/Src, frames, queues (any type; used by the app for Mouse/Keyboard/etc.) public func tick(now: TimeInterval, userActive: Bool) // heartbeats, timeouts public func drain() -> [Data] // bytes to write through CipherWriter, in order public func events() -> [SessionEvent] public var status: SocketStatus { get } public var peerName: String?; public var peerID: UInt32? } public struct Matrix: Sendable, Equatable { public var names: [String] (4); oneRow: Bool; wrap: Bool; init(string:), var string: String; slot(of:), neighbour(of:direction:live:) } public struct MachinePool: Sendable { init(string:), var string; resolveID(name:) -> UInt32?; name(for:) -> String?; learn(name:id:now:); isAlive(id:now:) } public enum MatrixPackets { static func encode(_ m: Matrix, sequencer:) -> [Packet] (4); static func apply(_ p: Packet, to: inout Matrix, pending: inout [String?]) -> Bool /* true when slot 4 commits */ } public enum Direction { case left, right, up, down } public struct Jump: Sendable { direction: Direction; targetSlot: Int; universal: (x: Int32, y: Int32) } public struct EdgeConfig { desktop: CGRect; primary: CGRect; corners: [CGPoint]; blockCorners: Bool; moveRelatively: Bool } public struct Edge { init(config:); mutating func evaluate(point: CGPoint, localIsController: Bool, controllerOwnsCursor: Bool, matrix: Matrix, liveNames: Set, now: TimeInterval) -> Jump? } public enum Coordinates { toUniversal(_:in:) ; fromUniversal(_:desktop:primarySize:) ; relative bias encode/decode ; nextMachinePacket(...) } ``` Exact spelling may change during the lane; this README is updated in the same change and later lanes code against it. ## 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`). - [ ] `Sources/MWBCore/Switching.swift`: `desMachineID` / ALL mode / `MachineSwitched` / `HideMouse` emission / `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. ## Work log ## QA log ## Review