npm package: @principal-ai/control-tower-core
Description: Centralized, runtime-agnostic library for real-time collaboration and synchronization
Author: Principal AI
Latest version: 0.6.2

# Control Tower Core

Centralized, runtime-agnostic library for real-time collaboration and synchronization.

## Installation

```bash
npm install @principal-ai/control-tower-core
```

## Quick Start

```typescript
import {
  ServerBuilder,
  DefaultRoomManager,
  DefaultLockManager,
  MockTransportAdapter
} from '@principal-ai/control-tower-core';

// Create a server with default implementations
const server = new ServerBuilder()
  .withTransport(new MockTransportAdapter())
  .withRoomManager(new DefaultRoomManager())
  .withLockManager(new DefaultLockManager())
  .build();

await server.start(8080);
console.log('Server started on port 8080');
```

## Features

- **Room Management**: Create, join, and manage collaborative rooms
- **Lock Management**: File/directory locking with queue support
- **Real-time Events**: Event broadcasting and history
- **Extensible**: Abstract interfaces for custom implementations
- **TypeScript**: Full type safety with generated declarations
- **Experimental APIs**: Opt-in broadcast features for rapid prototyping (see [Experimental Features](#experimental-features))

## API Reference

### ServerBuilder

The main entry point for creating servers:

```typescript
const server = new ServerBuilder()
  .withTransport(transportAdapter)
  .withRoomManager(roomManager)
  .withLockManager(lockManager)
  .withAuth(authAdapter) // optional
  .withStorage(storageAdapter) // optional
  .withDefaultRoomConfig({
    maxUsers: 50,
    maxHistory: 100,
    permissions: ['read', 'write']
  })
  .build();
```

### Default Implementations

- `DefaultRoomManager`: In-memory room management
- `DefaultLockManager`: In-memory locking with queue support
- `MockTransportAdapter`: Mock transport for testing

### Custom Implementations

Implement the abstract interfaces to create custom adapters:

```typescript
import { RoomManager } from '@principal-ai/control-tower-core';

class CustomRoomManager extends RoomManager {
  async createRoom(id: string, config: RoomConfig): Promise<Room> {
    // Your implementation
  }
  // ... implement other methods
}
```

## Experimental Features

⚠️ **For Development Use Only**

Control Tower Core provides experimental broadcast APIs for rapid prototyping and internal tooling. These APIs allow broadcasting messages beyond room boundaries.

### Enabling Experimental Features

```typescript
import { ServerBuilder } from '@principal-ai/control-tower-core';

const server = new ServerBuilder()
  .withTransport(transportAdapter)
  .withRoomManager(roomManager)
  .withLockManager(lockManager)
  .withExperimentalFeatures({
    enableBroadcast: true  // Enable experimental broadcast APIs
  })
  .build();
```

### Using Experimental Broadcast

```typescript
// Broadcast to all connected clients
await server.experimental.broadcast({
  type: 'system:announcement',
  data: { message: 'Server maintenance in 5 minutes' }
});

// Broadcast to authenticated users only
await server.experimental.broadcastAuthenticated({
  type: 'presence:user_online',
  data: { userId: 'alice' }
});

// Broadcast with custom filtering
await server.experimental.broadcastWhere(
  (client) => client.userId.startsWith('admin_'),
  { type: 'admin:alert', data: { ... } }
);

// Send to specific users
await server.experimental.sendToUsers(
  ['user1', 'user2'],
  { type: 'notification:mention', data: { ... } }
);
```

### Important Notes

- **Experimental APIs may change or be removed** without major version bumps
- **Not recommended for production** applications
- Use for prototyping, then submit a [feature request](docs/FEATURE_REQUEST_TEMPLATE.md) to graduate to stable API
- See [full documentation](docs/EXPERIMENTAL_BROADCAST.md) for details

## Testing

Control Tower Core provides comprehensive test utilities for building reliable applications.

### MockTransportAdapter

The `MockTransportAdapter` provides test helpers for simulating client-server interactions:

```typescript
import { MockTransportAdapter } from '@principal-ai/control-tower-core';

const transport = new MockTransportAdapter();

// Simulate a client connection
await transport.simulateConnection('client-id', {
  authenticated: true,
  userId: 'user-123',
  metadata: { deviceType: 'desktop' }
});

// Simulate client messages
await transport.simulateClientMessage('client-id', 'join_room', {
  roomId: 'room-1'
});

// Simulate incoming server messages (for client tests)
transport.simulateIncomingMessage({
  type: 'room_joined',
  payload: { roomId: 'room-1', state: { ... } }
});

// Track connection attempts (useful for reconnection tests)
const attempts = transport.getConnectionAttempts();
transport.resetConnectionAttempts();

// Get messages sent to specific clients
const messages = transport.getSentMessages('client-id');
```

### Running Tests

```bash
# Run all tests
bun test

# Run specific test file
bun test tests/BaseServer.test.ts

# Run with coverage
bun test --coverage
```

## Documentation

- [Experimental Broadcast APIs](docs/EXPERIMENTAL_BROADCAST.md)
- [Feature Request Template](docs/FEATURE_REQUEST_TEMPLATE.md)
- [Architecture Design](DESIGN.md)
- [Changelog](CHANGELOG.md)

## License

MIT