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,196 @@
# OpenSpec Change: enterprise-message-bridge
- **Change ID**: enterprise-message-bridge
- **Package**: `@suaveplan/message-bridge`
- **Category**: universal
- **Target path**: `universal/social/message-bridge`
- **Status**: IN PROGRESS
- **Date**: 2026-04-24
- **Reference spec**: `/mnt/s/web/suaveplan/enterprise/message-bridge.md`
---
## Summary
Deliver `@suaveplan/message-bridge` on the genesis branch from scratch at enterprise quality. The package provides a unified multi-platform message bridge: a `MessageBridge` facade that normalizes inbound and outbound messages across registered `MessageAdapter` implementations (Slack, Discord, Telegram, iMessage, SMS), a canonical `UnifiedMessage` model, platform-agnostic routing rules, deduplication of inbound messages by message ID, delivery confirmation tracking, and an event bus for inbound message propagation. This package defines the `MessageAdapter` interface that all platform adapters implement. Genesis adds structured errors, Zod schemas, OTel instrumentation, `AbortSignal` cancellation, and property-based tests.
---
## Current-state audit (genesis)
The package does not exist on genesis yet — this is a fresh build.
---
## Available workspace deps on genesis
| Package | Role |
|---|---|
| `@suaveplan/error` (`workspace:^`) | `MessageBridgeError`; `MSG_BRIDGE.*` error codes |
| `@suaveplan/types` (`workspace:^`) | `LoggerLike`, `Clock`, `EventBusLike` |
| `@suaveplan/events` (`workspace:^`) | Inbound message event propagation |
| `@suaveplan/retry` (`workspace:^`) | Retry on send failures |
| `zod` (`catalog:forms`) | Schema validation |
| `@opentelemetry/api` (`catalog:observability`) | Spans + counters |
Dev deps: `vitest`, `@vitest/coverage-istanbul`, `fast-check` (all `catalog:testing`).
---
## Public API surface
### `UnifiedMessage`
```ts
interface UnifiedMessage {
id: string
platform: string // 'slack' | 'discord' | 'telegram' | 'imessage' | 'sms' | custom
channelId?: string
threadId?: string
senderId: string
senderName?: string
text: string
attachments: MessageAttachment[]
timestamp: Date
raw?: unknown // original platform payload
metadata: Record<string, unknown>
}
interface MessageAttachment {
id: string
type: 'image' | 'video' | 'audio' | 'file'
url?: string
content?: Uint8Array
mimeType?: string
filename?: string
size?: number
}
interface SendOptions {
platform: string
to: string // channel ID, chat ID, or phone number depending on platform
threadId?: string
attachments?: MessageAttachment[]
signal?: AbortSignal
}
```
### `MessageAdapter` interface
```ts
interface MessageAdapter {
readonly platform: string
start(signal?: AbortSignal): AsyncGenerator<UnifiedMessage>
send(to: string, text: string, options?: AdapterSendOptions): Promise<void>
isAvailable(): boolean
}
```
### `MessageBridge`
```ts
class MessageBridge {
constructor(options?: MessageBridgeOptions)
register(adapter: MessageAdapter): void
unregister(platform: string): void
send(options: SendOptions, text: string): Promise<void>
start(signal?: AbortSignal): void // starts all registered adapters
stop(): void
on(event: 'message', handler: (msg: UnifiedMessage) => void): () => void
platforms(): string[]
}
interface MessageBridgeOptions {
bus?: EventBusLike
logger?: LoggerLike
clock?: Clock
deduplicationWindowMs?: number // default 60_000; 0 disables
}
```
### Routing
```ts
interface RouteRule {
fromPlatform?: string
toPlatform: string
transform?: (msg: UnifiedMessage) => Partial<UnifiedMessage>
}
function applyRoutes(bridge: MessageBridge, rules: RouteRule[]): () => void
```
### Error codes
```ts
type MessageBridgeErrorCode =
| 'MSG_BRIDGE_ADAPTER_NOT_FOUND'
| 'MSG_BRIDGE_SEND_FAILED'
| 'MSG_BRIDGE_ADAPTER_UNAVAILABLE'
| 'MSG_BRIDGE_DEDUP_CONFLICT'
| 'MSG_BRIDGE_ROUTE_FAILED'
| 'MSG_BRIDGE_ABORTED'
```
---
## Genesis additions
1. **`MessageBridgeError`** extends `SuaveplanError` with six stable codes.
2. **Zod schemas** for `UnifiedMessage`, `MessageAttachment`, `SendOptions`, `RouteRule`, `MessageBridgeOptions`.
3. **Message deduplication** — a sliding-window set keyed by `${platform}:${id}` prevents duplicate inbound delivery when multiple adapters or polling overlaps produce the same message.
4. **Routing rules** — `applyRoutes` wires cross-platform message forwarding (e.g. Slack → Telegram bridge) with optional transform.
5. **OTel instrumentation** — counter `message_bridge.inbound_total` with attribute `message_bridge.platform`; counter `message_bridge.outbound_total`; histogram `message_bridge.send_duration_ms`.
6. **Property-based tests** — deduplication window correctly excludes duplicates and expires old entries for arbitrary sequences of message IDs.
---
## File layout
```text
universal/social/message-bridge/
package.json
tsconfig.json
vitest.config.ts
src/
index.ts
error-codes.ts
constants/
index.ts
types/
common.ts
common.md
core/
message-bridge/
message-bridge.ts
message-bridge.md
message-bridge.types.ts
message-bridge.test.ts
index.ts
deduplicator/
deduplicator.ts
deduplicator.md
deduplicator.test.ts
index.ts
routing/
route-rules/
route-rules.ts
route-rules.md
route-rules.test.ts
index.ts
__benchmarks__/
message-bridge.bench.ts
tests/
integration.test.ts
property.test.ts
```
---
## Impact
**Downstream consumers**: `@suaveplan/imessage-adapter`, `@suaveplan/slack-client` (adapter registration), `@suaveplan/discord-client`, `@suaveplan/telegram-client`, `@suaveplan/sms-providers`.
**Note**: This package must be built before the adapter packages since it defines the `MessageAdapter` interface they implement.
**Workspace dep prerequisites**: `@suaveplan/error`, `@suaveplan/types`, `@suaveplan/events`, `@suaveplan/retry`.

View File

@@ -0,0 +1,69 @@
# Tasks: enterprise-message-bridge
**Change ID**: enterprise-message-bridge
**Package**: `@suaveplan/message-bridge`
**Target path**: `universal/social/message-bridge`
**Prerequisite packages on Verdaccio**: `@suaveplan/error`, `@suaveplan/types`, `@suaveplan/events`, `@suaveplan/retry`
---
## 0. Pre-flight (non-negotiable)
- [ ] 0.1 Confirm clean working tree (`git status` reports nothing) and no in-flight worktrees with uncommitted work (`git worktree list` then `git status` in each)
- [ ] 0.2 If any worktrees exist under `.claude/worktrees/`, account for each one: still-active agent, work-pending-merge, or stale-and-prune. Stale worktrees MUST be removed (`git worktree remove`) before opening a new one — code that has been lost twice on main is the failure mode this guards against.
- [ ] 0.3 Confirm the package set in `MANIFEST.md` matches `find packages -maxdepth 3 -name package.json` count. Drift here means a prior change archived without regenerating the manifest.
## 1. Scaffold
- [ ] Create `universal/social/message-bridge/` with `src/`, `tests/`, `src/__benchmarks__/` and all feature subdirectories per the layout in `proposal.md`.
- [ ] Write `package.json` at version `0.1.0` with `"type": "module"`, `"sideEffects": false`, correct `exports` map, `dependencies`, and `devDependencies`.
- [ ] Write `tsconfig.json` extending `@suaveplan/typescript-config/library.json`.
- [ ] Write `vitest.config.ts` using `createTestConfig()` from `@suaveplan/testing/config`.
- [ ] Add `lint`, `typecheck`, `test`, `test:coverage`, `build`, `docs:check` scripts.
---
## 2. Types + errors
- [ ] `src/types/common.ts` — `UnifiedMessage`, `MessageAttachment`, `SendOptions`, `AdapterSendOptions`, `MessageAdapter` (interface), `MessageBridgeOptions`, `RouteRule`.
- [ ] `src/types/common.md` (≥200 words, both examples, API reference).
- [ ] `src/error-codes.ts` — `MessageBridgeErrorCode` (6 codes), metadata, register, eager call.
- [ ] `src/types/schemas.ts` + `schemas.md` — Zod schemas.
---
## 3. Core modules
- [ ] **`src/core/deduplicator/`** — `Deduplicator(windowMs)`: tracks a `Map<key, expiresAt>`; `isDuplicate(key)` returns true if key was seen within window and not expired; `record(key)` adds entry with `now + windowMs` expiry; `purge()` removes expired entries (called on each `isDuplicate` check). Tests: first occurrence not duplicate, second within window is duplicate, after window expires not duplicate, `windowMs=0` always not duplicate.
- [ ] **`src/routing/route-rules/`** — `applyRoutes(bridge, rules)`: subscribes to `bridge.on('message', ...)`, matches rules by `fromPlatform`, calls `bridge.send` to `toPlatform` with optional transform; returns unsubscribe function. Tests: message from matching platform is forwarded, non-matching platform skipped, transform applied, unsubscribe stops forwarding.
- [ ] **`src/core/message-bridge/`** — `MessageBridge`: `register(adapter)` adds to internal map; `start(signal)` iterates registered adapters and starts each (async generators) funnelled into a shared queue; on inbound message, checks `Deduplicator`; if new, emits via `bus` and calls `on('message')` listeners. `send(options, text)` looks up adapter by `options.platform`, calls `adapter.send`. Tests: register/unregister, send to registered platform, send to unknown platform throws, deduplication suppresses second occurrence, start/stop via AbortSignal, route forwarding end-to-end with stub adapters.
---
## 4. OTel instrumentation
- [ ] Counter `message_bridge.inbound_total` with attribute `message_bridge.platform` on each new inbound message.
- [ ] Counter `message_bridge.outbound_total` with same attribute on each send.
- [ ] Histogram `message_bridge.send_duration_ms`.
---
## 5. Property-based tests (`tests/property.test.ts`)
- [ ] Deduplication: for arbitrary sequences of `(key, timestamp)` pairs with a fixed window, the deduplicator correctly reports duplicate status consistent with the window boundary.
---
## 6. Benchmarks (`src/__benchmarks__/message-bridge.bench.ts`)
- [ ] `Deduplicator.isDuplicate` for 100 000 unique keys.
---
## 7. Docs + verify
- [ ] One `.md` per implementation file (≥200 words, both examples, API reference). Root `README.md`.
- [ ] `bunx turbo lint typecheck test --filter=@suaveplan/message-bridge` — green.
- [ ] `bunx turbo test:coverage --filter=@suaveplan/message-bridge` — 100%.
- [ ] `bun scripts/publish.ts --package @suaveplan/message-bridge`.
- [ ] Archive: `openspec/archive/2026-04-24-enterprise-message-bridge/`.