control-channel
Goal
The sockets. MWBNet turns Session + CipherWriter/CipherReader
into live TCP connections on port+1 (docs/protocol.md §3.1, §3.3, §7):
an NWListener for inbound peers, one outbound NWConnection per
non-local matrix name with the Windows retry cadence, name resolution
with Name2IP, the keep-one-client-per-peer rule, reconnect triggers,
and the bounded queues and stall detection that contracts C2/C3
require. It reports SessionEvents and connection lifecycle to an
EngineSink protocol; the Engine itself arrives in the app-shell lane.
No packet is interpreted here.
Assumptions
- Network.framework only (
NWListener,NWConnection,NWPathMonitor,NWEndpoint); no BSD sockets exceptgetaddrinfoinsideResolverfor theName2IP-free path, becauseNWConnection(host:port:)already resolves names — prefer it and usegetaddrinfoonly for the reverse-lookup validation option. (Shipped differently:Resolverdoes every lookup withgetaddrinfoand handsNWConnectiona numeric address. See the work log — Windows resolves the name itself, filters the address list and dials each surviving address in parallel, and neither filter nor the parallel dial can be expressed if the connection resolves the name for us.) - Two listeners are the protocol's shape (
SocketStuff.cs:475-495): this lane opens the control listener onport + 1only; the clipboard listener onportis the clipboard lane's. - Per connection: one
PeerConnectionowningNWConnection,Session,CipherWriter,CipherReader, one serialDispatchQueue, a bounded outbound queue (512 framed packets) and a 500 ms send timeout (SocketStuff.cs:1286). The first bytes written areCipherWriter.header(48 bytes); the first bytes read go intoCipherReader, whose output feedsSession.feed. A read that returns fewer than 32 bytes at EOF or errors callsSession.noteReceiveError(bytesReceived:)with the real count (contracts, session-matrix Review). The read is sized to make that exact: 48 bytes once for the peer's preamble, then exactly 32 bytes per read, which after the preamble is exactly one WindowsReadEx(buf, 0, PACKAGE_SIZE)(docs/protocol.md§10.3 note 8). - Outbound clients: for every matrix name that is not the local
name and has no connected client, dial
name:port+1; retry every 1 s until 30 s have passed (SocketStuff.cs:158, 276, 1179-1198), then report.timeoutand wait for the next reconnect trigger. Socket options mirror Windows:NoDelay, 320 000-byte buffers where Network.framework exposes them (SocketStuff.cs:1283-1286) — it exposes none, so onlyNoDelayis set and the bounded outbox is what limits queued bytes. - Name resolution filters each address group on its own
(
SocketStuff.cs:928-944, 950, 989-1044):Resolver.addressesruns the same control flowStartNewTcpClientdoes, not a filter over the union. TheName2IPmappings are checked against the same-subnet rule alone, and when that check fails Windows returns fromStartNewTcpClientbeforeDns.GetHostEntryis called (:934-937, 950) — so the name is not dialled at all that round and we return[]. The DNS group is filtered by the reverse lookup and then gets its own same-subnet check (:1037-1040); failing it drops the DNS addresses only, leaving the mapped ones, which Windows has already handed toStartNewTcpClientThreadby then. The reverse lookup never applies to a user-supplied mapping (docs/protocol.md§10.3 note 6). - Keep one client per peer (
SocketStuff.cs:1980-2004): when a second connection to the same peer name reaches.connected, the later client connection is closed; inbound (server-side) connections are always kept. The channel therefore ends with at most one outbound and one inbound connection per peer, and forwards every app packet to both — the receiver's replay ring collapses the pair (contracts C1). - Machine-id collision (
SocketStuff.cs:1984-1992): if a trusted peer reports our own id over an outbound connection, the channel reports.idCollisionto the sink; the app regenerates and callsreopenAll(). Windows force-closes every socket in that branch, not just the offending one (docs/protocol.md§10.3 note 3), and so do we. Like the duplicate-client rule, this is client-only:UpdateTcpSocketsruns the whole block understatus == Connected && tcp.IsClient(:1980-1981), so an id reported over an inbound connection is silently tolerated, here as there. - Failure budget per endpoint (
SocketStuff.cs:1482-1499): more than 10.invalidKeyoutcomes from the same remote address ⇒ report.peerRejected(address)and stop dialling it untilreopenAll(). Keyed by address only, and counting both invalid-key reasons — Windows keys by address and port and counts only the mismatched ack, which makes its counter almost unreachable (docs/protocol.md§10.3 note 5). - Reconnect triggers (§3.3):
NWPathMonitorstatus change, an explicitreopenAll()(the app calls it on wake, display change and the reconnect hotkey), a connection reset, and the settings change of key/port/matrix (the app callsreconfigure(_:)). A key, port, local name or local id change reopens everything; a matrix change clears the dial state and grants a fresh 30 s budget, so a slot edited after the budget expired is actually dialled. - Ticks: the channel runs one 100 ms
DispatchSourceTimerthat callsSession.tick(now:inputEventCount:)on every connection, drains outboxes and events, and detects the C2 "30 s silence while we are sending input" stall: if the connection the sink marked ascontrolledreceives nothing for 30 s while packets are being forwarded to it, close it. - The channel counts input; it does not judge it.
noteUserActivity()is ourEvent.RealInputEventCount++(Event.cs:51-55,InputHook.cs:223, 345) and the tick passes the raw counter to every session unchanged. TheAwake-or-Heartbeattest (lastRealInputEventCount != Event.RealInputEventCount, re-recorded on the way out —SendAwakeBeat,Common.cs:545-559) lives inSession, because on Windows the beat is the send and each of our sessions schedules its own beat. A boundary held here would be out of phase with every connection's heartbeat instant and could reportHeartbeatfor input that postdates that connection's own previous beat. ChannelConfig(contracts C4) carries everything: local name, local id, port, security key, matrix names,Name2IPtext,sameSubnetOnly,validateRemoteIP,blockScreenSaver.- Threading: all mutation of channel state happens on one private
serial queue;
EngineSinkcalls are made from that queue and the sink is expected to hop to its actor.PeerConnectionis notSendable; it never escapes the channel's queue. (Shipped as@unchecked Sendableon bothControlChannelandPeerConnection, because Network.framework's handlers are@Sendableclosures. The confinement is real and unchanged: eachPeerConnectionhas its own serial queue created withtarget: channelQueue, so every callback in the channel is serialised on the one channel queue. See the work log.) - Time is monotonic. Every interval here is measured with
DispatchTime.now().uptimeNanoseconds, which is whatCommon.GetTick()is on Windows; nothing reads the wall clock, so a clock correction cannot make a heartbeat or the stall rule fire.
Handshakes
Consumed
wire-core:CipherWriter,CipherReader,MagicHash,Packet,Framing(viaSession),packageSize.session-matrix:Session,SessionConfig,SessionEvent,SocketStatus,InvalidKeyReason,PacketSequencer,ReplayFilter.
One MWBCore change was made by this lane, with the lead's authorisation
(rework round 2): Session.tick(now:userActive:) became
Session.tick(now:inputEventCount:), moving SendAwakeBeat's counter
comparison into the session that owns the heartbeat instant
(Common.cs:542-559). The contract is written up in the session-matrix
README's Handshakes section; nothing else in MWBCore was touched.
Promised (to app-shell, clipboard)
As shipped 2026-09-16. Later lanes code against this, not against the sketch this section used to hold.
// ChannelConfig.swift — the vocabulary
public struct ChannelConfig: Sendable, Equatable {
public var localName: String, localID: UInt32, port: UInt16 // port + 1 is the control port
public var securityKey: String, matrixNames: [String], name2IP: String
public var sameSubnetOnly: Bool, validateRemoteIP: Bool, blockScreenSaver: Bool
public var controlPort: UInt16 { get }
public init(localName:localID:port:securityKey:matrixNames:name2IP:
sameSubnetOnly:validateRemoteIP:blockScreenSaver:) // all but the first two defaulted
}
public enum Destination: Sendable, Equatable { case all, peer(UInt32) }
public enum DisconnectReason: Sendable, Equatable {
case closed, readError, sendError, invalidKey(InvalidKeyReason), peerRejected,
stall, duplicateClient, selfConnection, idCollision, timeout, forceClosed
}
public struct PeerStatus: Sendable, Equatable {
public var name: String; public var status: SocketStatus; public var isOutbound: Bool
public var peerID: UInt32?; public var address: String?
public init(name:status:isOutbound:peerID:address:)
}
public protocol EngineSink: AnyObject, Sendable {
func channel(_ channel: ControlChannel, connectionStatus: SocketStatus,
peerName: String?, isOutbound: Bool)
func channel(_ channel: ControlChannel, connected peerName: String, peerID: UInt32)
func channel(_ channel: ControlChannel, received packet: Packet, from peerID: UInt32)
func channel(_ channel: ControlChannel, disconnected peerID: UInt32?,
peerName: String?, reason: DisconnectReason)
func channelDetectedIDCollision(_ channel: ControlChannel)
}
// ControlChannel.swift — the sockets
public final class ControlChannel: @unchecked Sendable {
public static let connectTimeout: TimeInterval = 30 // SocketStuff.cs:158, 276
public static let retryInterval: TimeInterval = 1 // :1186
public static let tickInterval: TimeInterval = 0.1 // frmScreen.cs:285-288
public static let endpointFailureLimit = 10 // :1487-1497
public init(config: ChannelConfig, sequencer: PacketSequencer,
replay: ReplayFilter, sink: EngineSink)
public func start(); public func stop(); public func sayGoodbye()
public func reconfigure(_ new: ChannelConfig) // reopens what changed
public func reopenAll()
public func forward(_ packet: Packet, to: Destination) // already sequenced (C1)
public func noteUserActivity()
public func markControlled(peerID: UInt32?) // arms the 30 s stall rule
public var statuses: [PeerStatus] { get } // any thread
}
// Resolver.swift — name → addresses, no discovery
public enum Resolver {
public static func addresses(for name: String, config: ChannelConfig) -> [String]
public static func mappedAddresses(for name: String, in name2IP: String) -> [String]
public static func lookup(_ name: String) -> [String]
public static func reverseName(for address: String) -> String?
public static func shortName(for address: String) -> String
}
Rules the consuming lanes must honour:
- Every
EngineSinkcall arrives on the channel's serial queue. Do the least possible work in it and hop to the Engine actor; a sink that blocks stalls every connection, the heartbeats and the stall rule. The channel is handed to the sink as a parameter, so the sink never needs to capture it. forward(_:to:)takes an already-sequenced packet (contracts C1). The channel stamps nothing; it fans the identical bytes out, which is what makes the receiver's replay ring collapse a peer pair's two deliveries..allis filtered by the matrix, exactly asSkSenddoes.reopenAll()is the only way back from a give-up. After the 30 s connect budget expires, or after an address spends its failure budget, the channel stops dialling on its own. The app is what turns that around, on the reconnect hotkey, on wake, on a display change, and on the "no socket established" countdown Windows runs from its 100 ms timer (frmScreen.cs:427-450). The channel reopens itself only on anNWPathMonitorstatus change.disconnectedcarries optionals. A connection that dies before the handshake has no peer id and possibly no name;peerIDisnilthere. Do not key recovery on the id alone.- The app owns the machine id. On
channelDetectedIDCollisionthe channel has already closed every connection; the app draws a newMachineID, hands it over inreconfigure(_:)and callsreopenAll(). stop()does not say goodbye. CallsayGoodbye()first on a clean exit (Common.SendByeBye,InitAndCleanup.cs:192).
Requested of other lanes (open)
- app-shell: the reopen countdown is the app's. The channel gives up
dialling 30 s after
start()/reopenAll()because Windows does (docs/protocol.md§10.3 notes 1–2); something must callreopenAll()again while no connection is established, or a machine that boots late is never reached. Windows's rule — reopen when no socket is established, checked every 30 s — is the one to port (frmScreen.cs:427-450). - app-shell:
markControlled(peerID:)must be called on every switch, including back to local (nil). It is what arms the C2 30 s stall rule, and nothing else in the channel knows which peer is receiving input. - session-matrix: the "Heartbeats follow the 100 ms timer cadence"
bullet in that lane's Assumptions still says
Awakeis sent "if the user was active within the window" and citesCommon.cs:499-513(SendPackage/SendHeartBeat). Both are wrong as of this rework: the test is a counter comparison against the session's own previous beat, and the citation isCommon.cs:545-559. This lane's authorisation covered that README's Handshakes section only, so the Assumptions bullet is left for its owner.
Answered from session-matrix
- The duplicate-client-socket policy (
SocketStuff.cs:1980-2004) and the per-endpoint failure budget (:1482-1499) are implemented here, keyed by peer name and remote address respectively.Sessionstill counts nothing across connections.
Status / TODO
Sources/MWBNet/ChannelConfig.swift: config,EngineSink,DisconnectReason,PeerStatus,Destination.Sources/MWBNet/PeerConnection.swift: one connection — cipher header exchange, read loop with 32/64 framing left toSession, bounded outbox, 500 ms send timeout, stall detection, close (SocketStuff.cs:1261-1565I/O side,:1283-1286).Sources/MWBNet/Resolver.swift:Name2IPparsing (SocketStuff.cs:904-946, 1258-1259), same-/16 check (:1065-1107), reverse validation (:991-1032).Sources/MWBNet/ControlChannel.swift: listener, dial loop with retry (:797-837, 1169-1198), one-client-per-peer (:1980-2004), id collision (:1984-1992), per-endpoint failure budget (:1482-1499),NWPathMonitor+reopenAll(§3.3), 100 ms tick.- Delete
Sources/MWBNet/Placeholder.swift. docs/protocol.md: append §10.3 with anything learned, cited.
Not done, deliberately:
- The
Name2IpPolicyListhalf of the mapping list (SocketStuff.cs:906): it is a Windows GPO-delivered setting, and GPO is out of scope (README D6).Name2IPalone is parsed, with the same grammar. - The bad-IP cache (
SocketStuff.cs:840-882): it only memoises the reverse-lookup result so a failing address is not looked up again. Behaviour is identical without it — a rejected address is simply re-checked on the next dial — and the option is off by default. - Socket send/receive buffer sizes (
:1283-1284): Network.framework exposes neither. The bounded outbox (512 framed packets) is the equivalent limit and is what contracts C3 asks for anyway. - Reverse DNS for an inbound peer's display name
(
GetMachineNameFromSocket,:733-762): the lookup blocks, and the channel queue must not. An inbound connection is labelled by its address until theHandshakeAcksupplies the real name, which is within ten packets.Resolver.shortName(for:)exists for a lane that wants it off the queue. - Windows quitting the app on the eleventh failure from one endpoint
(
:1493-1496): a Mac that silently exits because one peer has a wrong key is a worse outcome than one dead peer. We block the address and keep running.
Work log
2026-09-16 — dev (Opus)
Four files in MWBNet, Placeholder.swift deleted, tools/gates.sh
green. What each file is responsible for, in one sentence apiece:
ChannelConfig.swift(189 lines) — the vocabulary the channel and the app share, and nothing else: config,Destination,DisconnectReason,PeerStatus,EngineSink.Resolver.swift(229 lines) — a machine name to the list of addresses worth dialling, including both optional filters. The only file that touchesgetaddrinfo/getifaddrs, and the only one that blocks.PeerConnection.swift(356 lines) — one connection's I/O: the cipher preamble, the sized reads, the bounded outbox with its 500 ms timeout, and the translation ofSessionEventinto channel events.ControlChannel.swift(505 lines) — everything keyed by endpoint rather than by connection: the listener, the dial loop, the one-client-per-peer and id-collision rules, the failure budget, the reconnect triggers and the 100 ms tick.
Decisions and deviations, each with why:
- Reads are sized, not streamed. The obvious
receive(min: 1, max: 65536)loop would have made "a read that returned fewer than 32 bytes" unrepresentable, and that byte count is exactly whatSession.noteReceiveError(bytesReceived:)needs to distinguish Windows'sError(0 bytes) fromInvalid(short) package (SocketStuff.cs:574-578). Instead the reader takes the peer's 48-byte preamble in one read and then exactly 32 bytes per read. That is sound because the stream is packet-aligned after the preamble: every write is a whole 32- or 64-byte packet through a no-padding CBC stream, so 32 bytes of ciphertext in are always 32 bytes of plaintext out (protocol §10.3 note 8). Verified off-line with a no-socket harness that runs twoSessions through realCipherWriter/CipherReaderpairs at exactly this chunking: the preamble yields 0 plaintext bytes, every 32-byte read yields 32, the handshake reaches.connectedon both sides with the right peer name and id, and both streams drain to zero leftover. - One serial queue, per-connection queues that target it. The brief
asks for all channel state on one private serial queue; contracts C3
describes a queue per connection. Both are satisfied by
DispatchQueue(label: "mwb.peer.N", target: channelQueue): each connection has its own FIFO, and the target chain serialises every one of them on the channel queue, so there is no lock anywhere inMWBNetexcept the one publishingstatuses. @unchecked SendableonControlChannelandPeerConnection. Network.framework's state, receive and send handlers are@Sendableclosures, so a non-Sendableclass cannot be captured by them at all under Swift 6. The confinement the README promised is unchanged and is the justification: every stored property of both types is touched only from the channel queue.statusesis the one exception, and it is anOSAllocatedUnfairLockholding a value copy.Resolverresolves;NWConnectiondoes not.NWConnection(host: .name(…))would have been less code, but Windows resolves the name itself and then filters the address list (same-subnet, reverse lookup) and dials every survivor in parallel (SocketStuff.cs:989-1044). Neither the filter nor the parallel dial survives handing the name to Network.framework, soResolverreturns numeric addresses and the channel dials each one..waitingcounts as a failed attempt. Network.framework would happily sit in.waitingretrying a refused connection on its own schedule. Windows retries every second against a 30 s deadline, so the connection is cancelled on.waitingand the channel's own cadence governs (:1179-1193).- The dial loop is polled, Windows's is triggered.
UpdateTCPClientsruns only when something calls it (protocol §10.3 note 2), which works there because the 100 ms UI timer also runs a reopen countdown. Ours is re-evaluated on the same 100 ms tick, still bounded by the 1 s retry interval and the 30 s budget, so the observable cadence is Windows's without depending on an app-level countdown that does not exist yet — the countdown is still requested of app-shell (Handshakes) because it is what recovers after the budget expires. - The failure budget is keyed by address, not by address:port, and counts both invalid-key reasons. Windows's key includes the remote ephemeral port, which is new on every connection, so its counter effectively never fires (protocol §10.3 note 5). Keying by address makes the guard do what its code plainly intends. And we block that address instead of quitting the app (invariant 3: the Mac stays usable).
DisconnectReasonhas no.byeByecase. The sketch listed one, but the channel interprets no packet and therefore cannot know aByeByearrived —Sessiondelivers it to the app like any other trusted packet, and the app'sSwitcher.handleByeByealready owns the behaviour. Windows does not close the socket onByeByeeither.disconnectedgainedpeerNameand madepeerIDoptional. A connection that dies during the handshake has neither an id nor, usually, a confirmed name; the promised signature could not describe it. The sink needs the name to clear a matrix slot's status.sayGoodbye()was added.Common.SendByeByeis a broadcast on Windows, but session-matrix deliberately madeByeByea per-connection originate, so the channel needs an entry point that is notforward(_:to:). It is the app's last call beforestop().
Nothing outside the lane's file list was edited: four new files in
Sources/MWBNet, one deletion, this README, TODO.md §3 and
docs/protocol.md §10.3. No MWBCore file was touched and no handshake
request against another lane's files was needed.
Verification (no real listening socket was opened at any point, and no input event or pasteboard was touched):
tools/gates.shgreen on the final commit.- The no-socket chunking harness described in decision 1.
- A
Resolverharness over the public API:Name2IPparsing (case-insensitive name match, several mappings for one name, malformed and non-numeric lines dropped),lookupof a name that resolves and one that does not,shortNameof127.0.0.1, andaddresses(...)withsameSubnetOnlyandvalidateRemoteIPon. All as specified.
2026-09-16 — dev (Opus), rework after QA verdict REWORK
One commit per finding, plus a compliance pass. tools/gates.sh green on
the last of them; xcrun swift-format format -i --recursive Sources Package.swift is a no-op on all four files.
Resolver.addressesnow runsStartNewTcpClient's control flow instead of filtering the union. The mapped (Name2IP) group gets the same-subnet check on its own and, when it fails, the function returns[]without callinglookup— Windows'sreturnatSocketStuff.cs:934-937, which is reached beforeDns.GetHostEntry(:950), so nothing is dialled for that name that round. The DNS group is then filtered by the reverse lookup (:989-1032) and gets its own same-subnet check (:1037-1040); failing it drops only the DNS addresses, because by that point Windows has already handed the mapped ones toStartNewTcpClientThread(:941). Both QA scenarios now match Windows: a mapped address out of subnet dials nothing even if DNS has an in-subnet address, and an out-of-subnet DNS address is no longer dialled just because a mapped address passed. Documented in Assumptions (new bullet) anddocs/protocol.md§10.3 note 6, which now spells out the two different failure modes.- The id-collision check moved inside the
isOutboundgate.UpdateTcpSocketsruns the collision branch and the keep-the-first-client branch as the two halves of one block gated bystatus == SocketStatus.Connected && tcp.IsClient(SocketStuff.cs:1980-1981), so a server-accepted socket reaches neither; the port had the gate on the dedup half only. An inbound peer announcing our id is now tolerated silently, as there. §10.3 note 3 said only that the collision force-closes everything; it now states the client-only gate and points at note 4's observation about the same gate. The Assumptions bullet and theDisconnectReason.idCollision/channelDetectedIDCollisiondoc comments say the same. userActiveisSendAwakeBeat's test, not a sliding window. The channel keeps the pair of counters Windows keeps:noteUserActivity()incrementsinputEventCount(ourEvent.RealInputEventCount++,InputHook.cs:223, 345) and the tick reportsinputEventCount != beatInputEventCount, re-recording the counter on its own heartbeat boundary exactly asSendAwakeBeatre-records on its way out (Common.cs:545-558). The boundary is the channel's, which is the one global beat Windows's 100 ms timer runs for every socket at once (frmScreen.cs:565-575); tracking it per connection would needSessionto say when it beat, andSessionis another lane's file. Comparing by count also means a single click 59 s before the beat is still anAwake, which the old window would have dropped. The stale §3.3 citation (Common.cs:499-513, 662-676—SendHeartBeatand screen-capture code) is replaced byCommon.cs:542-559with theEvent.cs:51-55/InputHook.cs:223, 345counter and theIsMyDesktopActive/desktop conditions named.- CLAUDE.md re-read of the four files. Sizes 191/235/356/535 lines,
every function inside 10–50 (the two longest are
PeerConnection.initat 30 lines andupdateClientsat 28), layering, the one-sentence responsibility test, no force-unwrap /try!/fatalError/precondition, no logging anywhere inMWBNet, no packet interpreted, no line over 110 columns. Three citations were wrong and are fixed:Common.SendByeByeisCommon.cs:611-615, andSkSend's stamp-and-fan-out is:916-930with theDes == ID.ALLmatrix test at:922-930.
No file outside the lane's list was touched: the four Sources/MWBNet
files, this README, docs/protocol.md §3.3 and §10.3. No MWBCore file
was edited — finding 3 was answered entirely on the channel side for that
reason — and TODO.md needed no change (its §3 items were already
ticked). No listener was opened, no input event posted and no pasteboard
touched during this rework.
2026-09-16 — dev (Opus), rework round 2 after QA verdict REWORK
One finding: the channel-global lastBeatAt / beatInputEventCount reset
was not synchronised with any connection's own heartbeat instant, so a
session could send Heartbeat (20) where Windows sends Awake (21), and
Awake is what drives the peer's Common.HumanBeingDetected()
(Receiver.cs:245-248) — the BlockScreenSaver mechanism, default on.
QA is right, and right about the cause: Windows's beat is the send, one
SendAwakeBeat() call for every socket at once (Common.cs:545-559,
frmScreen.cs:565-575), whereas our sessions each schedule their own
heartbeat from their own handshake-completion time
(Session.swift start(now:) / tick). A sampling boundary held by the
channel is therefore out of phase with every one of them by construction.
The previous entry's claim that the channel's boundary "is the one global
beat Windows runs for every socket at once" is withdrawn.
The fix puts Windows's pair of statics where Windows's beat is — at the send:
Sessionowns the comparison now.Session.tick(now:userActive:)becameSession.tick(now:inputEventCount:), taking the raw process-wide real-input counter (Event.RealInputEventCount,Event.cs:51-55, bumped by the hooks atInputHook.cs:223, 345). A new privatebeatInputEventCountisCommon.lastRealInputEventCount(Common.cs:543): the tick sends.awakeiffblockScreenSaveris on and the counter differs from the value this session recorded at its own previous beat, and re-records it on both branches, which is exactly whatSendAwakeBeatdoes atCommon.cs:547-548and:558. Because the record now happens at the same instant as the send, the out-of-phase case QA constructed cannot arise: a click att=10is still new to a connection whose own previous beat was att=0, whenever between beats the channel happens to tick.beatInputEventCountstarts at0, as the Windows static does, so the first beat of a session on a machine that has seen any input is anAwake; that errs towards keeping a peer awake, which is the safe direction for this mechanism.ControlChannelno longer has a beat.lastBeatAtandbeatInputEventCountare gone, along with the heartbeat-interval lookup that existed only to drive them.noteUserActivity()still just incrementsinputEventCount(&+=, so it wraps rather than traps), andtick()reads it once and hands the same value to every connection;PeerConnection.tick(now:inputEventCount:)passes it straight through. NouserActive-shaped name survives anywhere inSources(grep clean), so there is nothing left to reintroduce a window against.
Scope: this touched Sources/MWBCore/Session.swift, which belongs to
session-matrix — the lead authorised that one file plus that lane's
Handshakes section for this fix, because the finding cannot be answered on
the channel side at all (the channel does not and should not know when a
session beats). docs/features/session-matrix/README.md now carries the
new signature in its Promised block and a rule spelling out that the
argument is a raw counter and why a caller must not pre-compute the
verdict. A stale Assumptions bullet in that same README (a "window" and
the Common.cs:499-513 citation) is outside the authorisation and is
filed as open request 3 instead. docs/protocol.md §3.3 already describes
the rule correctly (Common.cs:542-559, corrected in the previous round)
and needed no change; TODO.md had nothing to tick.
Verification: xcrun swift-format format -i --recursive Sources Package.swift is a no-op, and tools/guard.sh -m 8 -t 1800 -- tools/gates.sh is green (lint --strict, the MWBCore layering check,
swift build -Xswiftc -warnings-as-errors); neither guard limit was hit.
No listener was opened, no CGEvent posted and no pasteboard touched.
QA log
2026-09-16 — QA (Sonnet)
Checked, in order: tools/gates.sh; every Status/TODO tick against
App/Class/SocketStuff.cs (listeners, UpdateTCPClients, Name2IP, DNS,
subnet, connect, options, MainTCPRoutine I/O, failure budget,
dedup/collision), TcpServer.cs, InitAndCleanup.cs:28-31,
frmScreen.cs:427-461; all four changed files top to bottom for CLAUDE.md
compliance (size, layering, naming, force-unwraps, retain cycles); that
MWBNet logs nothing and interprets no packet.
tools/gates.sh: green (swift-format lint --strict, MWBCore layering,swift build -Xswiftc -warnings-as-errors). NoTests/target exists in this repo (the user's rule,TODO.md/docs/topo.mdhistory) so noswift testgate applies; the work log's harnesses are not committed, consistent with that rule.- File-by-file read: no force-unwraps,
try!,fatalErrororpreconditionin any of the four files; noprint/Logger/os_logcalls anywhere inMWBNet(invariant 2 — nothing to leak key material or packet contents even inadvertently); every closure captured across an escaping boundary (NWConnection/NWListener/NWPathMonitor/DispatchSourceTimer/DispatchWorkItemhandlers in bothPeerConnectionandControlChannel) uses[weak self], so no retain cycle. File sizes (189/512/356/229) and every function body are inside CLAUDE.md's targets. ConfirmedSession.forward→sendDirectonly fillsSrcwhen unset and never touchesId(Sources/MWBCore/Session.swift:390-395), soforward(_:to:)truly never re-stamps a packet (C1). Confirmed the 48-bytewriter.headeris enqueued beforesession.start(now:)inbecameReady()(PeerConnection.swift:158-159), andreceiveExactlypasses the realreceived.counttonoteReceiveError(bytesReceived:)(PeerConnection.swift:207-208). Confirmed@unchecked Sendableon both types: every stored property is touched only fromqueue/peerQueue(which targetsqueue), exceptstatusStore, which is its ownOSAllocatedUnfairLock— no handler found that touches state off the channel queue. - Two undocumented behavioural deviations from the Windows source turned
up from the line-by-line comparison; neither is mentioned in
docs/protocol.md§10.3, the README, or the work log's list of deliberate deviations. Filed below. - Verified deliberate, documented deviations are in fact what's shipped:
Name2IpPolicyListand the bad-IP cache are absent (grepclean), the failure budget is keyed by address only and counts every.invalidKeyreason (ControlChannel.swift:400-406), Windows's app-quit-on-eleventh is replaced with per-address blocking — all as the work log states.
Verdict: REWORK
Findings:
-
Resolver.addressesmerges theName2IPand DNS address groups before the same-subnet check, instead of checking each group separately, and has no equivalent of Windows's early return when theName2IPgroup itself fails that check.Sources/MWBNet/Resolver.swift:24-41builds onefoundarray frommappedAddressesthenlookup, and appliesisSameSubnetonce to the union. Windows (SocketStuff.cs:930-944) runsCheckForSameSubNeton theName2IP-mapped addresses alone and, if it fails,returns fromStartNewTcpClientbeforeDns.GetHostEntryis ever called — skipping DNS resolution for that round entirely — then separately runsCheckForSameSubNetagain on the DNS-resolved group (:1035-1044). Net effect withsameSubnetOnlyon and aName2IPmapping configured: (a) aName2IPaddress outside the local subnet but a DNS address inside it — Windows dials nothing for that name this round (the early return skips DNS too); the port dials the DNS address. (b) AName2IPaddress inside the subnet but a DNS address outside it — Windows dials only theName2IPaddress; the port's single union check passes (because some address in the union matches) and dials both, including the out-of-subnet DNS address.docs/protocol.md§10.3 note 6 documents the reverse-lookup-filter half of this same code region but not the subnet-check-per-group split or the early return. BothsameSubnetOnlyandName2IPare off/empty by default, so this needs a live peer with both configured to reach. -
Machine-id collision is detected on inbound (server) connections too; Windows only detects it on outbound (client) sockets.
Sources/MWBNet/ControlChannel.swift:367-372(accept(_:name:id:)) runsif id == config.localID { sink.channelDetectedIDCollision(...); closeAll(.idCollision); return }for every connection that completes its handshake, regardless ofpeer.isOutbound. On Windows,UpdateTcpSockets's entire collision-and-dedup block is gated bystatus == SocketStatus.Connected && tcp.IsClient(SocketStuff.cs:1981) — the id check at:1985never runs for a server-accepted socket. The port gets the dedup half of that same guard right two lines below (peer.isOutboundon theduplicateClientcheck,ControlChannel.swift:375) but drops the guard for the collision half.docs/protocol.md§10.3 note 3 describes the force-close-everything behaviour but not the client-only gate, so this reads as faithfully ported when it isn't. Practical effect: a Mac can force-close every connection and regenerate its machine id reacting to a collision reported over an inbound connection, a case real Windows silently tolerates — not unsafe (invariant 3 is still satisfied, this only affects other machines), but an undocumented behavioural difference invariant 1 requires be either matched or explicitly justified. -
(Minor, doc-only) The
userActiveheuristic inControlChannel.tickis a time-window proxy, not whatSendAwakeBeatactually checks, and the approximation isn't cited anywhere.ControlChannel.swift:441-442computesuserActive = lastUserActivity > 0 && now - lastUserActivity <= interval(the heartbeat interval itself, 60 s/300 s). Windows'sSendAwakeBeat(Common.cs:545-558) instead sendsAwakewhenlastRealInputEventCount != Event.RealInputEventCount— i.e. any new real input since the previous heartbeat tick, not "within the last N seconds ofnow" — plusIsMyDesktopActive()and not-logon/not-screensaver-desktop checks this lane correctly leaves to another lane. The two proxies agree in the steady state (continuous activity or continuous idleness) and only diverge at the edges, so this is low-impact, but note thatdocs/protocol.md§3.3's own citation for this rule (Common.cs:499-513, 662-676) is stale — those lines areSendHeartBeat/screen-capture code, notSendAwakeBeat— which predates this lane and was inherited rather than checked against source. Worth a one-line fix to protocol.md §3.3's citation and a note on the approximation next time §3.3 or this file is touched; not blocking on its own.
2026-09-16 — QA (Sonnet), round 2
Read the rework Work-log entry, then git diff 09ca990..HEAD and
git log --oneline 09ca990..HEAD (five commits). Checked, in order:
tools/guard.sh -m 8 -t 600 -- tools/gates.sh; finding 1 against
SocketStuff.cs:920-950, 1030-1046; finding 2 against :1975-2005; finding
3's citations against Common.cs:540-562, 605-620, 910-935, Event.cs:45-60,
InputHook.cs:218-230, 340-350, frmScreen.cs:560-578; the two corrected
citations; then read ChannelConfig.swift, ControlChannel.swift,
PeerConnection.swift, Resolver.swift top to bottom for CLAUDE.md
compliance, and, because finding 3 is about a liveness signal that reaches
across the MWBNet/MWBCore boundary, read Sources/MWBCore/Session.swift's
start(now:) and tick(now:userActive:) to see how the channel's
userActive is actually consumed.
tools/guard.sh -m 8 -t 600 -- tools/gates.sh: green (lint --strict, MWBCore layering, warnings-as-errors build). Neither limit was hit.- Finding 1 — fixed, matches Windows.
Resolver.addresses(Resolver.swift:33-47) now checks the mapped group alone (!mapped.isEmpty, config.sameSubnetOnly, !isSameSubnet(mapped)) and returns[]beforelookup(name)is ever called, reproducingSocketStuff.cs:926-937'sreturnthat skipsDns.GetHostEntryat:950entirely. The DNS group is then resolved, reverse-validated, and gets its own independent same-subnet check that on failure zeroes onlyresolved(:1035-1044), so a rejected DNS group no longer suppresses an already-accepted mapped group.CheckForSameSubNetitself returnstruewhenever!Setting.Values.SameSubNetOnlyor either side has no IPv4 address (SocketStuff.cs:1069-1085), which the Swift gates (!mapped/ resolved.isEmpty, config.sameSubnetOnly) andisSameSubnet's own empty-array short-circuits (Resolver.swift:142, 144) reproduce. Both QA scenarios from round 1 now dial exactly what Windows dials.docs/protocol.md§10.3 note 6 states the two different failure modes; the citations (:928-944, 950,:989-1044,:934-937,:941, 1037-1040) all check out against the reference file. - Finding 2 — fixed, matches Windows.
ControlChannel.accept(_:name:id:)(ControlChannel.swift:377-394) now runs the id-collision check and the keep-the-first-client check as two branches of oneif peer.isOutboundblock, reproducingUpdateTcpSockets'sstatus == Connected && tcp.IsClientgate (SocketStuff.cs:1980-1981) around both the id compare (:1984-1992) and the dedup (:1993-1997). An inbound peer announcing our id now falls through todialers[name] = nil; sink.channel(...)untouched, same as Windows silently accepting it.docs/protocol.md§10.3 note 3 states the client-only gate and cross-references note 4; theDisconnectReason .idCollisionandchannelDetectedIDCollisiondoc comments (ChannelConfig.swift:121-123, 186-189) say the same. Matches. - Finding 3, the literal ask — fixed.
ControlChannel.tick()(:457-471) now comparesinputEventCount != beatInputEventCount, two counters bumped bynoteUserActivity()(:201-203, ourEvent.RealInputEventCount++) and re-snapshotted on a periodic boundary — a counter compare, not a sliding window, which is what was asked for.docs/protocol.md§3.3's citation is nowCommon.cs:542-559(confirmed:SendAwakeBeatitself,lastRealInputEventCount/lastInputEventCountfields included at542-543, function body545-559) withCommon.cs:547-548for theBlockScreenSaver/IsMyDesktopActive/ logon-desktop conditions — both check out exactly againstApp/Core/Common.cs.Event.cs:51-55(RealInputEventCountproperty) andInputHook.cs:223, 345(Event.RealInputEventCount++in the mouse and keyboard hooks) also check out. - Corrected citations — both right.
Common.SendByeByeisCommon.cs:611-615(confirmed exactly:internal static void SendByeBye()through the closing brace).SkSend's stamp isCommon.cs:916(data.Id = Interlocked.Increment(...)) and the fan-out loop through the matrix test is:916-930, ending at thesk.TcpSend(t, data)call — theChannelConfig.swift:87doc comment's narrower:922-930for "theDes == ID.ALLmatrix test" is theforeach-through-TcpSendsub-range and is consistent with it. - Compliance pass: no force-unwrap,
try!,fatalErrororpreconditionin any of the four files (checked with a grep for bare!/try!/fatalError/precondition(and manually cleared every hit — all are!=,guard !x, or!collection.contains, none are force-unwraps); noprint/Logger/os_log/NSLoganywhere inMWBNet. File sizes (191/535/356/235) match the work log exactly and stay inside CLAUDE.md's targets;tick()(15 lines),accept(_:name:id:)(18 lines) andResolver.addresses(15 lines) are all well inside 10–50.
New finding — finding 3's fix is incomplete: the channel's beat boundary
that resets beatInputEventCount is not the moment any connection actually
sends its heartbeat, so a connection can report Heartbeat when real input
happened since its own previous heartbeat. ControlChannel.tick()
(ControlChannel.swift:457-471) resets beatInputEventCount on the
channel's own clock: lastBeatAt starts at 0 (:61) and the boundary
fires every time now - lastBeatAt >= interval on the channel's 100 ms
timer, independent of any connection. But no connection's heartbeat is sent
on that clock — each PeerConnection's Session decides independently,
via its own nextHeartbeat field, set to now + heartbeatInterval in
start(now:) (Sources/MWBCore/Session.swift:167, now there being that
connection's handshake-completion time) and rescheduled the same way from
its own fire time in tick(now:userActive:)
(Session.swift:218-223). Nothing ties the two schedules together
(ControlChannel.swift:59-61 has no connection-keyed state at all), so a
connection's own heartbeat instant is generally out of phase with the
channel's reset instant. Concrete case: channel resets beatInputEventCount
at t=50; a connection's own nextHeartbeat fires at t=60 (phase set by
when that connection's handshake completed, unrelated to t=50); the
user's last click was at t=10, nothing since. At t=50 the reset
snapshots beatInputEventCount to a value that already includes the t=10
click; at the connection's own send at t=60, inputEventCount == beatInputEventCount (no new input since t=50), so userActive reads
false and the connection sends Heartbeat (20) — even though the click at
t=10 postdates that connection's own previous heartbeat and Windows's
single, truly-simultaneous SendAwakeBeat() call would have sent Awake (21) to every socket for it. Round 1's sliding-window version did not have
this failure mode: now - lastUserActivity <= interval, evaluated fresh at
whatever instant a connection ticked, had no shared reset to be out of phase
with. Awake is not cosmetic: on the peer it drives
Common.HumanBeingDetected() (Receiver.cs:245-248), which is the
mechanism the BlockScreenSaver feature (default on —
ChannelConfig.swift:59, blockScreenSaver: Bool = true) depends on to
keep a peer from screen-locking while this machine's user is active. The
work log's claim that "the boundary is the channel's, which is the one
global beat Windows's 100 ms timer runs for every socket at once"
(entry 3, and the matching doc comment at ControlChannel.swift:450-456)
overstates this: Windows's beat is the send, for every socket, in one call
(Common.cs:545-558, frmScreen.cs:565-575); the channel's beat is a
sampling boundary that no send is pinned to. Not a safety issue (invariants
2–4 are untouched) and it self-corrects once any two beats in a row see
continuous activity, but it is a real, default-on regression in exactly the
mechanism this finding was reworked to fix, and it needs either a
Session-side change (a session-matrix handshake — Session would have to
report its own beat, or take the raw counter and do the compare itself) or a
different ControlChannel-side scheme that doesn't rely on a channel-wide
reset. Flagged, not fixed — outside "verify, don't redesign."
Verdict: REWORK
Review
- 2026-09-16 (lead): inspected per
docs/loop.md§5 after two rework rounds. Gates green run by me; diff limited to the fourMWBNetfiles,Session.tick(authorised cross-lane change), TODO §3, protocol §10.3 and the two READMEs. ReadPeerConnection.swiftin full andControlChannel.swift's structure: 48-byte preamble first, sized reads with the real count passed tonoteReceiveError, bounded outbox and 500 ms deadline, stall rule armed bymarkControlled, all state on one queue,[weak self]throughout, nothing logged, nothing interpreted. QA round 2's heartbeat finding is fixed at the right place (Sessioncompares the raw counter against its own last beat,Common.cs:542-559). Verdict: merge. Carry into app-shell: the three open requests in this README — callreopenAll()on a countdown while nothing is connected (frmScreen.cs:427-450), callmarkControlled(peerID:)on every switch including back to local, and (done at close) the session-matrix Assumptions wording.