jack c6b7096b2f
BLE transport architecture V3: one engine domain, capability ports, feature-owned state (#1498)
* Make peer registry and local announce state lock-backed

The main actor answered isPeerConnected/peerNickname/currentPeerSnapshots
and flipped runtime capability bits by blocking on collectionsQueue behind
whatever transport work was in flight. Peer state now lives in a
lock-backed BLEPeerRegistryStore (every registry mutation is a single
whole-transition method, so readers never observe a torn state), and the
runtime capability bits move into BLELocalIdentityStateStore next to the
identity they ride announces with. No transport entry point called from
the main actor blocks on a transport queue for peer state anymore.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Move BLE link egress/ingress buffers to bleQueue ownership

pendingPeripheralWrites, pendingNotifications, and pendingWriteBuffers
were collectionsQueue-guarded, but every producer and drain already runs
on bleQueue next to the CoreBluetooth objects they feed — each access
paid a cross-queue barrier for state that never leaves the radio thread,
and the notification drain even invoked peripheralManager.updateValue
from the collections queue. They are now bleQueue-confined like the link
state store: CB delegate callbacks and drains touch them directly, and
the few engine-side entry points hop to bleQueue (the direction the
transport's sync-edge order already allows). This clears most
bleQueue-to-collectionsQueue sync edges ahead of merging the collections
queue into the message queue.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Stop bleQueue maintenance and status paths from blocking on collectionsQueue

The traffic-burst tracker becomes a lock-backed monitor (written by the
receive pipeline, read by scan-duty adaptation and announce pacing on
bleQueue), the status-log peer summary and topology refresh read the
already lock-backed registry directly, and the stalled-fragment reap
moves to an async collections hop with the gossip resync request inside
it. bleQueue no longer sync-waits on the collections queue anywhere.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Unify the message and collections queues into one serial engine queue

The old model ran a concurrent message queue over a second concurrent
collections queue whose barrier flags served as the real mutual
exclusion — every field carried an ownership comment, and correctness
lived in per-site discipline. The message queue is now a single serial
engine queue that owns all mesh protocol state; the collections queue,
its 98 sync/async hops, and every barrier flag are gone. Cross-thread
callers go through onEngine, which documents and (in debug) enforces
the transport's sync-edge order: main and test threads may block on the
engine, the engine may block on bleQueue and the crypto/identity
queues, and nothing may block the other way.

The debug trap caught two latent inversions the leaf-lock structure had
been masking: the verified-announce rebind path re-resolved the ingress
link through the engine from inside its bleQueue critical section (it
now receives the already-resolved link), and the noise
session-generation closures sync-re-entered the engine from the noise
manager's queue while their own engine slot was blocked on it (they now
touch engine state directly, which the held slot makes exclusive).

BLE throughput is orders of magnitude below what one serial queue
sustains; the full suite runs at identical speed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Wire gateway/bridge/panic features to capability ports, not BLEService

App wiring discovered mesh-only features by casting the Transport to
the concrete BLEService class in nine places. Those surfaces are now
three capability protocols — BluetoothStateReporting,
PanicResettingTransport, and MeshBridgingTransport — discovered with
as? like any optional capability, so the bootstrapper, panic flow, and
lifecycle coordinator no longer name the concrete transport at all. A
future second mesh transport picks up gateway/bridge wiring and the
panic lifecycle by conforming, and the remaining Transport god-protocol
requirements can migrate to the same pattern.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Extract mesh-ping diagnostics state into a pure engine-confined tracker

First slice of the feature-module direction: BLEMeshPingTracker owns the
outstanding-probe map and the per-link inbound response budget as pure
state (register/resolve/expire/reset), so the security invariants — a
pong only resolves against the probed peer, the budget keys on the
ingress link because claimed senders are forgeable, panic reset drops
probes and budget together — are now unit-tested without queues or
radios. The transport keeps only packet I/O, timers, and main-actor
delivery around it.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Document the V3 transport architecture and remaining roadmap

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Resolve the pass-6 review findings and the proof-timeout drain defect

Periphery: the registry store's unused forwarders are gone (the struct
method stays — it has direct tests). F1: refreshPeerIdentity,
deliverBridgedEnvelope, and the three panic fences route through
onEngine, so every sync entry onto the engine now carries the bleQueue
trap. F2: the registry-store ownership comments state the real writer
set (engine plus the two bleQueue link-drop paths). F7:
BLEQueueContractTests pins the contract — only onEngine may sync-enter
the engine, transport code never sync-dispatches to main, and the
collections queue stays deleted — with a queue-contract-ok waiver for
the two sanctioned lines.

The real defect behind the timeoutRestoredSession CI flake: a
timeout-restore parks the outbound queues until the convergence retry,
but the capability-proof watchdog armed at the original authentication
kept draining them when it fired — encrypting the parked traffic under
restored keys the counterpart may have discarded, the exact silent loss
the defer path exists to prevent. Deferred peers are now tracked and
the watchdog drain respects the same rule; the test fires the watchdog
deterministically inside the deferred window instead of losing that
race only on stalled runners.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Extract private-media session state into a lock-backed store

The six generation-keyed maps plus the convergence-deferral set move
out of BLEService into BLEPrivateMediaSessionStore, each transition one
whole method under a leaf lock with direct unit tests (generation
rotation rejects mismatched waiters, stale proofs cannot classify a
replacement session, expiry requires the live deadline identity, clears
rebase waiters onto a nil-generation deadline, peer-state sends are
once per generation per kind).

Being a leaf lock also simplifies two contracts: the send policy is now
answered entirely from locks (the main actor no longer sync-enters the
engine for it), and the noise-manager critical sections call ordinary
store methods instead of relying on the held-engine-slot direct-access
subtlety.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Split the mesh-only Transport surface into capability protocols

Transport kept ~50 requirements that only the BLE mesh implements —
files/private media, voice, courier, groups, board, diagnostics,
verification, archive — held together by an extension of inert
defaults, so every call site compiled against a surface most transports
faked. Those are now eight capability protocols (MeshFileTransferring,
MeshVoiceStreaming, MeshCourierTransporting, MeshGroupMessaging,
MeshBoardBroadcasting, MeshDiagnosing, MeshVerifying,
MeshPublicArchiving) discovered with as?, joining the bridging/panic
ports from the previous pass. Consumers resolve the capability they
need; where the old defaults encoded a safe floor the caller keeps it
explicitly (private-media policy degrades to blockedDowngrade). The
inert-defaults extension is deleted, along with the never-implemented
acceptPendingFile/declinePendingFile pair. NostrTransport is untouched
— it only ever implemented the core.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Update the V3 doc for the completed feature-peeling and Transport split

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Drop the dead three-argument sendFilePrivate overload

Every production caller goes through the allowLegacyFallback variant;
the short form only existed as a Transport-era forwarding default.
Tests that used it on the concrete service now state the fallback
decision explicitly, which is the point of the parameter.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Decide the link-auth boundary: bindings become engine-owned

The atomicity that keeps link-auth on bleQueue exists to stop a binding
from changing between a security check and its action; once every
rebind is an engine operation, the engine's serial slot gives the same
guarantee, the stolen-link residual is unchanged (directed payloads are
Noise ciphertext), and the receive path lands in its sans-I/O shape —
the link layer reports bytes-plus-linkID and the engine resolves the
sender. Records the extraction order too: the binding-free radio half
first (after #1521 lands — it collides in the scanPlan region), then
bindings, then the delegates behind the port.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Fix two bleQueue-to-engine sync edges the queue merge created

The collections-to-engine conversion turned two formerly leaf-lock
sync calls into onEngine calls reachable from bleQueue, where the
debug trap (correctly) aborts: flushDirectedSpool runs from bleQueue
maintenance and now hops to the engine asynchronously, and ingress
recording — which must answer the duplicate gate on bleQueue the
moment a frame decodes — moves to a lock-backed BLEIngressLinkStore
read by the engine's relay and routing decisions.

Unit suites never hit either path (no CoreBluetooth managers means no
maintenance timer and no live receive path); the iOS simulator job
boots the real app as its test host, which is exactly where the
maintenance trap fired. The ingress one would have trapped a real
device on its first received packet — worth a device pass before
release.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Route all deferred engine work through an injectable scheduler

Relay jitter, announce delays, the ping and capability-proof deadlines,
notification retry backoff, and fragment pacing all reached the engine
through raw messageQueue.asyncAfter with product constants as deadlines
— the hidden-elapsed-deadline flake class that the test-timing hygiene
rules exist to contain, testable only by racing the wall clock.
BLEEngineScheduling is now the transport's single source of engine
delay: production is a thin veneer over the engine queue, tests inject
a manually advanced clock whose advance() returns only after the
released work has finished on the engine. The queue-contract test pins
the seam (no raw messageQueue.asyncAfter), and the ping deadline gets
the pattern's proof: the real 10s constant asserted in milliseconds —
must not fire early, fires exactly once at the deadline, stays consumed
after.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Assert the armed deadline count in the injected-clock ping test

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: jack <jackjackbits@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-29 16:03:20 +01:00
..