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.

View File

@@ -0,0 +1,86 @@
# Tasks — network-core
> Blocked on: none. Consumes existing genesis packages only.
## 1. Scaffold
- [x] 1.1 `packages/network/network/` with `package.json` (`@suaveplan/network@0.0.0`), `tsconfig.json`, `vitest.config.ts`, `README.md`.
- [x] 1.2 Workspace deps: `@suaveplan/error`, `@suaveplan/types`, `@suaveplan/events`, `@suaveplan/streams`, `@suaveplan/bitpacker`, `@suaveplan/serialize`, `@opentelemetry/api`, `zod`.
- [x] 1.3 No external runtime deps beyond catalog.
## 2. Types and contracts
- [x] 2.1 `src/types/plugin.types.ts` — `NetworkPlugin`, `PluginContext`, `PluginLifecycle`.
- [x] 2.2 `src/types/envelope.types.ts` — `MessageEnvelope`, `EnvelopeHeaders`, Zod schema.
- [x] 2.3 `src/types/transport.types.ts` — `Transport`, `TransportConfig`, `PeerInfo`.
- [x] 2.4 `src/types/node.types.ts` — `NetworkNodeConfig`, `NetworkNodeState`.
- [x] 2.5 `src/error-codes.ts` — `defineCodes("NET", [...])` frozen registry.
## 3. Plugin manager
- [x] 3.1 `src/plugin/plugin-manager.ts` — `use(plugin)`, `installAll()`, `startAll()`, `stopAll()`, `disposeAll()` in correct order.
- [x] 3.2 Lifecycle dedup: installing the same plugin twice is a no-op.
## 4. Network bus
- [x] 4.1 `src/bus/network-bus.ts` — wraps `@suaveplan/events` with topic-based routing, bounded queue, interceptors.
- [x] 4.2 Topics: `peer:joined`, `peer:left`, `peer:latency`, `election:vote`, `election:completed`, `failover:triggered`, `message:received`, `topology:changed`.
## 5. Message router
- [x] 5.1 `src/router/message-router.ts` — `route(envelope)` resolves `targetId` to transport, `broadcast()` fans out to all transports.
- [x] 5.2 `broadcast` skips the sender.
## 6. Network node
- [x] 6.1 `src/node/network-node.ts` — `use(plugin)`, `start()`, `stop()`, `send()`, `broadcast()`, `on(event)`.
- [x] 6.2 Envelope validation via Zod before routing.
- [x] 6.3 Idempotent `start()` / `stop()`.
## 7. Spec
- [x] 7.1 `openspec/specs/network/spec.md` — requirements `NET-01` through `NET-05` and `NET-12`.
## 8. Conformance tests
- [x] 8.1 `src/plugin/plugin.spec-conformance.test.ts` — lifecycle order, duplicate install no-op.
- [x] 8.2 `src/node/node.spec-conformance.test.ts` — send, broadcast, envelope validation, plugin wiring.
- [x] 8.3 `src/bus/bus.spec-conformance.test.ts` — FIFO, backpressure, interceptor.
- [x] 8.4 `src/router/router.spec-conformance.test.ts` — unicast, broadcast, skip-sender.
- [x] 8.5 `src/envelope/envelope.spec-conformance.test.ts` — Zod accept/reject.
- [x] 8.6 `src/error-codes.spec-conformance.test.ts` — frozen registry.
- [x] 8.7 `tests/dep-graph.test.ts` — no cycles, tree-shake clean.
## 10. API versioning
- [x] 10.1 `src/versioning/version-info.ts` — `VersionInfo`, semantic versioning, compatibility check.
- [x] 10.2 `src/versioning/version-manager.ts` — `VersionManager`, migration paths, stability classification.
- [x] 10.3 `src/versioning/version-negotiator.ts` — `VersionNegotiator`, exchanges versions during handshake.
- [x] 10.4 Version embedded in `MessageEnvelope` headers.
## 11. Network timestamps
- [x] 11.1 `src/timing/network-timestamp.ts` — `NetworkTimestamp`, ISO8601/unix/custom, timezone, precision.
- [x] 11.2 `src/timing/clock.ts` — `Clock` interface, injectable for testing.
- [x] 11.3 `src/timing/timestamp-comparer.ts` — `TimestampComparer`, `isAfter`, `isBefore`, `compare`.
## 12. Standardized event constants
- [x] 12.1 `src/events/network-events.ts` — `NetworkEvents`, frozen enum of all standard bus topics.
- [x] 12.2 Node lifecycle, message, hierarchy, plugin, system topics.
## 13. Spec
- [x] 13.1 Update `openspec/specs/network/spec.md` with `NET-53`, `NET-54`, `NET-55`.
## 14. Conformance tests
- [x] 14.1 `src/versioning/versioning.spec-conformance.test.ts` — compatibility, negotiation, rejection.
- [x] 14.2 `src/timing/timing.spec-conformance.test.ts` — formats, timezone, precision, comparison.
- [x] 14.3 `src/events/events.spec-conformance.test.ts` — constants, no typos, coverage.
## 15. Verify
- [x] 15.1 `bunx turbo lint typecheck test --filter=@suaveplan/network` green.
- [x] 15.2 `bunx turbo test:coverage --filter=@suaveplan/network` 100/100/100/100.
- [x] 15.3 `bun scripts/openspec-conformance.ts @suaveplan/network` PASS.