# @cognitum/gate
[](https://www.npmjs.com/package/@cognitum/gate)
[](https://bundlephobia.com/package/@cognitum/gate)
[](https://github.com/ruvnet/ruvector/blob/main/LICENSE)
[](https://www.typescriptlang.org/)
[](https://webassembly.org/)
**Browser and Node.js coherence gate for AI agent safety**
---
## Introduction
The Cognitum Gate is a high-performance WASM-based coherence verification system designed to bring real-time safety guarantees to AI agent operations. Whether you're building autonomous agents in the browser or orchestrating complex workflows on Node.js, this package provides cryptographically-verifiable permit/defer/deny decisions in microseconds. Every action your agent considers passes through the gate, receiving an immediate verdict backed by witness receipts that create an immutable audit trail.
Unlike traditional attention mechanisms that weight tokens by relevance, the coherence gate transforms attention into a permission system. Actions are not merely ranked by probability or popularity---they are explicitly permitted or denied based on configurable safety thresholds, context windows, and agent-specific policies. This paradigm shift means your agents operate within well-defined boundaries, preventing runaway behaviors while maintaining the responsiveness users expect from modern AI applications.
**Attention becomes a permission system, not a popularity contest.**
The gate achieves sub-millisecond latency through a 256-tile WASM fabric that distributes verification across Web Workers (browser) or worker threads (Node.js). Each tile maintains its own coherence state, enabling horizontal scaling without sacrificing consistency. The result is a system that can handle thousands of permission checks per second while generating cryptographic receipts suitable for compliance, debugging, and post-hoc analysis.
**Created by [ruv.io](https://ruv.io) and [RuVector](https://github.com/ruvnet/ruvector)**
---
## Quick Start
```bash
npm install @cognitum/gate
```
```typescript
import { CognitumGate } from '@cognitum/gate';
// Initialize the gate with default configuration
const gate = await CognitumGate.init({
tileCount: 16,
coherenceThreshold: 0.85,
maxContextTokens: 8192,
});
// Request permission for an agent action
const result = await gate.permitAction({
agentId: 'agent-001',
action: 'file_write',
target: '/app/config.json',
context: { reason: 'Update user preferences' },
});
if (result.verdict === 'permit') {
console.log('Action permitted:', result.token);
// Proceed with the action...
// Get the witness receipt for audit trail
const receipt = await gate.getReceipt(result.token);
console.log('Receipt hash:', receipt.witnessHash);
} else if (result.verdict === 'defer') {
console.log('Action deferred, retry after:', result.deferMs, 'ms');
} else {
console.log('Action denied:', result.reason);
}
```
---
Architecture
### How WASM Tiles Work in Browser/Node
The coherence gate operates through a distributed tile architecture where each tile is an independent WASM module responsible for a subset of coherence verification. This design enables:
- **Parallel Processing**: Multiple tiles process requests concurrently
- **Fault Isolation**: A failing tile doesn't crash the entire system
- **Horizontal Scaling**: Add more tiles as load increases
```
+---------------------------------------------------------------+
| CognitumGate API |
+---------------------------------------------------------------+
| Tile Coordinator |
+-------+-------+-------+-------+-------+-------+-------+-------+
|Tile 0 |Tile 1 |Tile 2 |Tile 3 | ... |Tile N |Arbiter|Witness|
| WASM | WASM | WASM | WASM | | WASM | Tile | Store |
+-------+-------+-------+-------+-------+-------+-------+-------+
| | | | | |
+-------+-------+-------+---------------+-------+
SharedArrayBuffer / MessageChannel
```
### Web Worker Distribution (Browser)
In browser environments, each tile runs in its own Web Worker for true parallelism:
```typescript
// The gate automatically spawns workers
const gate = await CognitumGate.init({
tileCount: navigator.hardwareConcurrency || 4,
workerUrl: '/cognitum-worker.js', // Optional custom worker
});
// Check active workers
console.log('Active tiles:', gate.getStats().activeTiles);
```
Workers communicate through `SharedArrayBuffer` when available (requires cross-origin isolation) or fall back to `MessageChannel` for broader compatibility.
### Worker Threads (Node.js)
On Node.js, the gate uses `worker_threads` for true parallelism:
```typescript
import { CognitumGate } from '@cognitum/gate/node';
import os from 'os';
const gate = await CognitumGate.init({
tileCount: os.cpus().length,
threadPoolSize: 4,
});
```
### SharedArrayBuffer for Tile Communication
When cross-origin isolation is enabled, tiles share memory through `SharedArrayBuffer`:
```typescript
// Check if SharedArrayBuffer is available
if (gate.supportsSharedMemory) {
console.log('Using SharedArrayBuffer for zero-copy communication');
} else {
console.log('Falling back to structured clone');
}
```
Required headers for cross-origin isolation:
```
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
```
### Memory Layout Per Tile
Each tile maintains approximately 41KB of state:
```typescript
interface TileState {
graphShard: Uint8Array; // ~32KB - compact neighborhood graph
featureWindow: Float32Array; // ~8KB - rolling normality scores
coherence: number; // f32 - local coherence score
boundaryEdges: Uint32Array; // 8 edges - local boundary candidates
eAccumulator: number; // f64 - local E-value accumulator
tick: bigint; // u64 - tick counter
}
```
---
Technical Deep Dive
### WASM Module Loading
The gate loads WASM modules asynchronously with streaming compilation when supported:
```typescript
import { loadWasmModule } from '@cognitum/gate/wasm';
// Manual WASM loading (usually handled automatically)
const wasmModule = await loadWasmModule({
url: '/cognitum-gate.wasm',
streaming: true, // Use WebAssembly.instantiateStreaming
cache: 'persistent', // Cache in IndexedDB
});
```
The WASM binary is approximately 180KB gzipped and includes:
- Coherence scoring algorithms
- Cryptographic witness generation (BLAKE3/SHA-256)
- Tile state management
- Receipt serialization
### Memory Management (LinearMemory)
Each WASM tile operates with its own `WebAssembly.Memory` instance:
```typescript
interface TileMemoryConfig {
initial: number; // Initial pages (64KB each)
maximum: number; // Maximum pages
shared: boolean; // Use SharedArrayBuffer
}
const gate = await CognitumGate.init({
tileMemory: {
initial: 16, // 1MB initial
maximum: 256, // 16MB maximum
shared: true, // Enable shared memory
},
});
// Monitor memory usage
const stats = gate.getStats();
console.log('Memory per tile:', stats.memoryPerTile);
```
Memory lifecycle:
1. **Allocation**: Memory allocated on tile creation
2. **Growth**: Automatic growth up to `maximum` pages
3. **Compaction**: Periodic compaction during idle periods
4. **Release**: Memory freed when gate is destroyed
### TypeScript Type Definitions
Full type coverage for all APIs:
```typescript
// Core types
type Verdict = 'permit' | 'defer' | 'deny';
interface PermitRequest {
agentId: string;
action: string;
target?: string;
context?: Record;
priority?: 'low' | 'normal' | 'high' | 'critical';
timeoutMs?: number;
}
interface PermitResult {
verdict: Verdict;
token: string; // Unique permit token
coherenceScore: number; // 0.0 - 1.0
tileId: number; // Processing tile
latencyUs: number; // Processing time in microseconds
reason?: string; // Human-readable reason for defer/deny
deferMs?: number; // Suggested retry delay
}
interface WitnessReceipt {
token: string;
witnessHash: string; // BLAKE3/SHA-256 hash
timestamp: number; // Unix timestamp (ms)
agentId: string;
action: string;
verdict: Verdict;
coherenceScore: number;
parentHash?: string; // Chain to previous receipt
signature?: Uint8Array; // Optional Ed25519 signature
outcome?: ActionOutcome; // Recorded outcome
}
```
### Performance Characteristics
| Operation | Latency (p50) | Latency (p99) | Throughput |
|-----------|---------------|---------------|------------|
| `permitAction` | 45 us | 120 us | 22,000 req/s |
| `getReceipt` | 12 us | 35 us | 80,000 req/s |
| `batchPermit` (100) | 2.1 ms | 4.5 ms | 47,000 req/s |
| Tile cold start | 8 ms | 15 ms | N/A |
Benchmarked on:
- Browser: Chrome 120, M2 MacBook Pro
- Node.js: v20.10, 8-core AMD EPYC
---