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,128 @@
# OpenSpec Change: network-core
- **Change ID**: network-core
- **Package**: `@suaveplan/network` (new)
- **Status**: PROPOSED
- **Type**: new-package
- **Date**: 2026-04-29
## Why
Genesis has production-grade crypto (`crypto-cipher`), streams (`streams` with real AEAD + compression + framing), bitpacker, storage, and event-bus primitives — but no networking layer to compose them. The suaveplan `network` package exists in `../suaveplan/packages/universal/network` with the right architecture (plugin-based, hierarchical topology, governance, failover) but its transform layer contains documented stubs (fake encryption, fake compression, unimplemented ping). Rather than port the whole monolith, we extract the **core plugin architecture and abstractions** into a genesis-native package, then add real plugin packages that wire to genesis primitives.
## What changes
- **ADDED**: `NetworkPlugin` interface — universal contract for all network extensions (`name`, `install(node)`, `start()`, `stop()`, `dispose?()`).
- **ADDED**: `NetworkNode` class — single entry-point that owns plugin lifecycle, message routing, and envelope validation.
- **ADDED**: `MessageEnvelope` schema — Zod-validated envelope with `id`, `type`, `senderId`, `targetId`, `payload`, `timestamp`, `headers`.
- **ADDED**: `Transport` interface — abstract contract for transport plugins (`connect`, `disconnect`, `send`, `onMessage`, `getConnectedPeers`).
- **ADDED**: `NetworkBus` — typed pub/sub broker wrapping `@suaveplan/events` with bounded-queue backpressure and interceptors.
- **ADDED**: `PluginManager` — installs plugins in registration order, starts them, stops them in reverse, disposes in reverse.
- **ADDED**: `MessageRouter` — routes envelopes to transports (unicast by `targetId`, broadcast to all peers, fan-out across transports).
- **ADDED**: `NETWORK_CODES` — frozen error registry (`defineCodes("NET", [...])`).
## Out of scope
- Concrete transport implementations → `network-plugin-webrtc`, `network-plugin-websocket` (deferred).
- Governance/election logic → `network-plugin-governance`.
- Peer registry / delta sync → `network-plugin-registry`.
- Heartbeat / failover FSM → `network-plugin-failover`.
- Tiered topology management → `network-plugin-topology`.
- Signaling server → deferred; plugins accept a pluggable `SignalingClient` interface.
## Source mapping
This change derives from `../suaveplan/enterprise/network.md` and `../suaveplan/packages/universal/network/src/core/engine/`, `src/contracts/`, `src/plugin/`.
| Requirement | Source lines | Notes |
|---|---|---|
| Plugin lifecycle (install → start → stop → dispose) | `network/src/plugin/manager/manager.md` | verbatim contract |
| NetworkNode unified API | `network/src/core/network/unified-node/network-node.md` | reworded; genesis uses `NetworkBus` instead of direct EventEmitter |
| MessageEnvelope shape | `network/src/contracts/core.types.md` | extended with Zod schema |
| Transport abstraction | `network/src/contracts/transport.types.md` | verbatim |
### Requirements with no source line
| Requirement | Justification |
|---|---|
| Zod validation on every envelope | Genesis cross-cutting requirement per AGENTS.md |
| `NetworkBus` wraps `@suaveplan/events` | Genesis already has a typed event bus; no need to invent a second one |
| `PluginManager` reverse-order stop/dispose | Defensive programming not explicitly in source docs |
## Verification approach
- `src/plugin/plugin.spec-conformance.test.ts` — pins `NetworkPlugin` interface shape and lifecycle order.
- `src/node/node.spec-conformance.test.ts` — pins `NetworkNode` public API, envelope validation, and plugin wiring.
- `src/bus/bus.spec-conformance.test.ts` — pins `NetworkBus` FIFO, backpressure, interceptor behavior.
- `src/router/router.spec-conformance.test.ts` — pins unicast, broadcast, and transport fan-out.
- `src/envelope/envelope.spec-conformance.test.ts` — pins Zod schema rejections and valid envelope acceptance.
- `tests/dep-graph.test.ts` — pins no circular deps, no external runtime deps beyond workspace.
## Enhancement: API Versioning Infrastructure
**Source**: `docs/old-network-planning/ADAPT_2.md` §API Versioning, `PHASE_0_IMPLEMENTATION_PLAN.md` §Version Info
The core needs versioning from the start to ensure interoperability as the mesh evolves:
- `VersionInfo` — semantic versioning with `major.minor.patch`. `isCompatibleWith(other)` checks same major and minor >= required.
- `VersionManager` — tracks current library version, provides migration paths between versions, stability classification (`experimental`, `stable`, `deprecated`).
- `VersionNegotiator` — exchanges versions during peer handshake. Rejects incompatible peers.
- Version is embedded in `MessageEnvelope` headers.
## Enhancement: Network Timestamps
**Source**: `docs/old-network-planning/ADAPT_4.md` §Timestamp Handling
Cross-node operations require reliable time handling:
- `NetworkTimestamp` — standardized timestamp with multiple formats: ISO8601, unix, custom. Timezone support with adjustment. Precision levels: millisecond, microsecond, nanosecond.
- `Clock` interface — injectable clock for testing. Default uses `performance.now()` or `Date.now()`.
- `TimestampComparer` — `isAfter()`, `isBefore()`, `compare()` with timezone awareness.
## Enhancement: Standardized Event Constants
**Source**: `docs/old-network-planning/PHASE_0_IMPLEMENTATION_PLAN.md` §Event Constants
The bus uses string topics. Standardized constants prevent typos and enable IDE autocomplete:
- `NetworkEvents` — frozen enum of all standard bus topics:
- Node lifecycle: `node:created`, `node:connected`, `node:disconnected`, `node:updated`, `node:removed`
- Message: `message:sent`, `message:received`, `message:routed`, `message:dropped`
- Hierarchy: `hierarchy:changed`, `hierarchy:parent-changed`, `hierarchy:child-added`, `hierarchy:child-removed`, `hierarchy:level-changed`
- Plugin: `plugin:registered`, `plugin:unregistered`
- System: `system:error`, `system:warning`, `system:info`
## Enhancement: Bootstrap and Cold Start
**Source**: `docs/old-network-planning/ADAPT_3.md` §Optimize Cold Start Procedure
The core must support fast initialization for first-time mesh joiners:
- `BootstrapOptions` — configurable bootstrap: `mode: 'aggressive' | 'balanced' | 'conservative'`, `initialPeers`, `bootstrapServers`, `connectionConcurrency`, `discoveryTimeout`, `prioritizeLocalNetwork`.
- `NetworkNode.bootstrap(options)` — fast-path initialization that progressively discovers peers and forms hierarchy without blocking on full mesh state.
- `ConnectionPreWarmer` — pre-opens transport connections to known peers before they are needed.
- `StatePreLoader` — hydrates cached topology and registry state from previous session to skip full discovery.
## Enhancement: Transport Plugin Development Kit (PDK)
**Source**: `docs/old-network-planning/ADAPT_2.md` §Enhance Transport Plugin Framework
Third-party transport plugins need a standardized development kit:
- `BaseTransportPlugin` abstract class — implements common transport lifecycle (connect, disconnect, send, health tracking).
- `TransportCapabilities` interface — `supportsDirect`, `supportsRelay`, `supportsBroadcast`, `maxMessageSize`, `reliabilityLevel`.
- `TransportTester` — conformance test suite that any transport plugin can run: `testBasicFunctionality()`, `testReliability()`, `testBackpressure()`, `testReconnection()`.
- `TransportBenchmark` — performance benchmark harness: throughput, latency, memory usage.
- Plugin discovery — `PluginRegistry` supports runtime registration and lookup by capability.
## Enhancement: Plugin Registry and Discovery
**Source**: `docs/old-network-planning/ADAPT_5.md` §Develop Plugin Ecosystem Support
- `PluginRegistry` — runtime registry of installed plugins. `register(plugin)`, `unregister(id)`, `has(id)`, `get(id)`, `list()`.
- `PluginDiscovery` — scans for available plugins by capability query: `findPluginsByCapability('state-sync')`.
- `PluginCapabilityValidator` — verifies that a plugin's declared capabilities match its actual exports.
## Migration impact
None — additive only. No consumers in genesis reference `@suaveplan/network` yet.