Initial Commit

This commit is contained in:
2026-05-27 23:29:53 +01:00
commit fbc70f96e6
10000 changed files with 1102152 additions and 0 deletions

View File

@@ -0,0 +1,124 @@
# OpenSpec Change: network-plugin-topology
- **Change ID**: network-plugin-topology
- **Package**: `@suaveplan/network-plugin-topology` (new)
- **Status**: PROPOSED
- **Type**: new-package
- **Date**: 2026-04-29
## Why
The tiered network needs explicit topology management: promoting/demoting nodes across tiers, tracking group membership, and assigning nodes to latency groups. The genesis `fsm` and `events` packages provide primitives. This plugin implements the `HierarchicalTopologyImpl` (Tier 0 Host, Tier 1 SubHost, Tier 2 Leaf) and `LatencyAssigner` consumed by the `network-webrtc` mesh.
## What changes
- **ADDED**: `TopologyPlugin` class implementing `NetworkPlugin`.
- **ADDED**: `HierarchicalTopologyImpl` — manages `Tier 0 → Tier 1 → Tier 2` hierarchy, promotion/demotion.
- **ADDED**: `LatencyAssigner` — assigns peers to latency groups based on RTT, rebalances periodically.
- **ADDED**: `GroupManager` — tracks group membership, handles join/leave.
- **ADDED**: `NETWORK_TOPO_CODES` — frozen error registry.
## Out of scope
- Global topology view across many groups → deferred to federation layer.
- Persistent topology state → future `network-plugin-topology-persistence`.
## Source mapping
This change derives from `../suaveplan/enterprise/network-topology.md` and `../suaveplan/packages/universal/network-topology/`.
| Requirement | Source lines | Notes |
|---|---|---|
| Tier 0 Host, Tier 1 SubHost, Tier 2 Leaf | `network-topology/README.md` §HierarchicalTopologyImpl | verbatim |
| Promotion/demotion | `network-topology/README.md` §HierarchicalTopologyImpl | verbatim |
| Latency-based group assignment | `network-topology/README.md` §LatencyAssigner | verbatim |
| Rebalancing | `network-topology/README.md` §LatencyAssigner | verbatim |
### Requirements with no source line
| Requirement | Justification |
|---|---|
| `TopologyPlugin` implements `NetworkPlugin` | Required to plug into `NetworkNode` |
| Consumes `election:result` from bus | Loose coupling to governance plugin |
| Consumes `peer:latency` from bus | Loose coupling to webrtc plugin |
## Verification approach
- `src/topology/topology.spec-conformance.test.ts` — pins tier assignment, promotion, demotion.
- `src/latency/latency.spec-conformance.test.ts` — pins group assignment, rebalancing, thresholds.
- `src/group/group.spec-conformance.test.ts` — pins join/leave, membership tracking.
- `tests/dep-graph.test.ts` — pins no direct import of webrtc or governance packages.
## Enhancement: Resource-Constrained Adaptation
**Source**: `docs/old-network-planning/ADAPT_3.md` §Resource Management, `PHASE_5.md` §Performance Metrics, `PLAN_ENHANCED_PHASE_5.md`
The topology must adapt to device capabilities:
- `DeviceProfiler` — classifies peers into profiles: `CONSTRAINED`, `STANDARD`, `POWERFUL`, `SERVER`.
- `ResourceBalancer` — monitors CPU, memory, bandwidth utilization. Detects imbalances and recommends promotions/demotions.
- `AdaptiveTierDepth` — adjusts maximum tier depth based on network size (logarithmic scaling) and available high-resource nodes.
- `MessagePool` — reduces allocations for constrained devices via object pooling.
- `ZeroCopyPassing` — where possible, passes message references instead of copying bytes between transport and protocol layers.
- `BatteryAwareMode` — when `DeviceProfile` is `CONSTRAINED` and battery level is low, reduces heartbeat frequency, defers non-urgent reorganizations, and lowers transport retry aggression.
- `BandwidthConservation` — `moderate` and `aggressive` modes that reduce gossip frequency, compress registry deltas more aggressively, and batch lower-priority messages.
## Enhancement: Tier Partition Handler
**Source**: `docs/old-network-planning/MODULAR_IMPLEMENTATION_PHASE_5.md` §TierPartitionHandler, `TIER_PARTITION_HANDLER_TEST_FIX_PLAN.md`
- `PartitionDetector` — builds connectivity map, detects isolated subgraphs via multi-factor analysis (heartbeat, path verification, consensus).
- `PartitionManager` — allows partitions to function autonomously with local hierarchies. Tracks partition size, composition, resource distribution.
- `PartitionRecovery` — controlled reconnection with prioritized sequence. Merges hierarchies using primary partition selection (size-based, performance-based, or hybrid).
- `StateReconciliationOnMerge` — reconciles diverged states after partition healing.
## Enhancement: Geographic-Aware Routing
**Source**: `docs/old-network-planning/PLAN_ENHANCED_PHASE_5.md` §Geographic Optimization
- `GeoLocator` — tracks peer geographic region (inferred from latency or explicit metadata).
- `RegionalClustering` — preferentially groups peers from same region.
- `GeoLatencyOptimizer` — minimizes cross-region latency in parent-child assignments.
## Enhancement: Circuit Breaker & Hysteresis
**Source**: `docs/old-network-planning/PHASE_5.md` §Cascading Failure Prevention
- `ReorganizationCircuitBreaker` — pauses reorganizations during cascading failures:
- Time-based: suspend for configurable period.
- Count-based: limit reorganizations per time window.
- Impact-based: evaluate disruption before proceeding.
- `PromotionHysteresis` — cooldown periods after level changes to prevent oscillation.
- `StabilityThreshold` — minimum stability period before promotion eligibility.
## Enhancement: Empty Tier Handling
**Source**: `docs/old-network-planning/PHASE_5.md` §Empty Tier Handling
- `EmptyTierDetector` — monitors node counts per tier.
- `EmptyTierRemover` — removes empty tiers, reconnects adjacent levels, renumbers affected tiers.
- `TierRenumberer` — updates level numbers and configurations consistently.
## Enhancement: Tiered Routing Rules
**Gap**: The topology plugin manages tiers but there is no specification for how messages flow between tiers. This enhancement adds explicit routing rules.
**Routing rules**:
1. **Leaf → Leaf (same mesh)**: Route through nearest common ancestor (Tier 1 or Tier 0). Direct leaf-to-leaf sends are disallowed unless the topology is flat (no Tier 1 sub-hosts).
2. **Leaf → Host**: Direct if connected, else via Tier 1 sub-host.
3. **Host → Leaf**: Forward through Tier 1 sub-hosts. Tier 0 does not flood all peers directly; it delegates to sub-hosts.
4. **Broadcast**: Fan out from Tier 0 → Tier 1 → Tier 2 (tree broadcast, not mesh flood).
5. **Cross-tier credential delegation**: Cross-tier operations require explicit credential delegation from a higher tier (enforced by `network-plugin-crypto-messages`).
**Components**:
- `TieredRouter` — implements the routing rules above. Consumes topology state and produces `nextHop` decisions.
- `BroadcastTree` — builds a spanning tree from Tier 0 for mesh-wide broadcasts. Rebuilt on every `topology:changed` event.
- `RouteCache` — caches frequently used `(sourceTier, targetTier, targetId) → nextHop` mappings. Invalidated on topology changes.
**Integration with partition plugin**: When `network-plugin-partition` detects a split, `TieredRouter` falls back to partition-local routing. When partitions heal, the broadcast tree is rebuilt.
## Migration impact
None — additive only.