Files
suaveplan/openspec/specs/network/spec.md
2026-05-27 23:29:53 +01:00

764 lines
45 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Capability Spec: network
- **Capability**: `network`
- **Packages**: `@suaveplan/network`, `@suaveplan/network-transport-webrtc`, `@suaveplan/network-plugin-governance`, `@suaveplan/network-plugin-failover`, `@suaveplan/network-plugin-registry`, `@suaveplan/network-plugin-topology`, `@suaveplan/network-plugin-protocol`, `@suaveplan/network-plugin-session`, `@suaveplan/network-plugin-transport-manager`, `@suaveplan/network-plugin-crypto-messages`, `@suaveplan/network-plugin-server-bridge`, `@suaveplan/network-plugin-content-delivery`, `@suaveplan/network-plugin-audit-mesh`, `@suaveplan/network-plugin-relay`, `@suaveplan/network-plugin-assignment`, `@suaveplan/network-plugin-partition`, `@suaveplan/network-plugin-circuit-breaker`, `@suaveplan/network-plugin-qos`, `@suaveplan/network-plugin-migration`, `@suaveplan/network-plugin-auth`
- **Date**: 2026-05-01
---
## Requirements
### NET-01 — `NetworkPlugin` is the universal extension contract
Every network plugin MUST implement the `NetworkPlugin` interface: `name`, `install(node)`, `start()`, `stop()`, and optional `dispose()`. The core MUST call these hooks in order during node lifecycle. Plugins MUST NOT depend on each other directly; all cross-plugin communication MUST go through the `NetworkBus`.
**Verified by:** `packages/network/network/src/plugin/plugin.spec-conformance.test.ts` (`NET-01`).
### NET-02 — `NetworkNode` is the single entry-point
`NetworkNode` MUST expose a unified API: `use(plugin)`, `start()`, `stop()`, `send(targetId, envelope)`, `broadcast(envelope)`, and `on(event, handler)`. It MUST manage plugin lifecycle (install → start → stop → dispose) and MUST route messages between transport plugins and processing plugins.
**Verified by:** `packages/network/network/src/node/node.spec-conformance.test.ts` (`NET-02`).
### NET-03 — `MessageEnvelope` carries typed payloads with metadata
`MessageEnvelope` MUST contain: `id` (unique), `type` (string), `senderId`, `targetId` (or `"*"` for broadcast), `payload` (Uint8Array), `timestamp` (injectable Clock), and `headers` (optional metadata map). The core MUST validate envelope shape via Zod before routing.
**Verified by:** `packages/network/network/src/envelope/envelope.spec-conformance.test.ts` (`NET-03`).
### NET-04 — Transport plugins implement the `Transport` interface
Transport plugins MUST implement: `connect(peerId, address)`, `disconnect(peerId)`, `send(peerId, envelope)`, `onMessage(handler)`, and `getConnectedPeers()`. The core MUST fan-out `broadcast()` to all active transports and aggregate their peer lists.
**Verified by:** `packages/network/network/src/transport/transport.spec-conformance.test.ts` (`NET-04`).
### NET-05 — `NetworkBus` is the cross-plugin event broker
`NetworkBus` MUST provide typed publish/subscribe with FIFO delivery, bounded-queue backpressure, and interceptor support. Plugins MUST use bus topics (e.g., `peer:joined`, `peer:left`, `election:vote`) rather than direct imports.
**Verified by:** `packages/network/network/src/bus/bus.spec-conformance.test.ts` (`NET-05`).
### NET-06 — WebRTC plugin forms mesh automatically
`network-transport-webrtc` MUST: create `RTCPeerConnection` per peer, negotiate via pluggable signaling, open `RTCDataChannel` for envelope transport, and maintain a mesh where every peer knows every other peer in its group. It MUST retry ICE on failure and MUST emit `transport:connected` / `transport:disconnected` on the bus.
**Verified by:** `packages/network/network-transport-webrtc/src/mesh/mesh.spec-conformance.test.ts` (`NET-06`).
### NET-07 — WebRTC plugin supports ping and latency measurement
The WebRTC plugin MUST expose `ping(peerId)` which sends a correlated echo frame and measures RTT. It MUST publish `peer:latency` events on the bus with `{ peerId, rttMs }`. RTT MUST be averaged with an EMA.
**Verified by:** `packages/network/network-transport-webrtc/src/ping/ping.spec-conformance.test.ts` (`NET-07`).
### NET-08 — Governance plugin runs elections
`network-plugin-governance` MUST: collect votes via bus, score candidates by latency/uptime/reputation, break ties deterministically (lowest lex peerId), and publish `election:completed` with `{ winnerId, term }`. It MUST support `metric`, `direct`, and `hybrid` modes.
**Verified by:** `packages/network/network-plugin-governance/src/election/election.spec-conformance.test.ts` (`NET-08`).
### NET-09 — Registry plugin tracks joins and leaves
`network-plugin-registry` MUST maintain a `PeerRegistry` with one entry per peer (static + dynamic data). It MUST emit `peer:joined` / `peer:updated` / `peer:left` on the bus. It MUST sync deltas using `@suaveplan/bitpacker` for dynamic state (position, health, etc.) and MUST detect sequence gaps.
**Verified by:** `packages/network/network-plugin-registry/src/registry/registry.spec-conformance.test.ts` (`NET-09`).
### NET-10 — Failover plugin monitors heartbeats
`network-plugin-failover` MUST track heartbeats per peer with an alive → suspect → dead FSM. On `dead`, it MUST publish `failover:triggered` on the bus. It MUST support configurable `intervalMs`, `timeoutMs`, `suspectThreshold`, and `maxMissed`. It MUST NOT trigger failover during an active election.
**Verified by:** `packages/network/network-plugin-failover/src/heartbeat/heartbeat.spec-conformance.test.ts` (`NET-10`).
### NET-11 — Topology plugin manages tiered groups
`network-plugin-topology` MUST organize peers into tiers: Tier 0 (host), Tier 1 (sub-host), Tier 2 (leaf). It MUST auto-promote/demote based on capability scores and group size limits. It MUST publish `topology:changed` when structure changes.
**Verified by:** `packages/network/network-plugin-topology/src/tiers/tiers.spec-conformance.test.ts` (`NET-11`).
### NET-12 — All network errors extend `SuaveplanError`
Every network package MUST use `defineCodes("NET", [...])` (or `NET_WEBRTC`, `NET_GOV`, etc.) and extend `SuaveplanError`. Error codes MUST be frozen registries.
**Verified by:** Each package's `src/error-codes.spec-conformance.test.ts` (`NET-12`).
### NET-13 — Registry plugin uses compact binary encoding
`network-plugin-registry` MUST encode `DynamicData` into a binary format of ≤ 62 bytes using `@suaveplan/bitpacker`. It MUST provide roundtrip encoding/decoding and MUST emit `registry:update` on the bus after each change.
**Verified by:** `packages/network/network-plugin-registry/src/encoder/encoder.spec-conformance.test.ts` (`NET-13`).
### NET-14 — Topology plugin assigns latency groups
`network-plugin-topology` MUST assign peers to `LatencyGroup` buckets based on RTT. It MUST rebalance periodically (configurable interval) and emit `latency:rebalance` on the bus.
**Verified by:** `packages/network/network-plugin-topology/src/latency/latency.spec-conformance.test.ts` (`NET-14`).
### NET-15 — Protocol plugin uses 13-byte binary header
`network-plugin-protocol` MUST prefix every message with a 13-byte header: `version(1) | flags(1) | messageType(1) | timestamp(8) | payloadLength(2)`. Version MUST be `1` for this revision.
**Verified by:** `packages/network/network-plugin-protocol/src/protocol/protocol.spec-conformance.test.ts` (`NET-15`).
### NET-16 — Protocol pipeline orders transforms correctly
`network-plugin-protocol` MUST wire the outbound pipeline as: `MessageEncoder` → `lengthPrefixEncode` → `CryptoTransform` → `compressStream`. Inbound MUST be the exact reverse. Any stage failure MUST throw `StreamPipeFailedError`.
**Verified by:** `packages/network/network-plugin-protocol/src/pipeline/pipeline.spec-conformance.test.ts` (`NET-16`).
### NET-17 — Protocol plugin supports schema-aware message encoding
`network-plugin-protocol` MUST encode/decode messages using `@suaveplan/bitpacker` with per-`MessageType` schemas. All `MessageType` variants MUST roundtrip through encode/decode.
**Verified by:** `packages/network/network-plugin-protocol/src/encoder/encoder.spec-conformance.test.ts` (`NET-17`).
### NET-18 — Session plugin provides logical session trees
`network-plugin-session` MUST maintain a tree of sessions with exactly one root per mesh. Each peer MUST belong to exactly one leaf session. Messages MUST be scoped to session branches and MUST NOT leak to peers outside the scope.
**Verified by:** `packages/network/network-plugin-session/src/router/router.spec-conformance.test.ts` (`NET-18`).
### NET-19 — Sessions support nested hierarchies
`network-plugin-session` MUST support arbitrary nesting depth (bounded at 4). Child sessions MUST receive optional read-only parent state via `ParentStateBridge`. Parent session peers MUST NOT receive child session messages.
**Verified by:** `packages/network/network-plugin-session/src/session/session.spec-conformance.test.ts` (`NET-19`).
### NET-20 — Per-session host election
Each session MUST nominate its own host independently of the mesh Tier 0 host. A peer MAY host multiple sessions. Session host election MUST use the same scoring algorithm as mesh governance but scoped to session peers.
**Verified by:** `packages/network/network-plugin-session/src/election/election.spec-conformance.test.ts` (`NET-20`).
### NET-21 — Session transitions with state snapshot
Join, leave, and move operations MUST transition through FSM states with state snapshot transfer from the session host. Move operations MUST create a temporary forwarding tunnel between old and new session hosts.
**Verified by:** `packages/network/network-plugin-session/src/transition/transition.spec-conformance.test.ts` (`NET-21`).
### NET-22 — Session capacity enforcement
Each session MUST enforce a configurable capacity limit. `join()` MUST be rejected with `NET_SESSION_CAPACITY_EXCEEDED` when full. The session registry MUST track peer counts for assignment decisions.
**Verified by:** `packages/network/network-plugin-session/src/capacity/capacity.spec-conformance.test.ts` (`NET-22`).
### NET-23 — Multi-transport simultaneous operation
`network-plugin-transport-manager` MUST maintain multiple active transports per peer simultaneously. It MUST register transports dynamically and MUST track health scores per transport.
**Verified by:** `packages/network/network-plugin-transport-manager/src/pool/pool.spec-conformance.test.ts` (`NET-23`).
### NET-24 — Capability-based transport negotiation
Peers MUST exchange capability bitmaps during handshake. The transport manager MUST only use transports supported by both peers.
**Verified by:** `packages/network/network-plugin-transport-manager/src/negotiator/negotiator.spec-conformance.test.ts` (`NET-24`).
### NET-25 — Priority-based message routing
Messages MUST be routed based on 5 priority tiers: `CRITICAL`, `HIGH`, `NORMAL`, `LOW`, `BULK`. CRITICAL messages MUST be sent redundantly on 2+ transports. BULK messages MUST use backpressure-aware transport selection.
**Verified by:** `packages/network/network-plugin-transport-manager/src/priority/priority.spec-conformance.test.ts` (`NET-25`).
### NET-26 — Round-robin load balancing
NORMAL and BULK traffic MUST be distributed across all healthy transports using round-robin to prevent path saturation.
**Verified by:** `packages/network/network-plugin-transport-manager/src/balancer/balancer.spec-conformance.test.ts` (`NET-26`).
### NET-27 — Ed25519 message signatures
Every outbound message from a host MUST be signed with Ed25519. Inbound signatures MUST be verified using peer public keys from the registry. Invalid signatures MUST reject the message.
**Verified by:** `packages/network/network-plugin-crypto-messages/src/signer/signer.spec-conformance.test.ts` (`NET-27`).
### NET-28 — Server-signed session tokens
Session creation MUST require a server-signed token. Tokens MUST include `sessionId`, `parentSessionId`, `capacity`, `rulesHash`, `expiresAt`, and `serverSignature`. Peers MUST reject sessions without valid tokens.
**Verified by:** `packages/network/network-plugin-crypto-messages/src/session-token/session-token.spec-conformance.test.ts` (`NET-28`).
### NET-29 — Server-signed mesh tokens
Mesh creation MUST require a server-signed token. Tokens MUST include `meshId`, `maxCapacity`, `allowedTiers`, `expiresAt`, and `serverSignature`.
**Verified by:** `packages/network/network-plugin-crypto-messages/src/mesh-token/mesh-token.spec-conformance.test.ts` (`NET-29`).
### NET-30 — Peer identity challenge-response
Peer handshake MUST include a challenge-response protocol to verify identity. Spoofed peer IDs MUST be detected and rejected.
**Verified by:** `packages/network/network-plugin-crypto-messages/src/identity/identity.spec-conformance.test.ts` (`NET-30`).
### NET-31 — Server bridge heartbeat and detection
`network-plugin-server-bridge` MUST maintain a persistent WebSocket from Tier 0 hosts to the central server. Server disconnect MUST be detected within 2× heartbeat interval.
**Verified by:** `packages/network/network-plugin-server-bridge/src/gateway/gateway.spec-conformance.test.ts` (`NET-31`).
### NET-32 — Offline autonomous operation
When the server is offline, the mesh MUST continue operating autonomously. Token grace periods MUST be extended. New session/mesh creation MUST be paused. Signed logs MUST be buffered locally.
**Verified by:** `packages/network/network-plugin-server-bridge/src/offline/offline.spec-conformance.test.ts` (`NET-32`).
### NET-33 — Log replay and reconciliation on reconnection
When the server reconnects, buffered logs MUST be replayed in sequence. The server MUST validate signatures, detect conflicts, and broadcast reconciled state.
**Verified by:** `packages/network/network-plugin-server-bridge/src/reconciliation/reconciliation.spec-conformance.test.ts` (`NET-33`).
### NET-34 — Server command dispatch
Server commands (kick, merge, split, token issue, broadcast) MUST be validated via Ed25519 signature and dispatched to appropriate plugins.
**Verified by:** `packages/network/network-plugin-server-bridge/src/command/command.spec-conformance.test.ts` (`NET-34`).
### NET-35 — P2P chunk distribution with redundancy
`network-plugin-content-delivery` MUST distribute file chunks across mesh peers with configurable redundancy (N copies). Chunk holders MUST be discoverable via gossip index. Re-replication MUST trigger on peer departure.
**Verified by:** `packages/network/network-plugin-content-delivery/src/redundancy/redundancy-manager.spec-conformance.test.ts` (`NET-35`).
### NET-36 — Chunk integrity verification
Every received chunk MUST be verified against its BLAKE3 hash. Corrupted chunks MUST be rejected and the sender temporarily blacklisted.
**Verified by:** `packages/network/network-plugin-content-delivery/src/integrity/integrity-verifier.spec-conformance.test.ts` (`NET-36`).
### NET-37 — Signed audit log chains
`network-plugin-audit-mesh` MUST maintain append-only logs where each entry includes `seq`, `prevHash`, `hostSignature`. Hash chain breaks MUST be detected as corruption.
**Verified by:** `packages/network/network-plugin-audit-mesh/src/log/signed-log.spec-conformance.test.ts` (`NET-37`).
### NET-38 — Cross-host log replication
Log entries MUST be replicated to at least R sibling hosts. CRITICAL events MUST replicate synchronously. NORMAL events MAY replicate asynchronously.
**Verified by:** `packages/network/network-plugin-audit-mesh/src/replicator/log-replicator.spec-conformance.test.ts` (`NET-38`).
### NET-39 — Log compaction and checkpoints
Old logs MUST be compacted into signed checkpoints. Checkpoints MUST contain a state snapshot at a given sequence number to reduce replay volume.
**Verified by:** `packages/network/network-plugin-audit-mesh/src/compaction/log-compaction.spec-conformance.test.ts` (`NET-39`).
### NET-40 — Intra-mesh relay for NAT traversal
`network-plugin-intra-relay` MUST discover relay candidates from the mesh topology, excluding leaf-tier peers. It MUST select optimal relays using `LowestLatency`, `HighestReliability`, `FewestHops`, `TierOptimized`, or `LoadBalanced` strategies. Relay messages MUST include `relayPath`, `hopCount`, `maxHops` (default 8), and `visitedNodes` for loop prevention. Messages MUST be dropped when `hopCount >= maxHops` or when `visitedNodes` contains the current peer.
**Verified by:** `packages/network/network-plugin-intra-relay/src/selector/selector.spec-conformance.test.ts` (`NET-40`).
### NET-41 — Middleware pipeline with priority ordering
`network-plugin-middleware` MUST execute middleware in 5 priority bands: `CRITICAL` (0–99), `HIGH` (100–199), `NORMAL` (200–299), `LOW` (300–399), `BACKGROUND` (400+). Middleware MUST support both incoming and outgoing directions. Any middleware returning `null` MUST drop the message. Middleware MUST be addable, removable, enableable, and disableable at runtime.
**Verified by:** `packages/network/network-plugin-middleware/src/manager/manager.spec-conformance.test.ts` (`NET-41`).
### NET-42 — State synchronization with conflict resolution
`network-plugin-state` MUST maintain versioned state with path-based access. It MUST support 5 reconciliation strategies: `latest-wins`, `remote-wins`, `local-wins`, `deep-merge`, and `custom`. Strategies MUST be configurable per path via `PathStrategyRegistry`. Delta sync MUST use `@suaveplan/bitpacker` for compression. Bloom filters MUST be used for efficient divergence detection. Full-state sync MUST be available for new peers.
**Verified by:** `packages/network/network-plugin-state/src/reconciler/reconciler.spec-conformance.test.ts` (`NET-42`).
### NET-43 — Network simulation framework
`network-plugin-simulation` MUST provide deterministic virtual network creation with configurable seeds. It MUST support time acceleration/deceleration. Virtual nodes MUST use the same `NetworkNode` code as real nodes. Predefined scenarios MUST include: `ServerFailure`, `NetworkPartition`, `ClientSurge`, and `CascadingFailure`. The chaos engine MUST support probabilistic peer crashes, partition injection, and random message drops.
**Verified by:** `packages/network/network-plugin-simulation/src/scenarios/cascading-failure.spec-conformance.test.ts` (`NET-43`).
### NET-44 — Monitoring and distributed tracing
`network-plugin-monitor` MUST collect metrics in 4 categories: node, connection, message, and hierarchy. It MUST support 4 metric types: Counter, Gauge, Histogram, and Summary. The tracer MUST propagate OpenTelemetry-compatible trace IDs across mesh hops via message headers. Sampling strategies MUST include: probabilistic, rate-limited, error-based, and priority-based. Alerting MUST emit `monitor:alert` on the bus when thresholds are exceeded.
**Verified by:** `packages/network/network-plugin-monitor/src/tracer/tracer.spec-conformance.test.ts` (`NET-44`).
### NET-45 — Serialization strategy framework
`network-plugin-protocol` MUST support multiple serialization strategies: JSON, Binary, and MessagePack. A `SerializerFactory` MUST select the appropriate serializer by content type with fallback to JSON. Content-type negotiation MUST be signaled in the 13-byte header flags.
**Verified by:** `packages/network/network-plugin-protocol/src/serialization/serialization.spec-conformance.test.ts` (`NET-45`).
### NET-46 — Pre-emptive transport switching
`network-plugin-transport-manager` MUST analyze quality trends (latency slope, packet loss trend, bandwidth degradation) and initiate transport switching BEFORE complete failure. The handoff MUST be smooth: establish the new transport before tearing down the old, with a configurable overlap window.
**Verified by:** `packages/network/network-plugin-transport-manager/src/selector/preemptive.spec-conformance.test.ts` (`NET-46`).
### NET-47 — Plugin security verifier
`network-plugin-crypto-messages` MUST validate plugin integrity before registration via `PluginSecurityVerifier`. It MUST enforce that plugins cannot exceed their declared capability set. Anomalous plugin activity (excessive broadcast, unauthorized operations) MUST be detected and reported.
**Verified by:** `packages/network/network-plugin-crypto-messages/src/plugin-security/plugin-security.spec-conformance.test.ts` (`NET-47`).
### NET-48 — Tier-specific security policies
`network-plugin-crypto-messages` MUST enforce different security rules per tier: Tier 0 has full authority, Tier 1 has relay and voting authority without token issuance, Tier 2 has read-only access for sensitive operations. Cross-tier operations MUST require explicit credential delegation from a higher tier.
**Verified by:** `packages/network/network-plugin-crypto-messages/src/policy/tier-policy.spec-conformance.test.ts` (`NET-48`).
### NET-49 — Resource-constrained adaptation
`network-plugin-topology` MUST classify peers into device profiles: `CONSTRAINED`, `STANDARD`, `POWERFUL`, `SERVER`. Tier depth MUST adapt based on network size and available high-resource nodes. Message pooling MUST be used for constrained devices. Resource balancing MUST detect CPU/memory/bandwidth imbalances and recommend promotions/demotions.
**Verified by:** `packages/network/network-plugin-topology/src/resource/resource.spec-conformance.test.ts` (`NET-49`).
### NET-50 — Tier partition handling
`network-plugin-topology` MUST detect network partitions via connectivity map analysis. Partitions MUST be allowed to operate autonomously with local hierarchies. Recovery MUST use controlled reconnection with primary partition selection (size-based, performance-based, or hybrid). Diverged state MUST be reconciled after partition healing.
**Verified by:** `packages/network/network-plugin-topology/src/partition/partition.spec-conformance.test.ts` (`NET-50`).
### NET-51 — Geographic-aware routing
`network-plugin-topology` MUST track peer geographic regions and preferentially cluster peers from the same region. Parent-child assignments MUST minimize cross-region latency where possible.
**Verified by:** `packages/network/network-plugin-topology/src/geo/geo.spec-conformance.test.ts` (`NET-51`).
### NET-52 — Circuit breaker and hysteresis for reorganizations
`network-plugin-topology` MUST pause reorganizations during cascading failures via a circuit breaker (time-based, count-based, or impact-based). Promotion and demotion MUST include configurable cooldown periods to prevent oscillation. Peers MUST meet a minimum stability threshold before promotion eligibility.
**Verified by:** `packages/network/network-plugin-topology/src/stability/stability.spec-conformance.test.ts` (`NET-52`).
### NET-53 — API versioning
`network-core` MUST include semantic versioning (`major.minor.patch`) in `MessageEnvelope` headers. `VersionInfo.isCompatibleWith(other)` MUST require matching major version and minor >= required. Incompatible peers MUST be rejected during handshake. Migration paths between versions MUST be documented.
**Verified by:** `packages/network/network/src/version/version.spec-conformance.test.ts` (`NET-53`).
### NET-54 — Network timestamps
`network-core` MUST provide `NetworkTimestamp` with ISO8601, unix, and custom formats. It MUST support timezone adjustment and precision levels (millisecond, microsecond, nanosecond). The `Clock` interface MUST be injectable for testing. All envelope timestamps MUST use UTC internally.
**Verified by:** `packages/network/network/src/timestamp/timestamp.spec-conformance.test.ts` (`NET-54`).
### NET-55 — Standardized event constants
`network-core` MUST define a frozen `NetworkEvents` enum containing all standard bus topics: node lifecycle (`node:created`, `node:connected`, etc.), message (`message:sent`, `message:received`, etc.), hierarchy (`hierarchy:changed`, etc.), plugin (`plugin:registered`, etc.), and system (`system:error`, etc.). All plugins SHOULD use these constants instead of raw strings.
**Verified by:** `packages/network/network/src/events/events.spec-conformance.test.ts` (`NET-55`).
### NET-56 — Configurable hosting model
`network-plugin-server-bridge` MUST support 4 hosting models: `PURE_CLIENT` (no server), `SERVER_BASED` (server always hosts), `SERVER_TO_CLIENT_FAILOVER` (server → client on disconnect), and `CLIENT_WITH_SERVER_BACKUP` (client hosts, server overrides when online). The model MUST be selectable at mesh creation and MUST affect election behavior, token authority, and reconciliation direction.
**Verified by:** `packages/network/network-plugin-server-bridge/src/hosting/hosting.spec-conformance.test.ts` (`NET-56`).
### NET-57 — Message priority queue and adaptive batching
`network-plugin-protocol` MUST implement a `PriorityMessageQueue` with 5 tiers (CRITICAL bypasses queue). FIFO ordering MUST be maintained within the same tier. `MessageBatcher` MUST group messages by type/recipient and flush on size, time, or priority triggers. The batch interval MUST adapt based on network conditions.
**Verified by:** `packages/network/network-plugin-protocol/src/queue/queue.spec-conformance.test.ts` (`NET-57`).
### NET-58 — Message TTL and loop detection
`network-plugin-protocol` MUST decrement a `ttl` field per hop and drop messages when `ttl <= 0`. The `visitedNodes` header MUST be checked for cycles; messages visiting the same node twice MUST be dropped. Broadcast messages MUST be deduplicated via `messageId` bloom filter.
**Verified by:** `packages/network/network-plugin-protocol/src/ttl/ttl.spec-conformance.test.ts` (`NET-58`).
### NET-59 — Route caching
`network-plugin-protocol` MUST cache frequently used `(source, target) → nextHop` mappings. The cache MUST be invalidated on `topology:changed` bus events. Cache size MUST adapt based on available memory.
**Verified by:** `packages/network/network-plugin-protocol/src/cache/cache.spec-conformance.test.ts` (`NET-59`).
### NET-60 — Session persistence during disconnection
`network-plugin-transport-manager` MUST buffer connection state during temporary drops. Reconnection MUST use exponential backoff with jitter. Buffered messages MUST be replayed in sequence on recovery. CRITICAL connections MUST recover before NORMAL and BULK connections.
**Verified by:** `packages/network/network-plugin-transport-manager/src/recovery/recovery.spec-conformance.test.ts` (`NET-60`).
---
## New requirements (NET-61 – NET-112)
### NET-61 — `RelayRouter` maintains a routing table
`network-plugin-relay` MUST maintain a routing table from `(destMeshId, destPeerId)` to `nextHopHostId`.
**Verified by:** `packages/network/network-plugin-relay/src/router/router.spec-conformance.test.ts` (`NET-61`).
### NET-62 — `HostBackboneTransport` connects Tier 0 hosts
`network-plugin-relay` MUST provide a `HostBackboneTransport` that connects Tier 0 hosts with capability negotiation.
**Verified by:** `packages/network/network-plugin-relay/src/backbone/backbone.spec-conformance.test.ts` (`NET-62`).
### NET-63 — `CrossMeshEnvelope` extends `MessageEnvelope`
`network-plugin-relay` MUST define a `CrossMeshEnvelope` that extends `MessageEnvelope` with `senderMeshId`, `targetMeshId`, `hopCount`, `maxHops`, `visitedNodes`, and `ttl`.
**Verified by:** `packages/network/network-plugin-relay/src/envelope/envelope.spec-conformance.test.ts` (`NET-63`).
### NET-64 — Cross-mesh messages drop at max hops
`network-plugin-relay` MUST drop cross-mesh messages when `hopCount >= maxHops`.
**Verified by:** `packages/network/network-plugin-relay/src/loop-prevention/loop-prevention.spec-conformance.test.ts` (`NET-64`).
### NET-65 — Cross-mesh messages drop at TTL expiry
`network-plugin-relay` MUST drop cross-mesh messages when `ttl <= 0`.
**Verified by:** `packages/network/network-plugin-relay/src/loop-prevention/loop-prevention.spec-conformance.test.ts` (`NET-65`).
### NET-66 — Cross-mesh messages drop on loop detection
`network-plugin-relay` MUST drop cross-mesh messages when `visitedNodes` contains the current node.
**Verified by:** `packages/network/network-plugin-relay/src/loop-prevention/loop-prevention.spec-conformance.test.ts` (`NET-66`).
### NET-67 — `MeshDirectory` registers known meshes
`network-plugin-relay` MUST provide a `MeshDirectory` that registers known meshes and their Tier 0 hosts.
**Verified by:** `packages/network/network-plugin-relay/src/directory/directory.spec-conformance.test.ts` (`NET-67`).
### NET-68 — Cross-mesh broadcast is deduplicated
`network-plugin-relay` MUST relay broadcast messages (`targetMeshId = "*"`) to all known meshes and deduplicate them at mesh boundaries.
**Verified by:** `packages/network/network-plugin-relay/src/manager/manager.spec-conformance.test.ts` (`NET-68`).
### NET-69 — `RelayManager` intercepts cross-mesh outbound messages
`network-plugin-relay` MUST intercept outbound messages where `targetMeshId !== localMeshId` and forward them.
**Verified by:** `packages/network/network-plugin-relay/src/manager/manager.spec-conformance.test.ts` (`NET-69`).
### NET-70 — Inbound cross-mesh envelopes are delivered locally
`network-plugin-relay` MUST deliver inbound cross-mesh envelopes to the local `NetworkBus` scoped to the target peer.
**Verified by:** `packages/network/network-plugin-relay/src/manager/manager.spec-conformance.test.ts` (`NET-70`).
### NET-71 — `MeshCapacityTracker` tracks utilization
`network-plugin-assignment` MUST track `currentPeers / maxPeers` per mesh from registry events.
**Verified by:** `packages/network/network-plugin-assignment/src/tracker/tracker.spec-conformance.test.ts` (`NET-71`).
### NET-72 — `AssignmentEngine` scores candidate meshes
`network-plugin-assignment` MUST score candidate meshes using latency, capacity, load, region, and tier fit.
**Verified by:** `packages/network/network-plugin-assignment/src/engine/engine.spec-conformance.test.ts` (`NET-72`).
### NET-73 — `AssignmentEngine` returns null when no mesh is suitable
`network-plugin-assignment` MUST return `null` when no suitable mesh is found.
**Verified by:** `packages/network/network-plugin-assignment/src/engine/engine.spec-conformance.test.ts` (`NET-73`).
### NET-74 — `MeshBalancer` detects imbalance
`network-plugin-assignment` MUST detect imbalance and generate `RebalancePlan` objects.
**Verified by:** `packages/network/network-plugin-assignment/src/balancer/balancer.spec-conformance.test.ts` (`NET-74`).
### NET-75 — `AdmissionController` rejects at global capacity
`network-plugin-assignment` MUST reject peers when global capacity is exceeded.
**Verified by:** `packages/network/network-plugin-assignment/src/controller/controller.spec-conformance.test.ts` (`NET-75`).
### NET-76 — `AdmissionController` returns alternatives
`network-plugin-assignment` MUST return ranked alternative meshes when the primary mesh is full.
**Verified by:** `packages/network/network-plugin-assignment/src/controller/controller.spec-conformance.test.ts` (`NET-76`).
### NET-77 — Rebalancing triggers migration
`network-plugin-assignment` MUST trigger `network-plugin-migration` for peer state transfer during rebalance.
**Verified by:** `packages/network/network-plugin-assignment/src/balancer/balancer.spec-conformance.test.ts` (`NET-77`).
### NET-78 — `PartitionDetector` tracks epochs
`network-plugin-partition` MUST track epochs from all known peers and detect partition when a majority is unreachable.
**Verified by:** `packages/network/network-plugin-partition/src/detector/detector.spec-conformance.test.ts` (`NET-78`).
### NET-79 — `PartitionView.partitionId` is deterministic
`network-plugin-partition` MUST produce a deterministic `partitionId` hash of the sorted reachable peer set.
**Verified by:** `packages/network/network-plugin-partition/src/detector/detector.spec-conformance.test.ts` (`NET-79`).
### NET-80 — `QuorumResolver` supports multiple strategies
`network-plugin-partition` MUST support `size`, `performance`, `age`, and `hybrid` quorum resolution strategies.
**Verified by:** `packages/network/network-plugin-partition/src/quorum/quorum.spec-conformance.test.ts` (`NET-80`).
### NET-81 — `MergeProtocol` reconciles state
`network-plugin-partition` MUST reconcile registry, topology, and audit state when partitions heal.
**Verified by:** `packages/network/network-plugin-partition/src/merge/merge.spec-conformance.test.ts` (`NET-81`).
### NET-82 — Non-authoritative peers rejoin after merge
`network-plugin-partition` MUST cause non-authoritative partition peers to rejoin the authoritative partition after merge.
**Verified by:** `packages/network/network-plugin-partition/src/merge/merge.spec-conformance.test.ts` (`NET-82`).
### NET-83 — Partition events are emitted on the bus
`network-plugin-partition` MUST emit `partition:detected` and `partition:healed` events on the `NetworkBus`.
**Verified by:** `packages/network/network-plugin-partition/src/detector/detector.spec-conformance.test.ts` (`NET-83`).
### NET-84 — Circuit breaker opens after failures
`network-plugin-circuit-breaker` MUST transition from `CLOSED` to `OPEN` after `failureThreshold` consecutive failures.
**Verified by:** `packages/network/network-plugin-circuit-breaker/src/breaker/breaker.spec-conformance.test.ts` (`NET-84`).
### NET-85 — Circuit breaker transitions to half-open
`network-plugin-circuit-breaker` MUST transition from `OPEN` to `HALF_OPEN` after `openDurationMs`.
**Verified by:** `packages/network/network-plugin-circuit-breaker/src/breaker/breaker.spec-conformance.test.ts` (`NET-85`).
### NET-86 — Circuit breaker closes after successes
`network-plugin-circuit-breaker` MUST transition from `HALF_OPEN` to `CLOSED` after `successThreshold` consecutive successes.
**Verified by:** `packages/network/network-plugin-circuit-breaker/src/breaker/breaker.spec-conformance.test.ts` (`NET-86`).
### NET-87 — Open circuit breaker rejects immediately
`network-plugin-circuit-breaker` MUST reject all executions immediately when in `OPEN` state.
**Verified by:** `packages/network/network-plugin-circuit-breaker/src/breaker/breaker.spec-conformance.test.ts` (`NET-87`).
### NET-88 — `HalfOpenProbe` sends probes
`network-plugin-circuit-breaker` MUST send lightweight probe messages during `HALF_OPEN`.
**Verified by:** `packages/network/network-plugin-circuit-breaker/src/probe/probe.spec-conformance.test.ts` (`NET-88`).
### NET-89 — `CircuitBreakerRegistry` manages per-path breakers
`network-plugin-circuit-breaker` MUST manage per-path circuit breakers.
**Verified by:** `packages/network/network-plugin-circuit-breaker/src/registry/registry.spec-conformance.test.ts` (`NET-89`).
### NET-90 — Circuit breaker middleware wraps relay send
`network-plugin-circuit-breaker` MUST wrap `HostBackboneTransport.send()` and record success/failure.
**Verified by:** `packages/network/network-plugin-circuit-breaker/src/middleware/middleware.spec-conformance.test.ts` (`NET-90`).
### NET-91 — `BandwidthQuotaEnforcer` tracks quotas
`network-plugin-qos` MUST track per-mesh, per-peer, and per-relay bandwidth using a sliding window.
**Verified by:** `packages/network/network-plugin-qos/src/enforcer/enforcer.spec-conformance.test.ts` (`NET-91`).
### NET-92 — `MessagePriorityClassifier` assigns QoS classes
`network-plugin-qos` MUST assign `QoSClass` based on message type and size.
**Verified by:** `packages/network/network-plugin-qos/src/classifier/classifier.spec-conformance.test.ts` (`NET-92`).
### NET-93 — Control plane bypasses quota
`network-plugin-qos` MUST bypass quota checks for `CONTROL_PLANE` messages.
**Verified by:** `packages/network/network-plugin-qos/src/router/qos-router.spec-conformance.test.ts` (`NET-93`).
### NET-94 — Realtime messages drop on quota exceed
`network-plugin-qos` MUST drop `REALTIME` messages when mesh quota is exceeded.
**Verified by:** `packages/network/network-plugin-qos/src/router/qos-router.spec-conformance.test.ts` (`NET-94`).
### NET-95 — Reliable messages queue on quota exceed
`network-plugin-qos` MUST queue `RELIABLE` messages with timeout when mesh quota is exceeded.
**Verified by:** `packages/network/network-plugin-qos/src/router/qos-router.spec-conformance.test.ts` (`NET-95`).
### NET-96 — Bulk messages defer on quota exceed
`network-plugin-qos` MUST drop or defer `BULK` and `SCAVENGER` messages when mesh quota is exceeded.
**Verified by:** `packages/network/network-plugin-qos/src/router/qos-router.spec-conformance.test.ts` (`NET-96`).
### NET-97 — Relay traffic is throttled independently
`network-plugin-qos` MUST throttle cross-mesh relay traffic independently and drop `SCAVENGER` relay traffic first.
**Verified by:** `packages/network/network-plugin-qos/src/router/qos-router.spec-conformance.test.ts` (`NET-97`).
### NET-98 — `CongestionMonitor` emits alerts
`network-plugin-qos` MUST emit `qos:congestion` events when utilization exceeds `alertThreshold` for `sustainedPeriodMs`.
**Verified by:** `packages/network/network-plugin-qos/src/monitor/congestion-monitor.spec-conformance.test.ts` (`NET-98`).
### NET-99 — `MigrationCoordinator` executes 8-step flow
`network-plugin-migration` MUST execute the 8-step migration flow: request, accept, snapshot, transfer, tunnel, cutover, drain, complete.
**Verified by:** `packages/network/network-plugin-migration/src/coordinator/coordinator.spec-conformance.test.ts` (`NET-99`).
### NET-100 — `StateTransferProtocol` serializes state
`network-plugin-migration` MUST serialize peer registry, topology, and session state using `@suaveplan/bitpacker`.
**Verified by:** `packages/network/network-plugin-migration/src/state-transfer/state-transfer.spec-conformance.test.ts` (`NET-100`).
### NET-101 — `ForwardingTunnel` buffers messages
`network-plugin-migration` MUST buffer messages for the migrating peer and forward them to the new host.
**Verified by:** `packages/network/network-plugin-migration/src/tunnel/forwarding-tunnel.spec-conformance.test.ts` (`NET-101`).
### NET-102 — `ForwardingTunnel` drops on overflow
`network-plugin-migration` MUST drop oldest messages when the forwarding buffer exceeds `maxBufferedMessages`.
**Verified by:** `packages/network/network-plugin-migration/src/tunnel/forwarding-tunnel.spec-conformance.test.ts` (`NET-102`).
### NET-103 — `ForwardingTunnel` closes after timeout
`network-plugin-migration` MUST close the forwarding tunnel after `drainTimeoutMs` regardless of buffer state.
**Verified by:** `packages/network/network-plugin-migration/src/tunnel/forwarding-tunnel.spec-conformance.test.ts` (`NET-103`).
### NET-104 — Urgent migrations skip tunnel
`network-plugin-migration` MUST skip the forwarding tunnel for `urgent` migrations and accept message loss.
**Verified by:** `packages/network/network-plugin-migration/src/coordinator/coordinator.spec-conformance.test.ts` (`NET-104`).
### NET-105 — Migration completion is broadcast
`network-plugin-migration` MUST emit `migration:completed` on both the source and target mesh buses.
**Verified by:** `packages/network/network-plugin-migration/src/coordinator/coordinator.spec-conformance.test.ts` (`NET-105`).
### NET-106 — `MeshMembershipVerifier` validates auth token
`network-plugin-auth` MUST validate `authToken` via `@suaveplan/auth` before allowing mesh join.
**Verified by:** `packages/network/network-plugin-auth/src/verifier/verifier.spec-conformance.test.ts` (`NET-106`).
### NET-107 — Public key matches auth identity
`network-plugin-auth` MUST check that the peer's `publicKey` matches the identity in `authToken`.
**Verified by:** `packages/network/network-plugin-auth/src/verifier/verifier.spec-conformance.test.ts` (`NET-107`).
### NET-108 — `CapabilityTokenIssuer` issues signed tokens
`network-plugin-auth` MUST issue tokens signed by the server that constrain tier and capabilities.
**Verified by:** `packages/network/network-plugin-auth/src/issuer/issuer.spec-conformance.test.ts` (`NET-108`).
### NET-109 — `CapabilityToken` contains required fields
`network-plugin-auth` MUST include `peerId`, `meshId`, `tier`, `capabilities`, `issuedAt`, `expiresAt`, and `serverSignature` in every `CapabilityToken`.
**Verified by:** `packages/network/network-plugin-auth/src/issuer/issuer.spec-conformance.test.ts` (`NET-109`).
### NET-110 — `CrossMeshTrustValidator` rejects untrusted relay
`network-plugin-auth` MUST reject relay between meshes unless a trust relationship is established.
**Verified by:** `packages/network/network-plugin-auth/src/trust/trust-validator.spec-conformance.test.ts` (`NET-110`).
### NET-111 — Trust decisions are cached
`network-plugin-auth` MUST cache trust decisions with a configurable TTL.
**Verified by:** `packages/network/network-plugin-auth/src/trust/trust-validator.spec-conformance.test.ts` (`NET-111`).
### NET-112 — Tier 0 hosts verify trust tokens
`network-plugin-auth` MUST verify `MeshTrustToken` before accepting backbone connections.
**Verified by:** `packages/network/network-plugin-auth/src/trust/trust-validator.spec-conformance.test.ts` (`NET-112`).
### NET-113 — `NetworkNode` supports bootstrap and cold start
`network-core` MUST provide `NetworkNode.bootstrap(options)` with `BootstrapOptions` supporting `mode`, `initialPeers`, `bootstrapServers`, `connectionConcurrency`, `discoveryTimeout`, and `prioritizeLocalNetwork`.
**Verified by:** `packages/network/network/src/bootstrap/bootstrap.spec-conformance.test.ts` (`NET-113`).
### NET-114 — Connection pre-warming is available
`network-core` MUST support `ConnectionPreWarmer` that pre-opens transport connections to known peers before they are needed.
**Verified by:** `packages/network/network/src/bootstrap/bootstrap.spec-conformance.test.ts` (`NET-114`).
### NET-115 — Transport Plugin Development Kit provides conformance tests
`network-core` MUST provide `TransportTester` with `testBasicFunctionality()`, `testReliability()`, `testBackpressure()`, and `testReconnection()` for third-party transport plugin validation.
**Verified by:** `packages/network/network/src/pdk/transport-tester.spec-conformance.test.ts` (`NET-115`).
### NET-116 — Plugin registry supports runtime discovery
`network-core` MUST provide `PluginRegistry` with `register()`, `unregister()`, `has()`, `get()`, and `list()`. `PluginDiscovery` MUST support `findPluginsByCapability()`.
**Verified by:** `packages/network/network/src/plugin/registry.spec-conformance.test.ts` (`NET-116`).
### NET-117 — `PingManager` is transport-agnostic
`network-transport-webrtc` MUST provide `PingManager` that sends correlated echo frames over any active transport (not just WebRTC), measures RTT with EMA smoothing, calculates jitter, detects packet loss, and maintains a composite reliability score.
**Verified by:** `packages/network/network-transport-webrtc/src/ping/ping.spec-conformance.test.ts` (`NET-117`).
### NET-118 — `HostSelector` uses historical trust-based scoring
`network-plugin-governance` MUST provide `HostSelector` that evaluates candidates using weighted multi-factor evaluation (latency, stability, uptime, capabilities, trust score) and enforces stability thresholds.
**Verified by:** `packages/network/network-plugin-governance/src/selector/selector.spec-conformance.test.ts` (`NET-118`).
### NET-119 — `HostHistory` tracks hosting sessions
`network-plugin-governance` MUST provide `HostHistory` that maintains an append-only record of successful/unsuccessful hosting sessions per peer, consumed by `HostSelector` to compute trust scores.
**Verified by:** `packages/network/network-plugin-governance/src/history/history.spec-conformance.test.ts` (`NET-119`).
### NET-120 — `MessagePool` reduces allocations on constrained devices
`network-plugin-topology` MUST provide `MessagePool` that reuses message objects for constrained device profiles.
**Verified by:** `packages/network/network-plugin-topology/src/resource/resource.spec-conformance.test.ts` (`NET-120`).
### NET-121 — Zero-copy message passing is supported where possible
`network-plugin-topology` MUST support `ZeroCopyPassing` that passes message references instead of copying bytes between transport and protocol layers when the platform allows.
**Verified by:** `packages/network/network-plugin-topology/src/resource/resource.spec-conformance.test.ts` (`NET-121`).
### NET-122 — Battery-aware mode reduces power consumption
`network-plugin-topology` MUST implement `BatteryAwareMode` that reduces heartbeat frequency, defers non-urgent reorganizations, and lowers transport retry aggression when battery level is low.
**Verified by:** `packages/network/network-plugin-topology/src/resource/resource.spec-conformance.test.ts` (`NET-122`).
### NET-123 — `BatteryAwareScheduler` conserves power in transport manager
`network-plugin-transport-manager` MUST provide `BatteryAwareScheduler` that reduces transport keepalive frequency and prefers lower-power transports when running on battery-powered devices.
**Verified by:** `packages/network/network-plugin-transport-manager/src/scheduler/battery.spec-conformance.test.ts` (`NET-123`).
### NET-124 — `BandwidthConservator` reduces aggregate bandwidth usage
`network-plugin-transport-manager` MUST provide `BandwidthConservator` that coalesces small messages, increases batching intervals, and pauses redundant CRITICAL sends when conservation mode is active.
**Verified by:** `packages/network/network-plugin-transport-manager/src/scheduler/bandwidth.spec-conformance.test.ts` (`NET-124`).
### NET-125 — `FastPathDispatcher` bypasses full pipeline for common messages
`network-plugin-protocol` MUST provide `FastPathDispatcher` — a zero-copy fast path for common message types (heartbeat, ping, registry delta) that bypasses the full pipeline when no encryption/compression is required.
**Verified by:** `packages/network/network-plugin-protocol/src/fast-path/fast-path.spec-conformance.test.ts` (`NET-125`).