{"_id":"@aigentic/cognitum-gate-kernel","_rev":"3-ac5504dc3d85b2b2ab5857e0891cb35a","name":"@aigentic/cognitum-gate-kernel","dist-tags":{"latest":"0.1.1"},"versions":{"0.1.0":{"name":"@aigentic/cognitum-gate-kernel","version":"0.1.0","keywords":["ai","agent","safety","coherence","wasm","webassembly","permission","audit","claude","llm"],"author":{"name":"RuVector","email":"hello@ruv.io"},"license":"(MIT OR Apache-2.0)","_id":"@aigentic/cognitum-gate-kernel@0.1.0","maintainers":[{"name":"aigentic","email":"engineering@aigentic.net"}],"homepage":"https://github.com/ruvnet/ruvector/tree/main/packages/cognitum-gate-wasm","bugs":{"url":"https://github.com/ruvnet/ruvector/issues"},"dist":{"shasum":"3aef825e603f73939974b62dc3187bac01d5b0da","tarball":"https://registry.npmjs.org/@aigentic/cognitum-gate-kernel/-/cognitum-gate-kernel-0.1.0.tgz","fileCount":2,"integrity":"sha512-t2ggaUjE/kc7lqaPozHg/2yWmC+AWEe221TRb4ugR9oedMRkPxGmzt577tS9dVfqavb/zi9PMDpapaONMA3Egw==","signatures":[{"sig":"MEUCIFE2K8xK/wUuUPLI1PHbrUaHAnImvKUZV7g43c6GKWFuAiEA/6eSoB0+erCv8ufjvnnQdSJ67R9veoa7szrWv6xiPCc=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":35370},"main":"./dist/cjs/index.js","types":"./dist/types/index.d.ts","module":"./dist/esm/index.js","engines":{"node":">=16.0.0"},"exports":{".":{"types":"./dist/types/index.d.ts","import":"./dist/esm/index.js","require":"./dist/cjs/index.js"},"./sw":{"types":"./dist/types/sw.d.ts","import":"./dist/esm/sw.js"},"./node":{"types":"./dist/types/node.d.ts","import":"./dist/esm/node.js","require":"./dist/cjs/node.js"},"./wasm":{"types":"./dist/types/wasm.d.ts","import":"./dist/esm/wasm.js","require":"./dist/cjs/wasm.js"},"./experimental":{"types":"./dist/types/experimental.d.ts","import":"./dist/esm/experimental.js"}},"gitHead":"06426cbc6e70f09762e996a98517b0b1fd1c7c4e","scripts":{"lint":"eslint src --ext .ts,.tsx","test":"vitest run","build":"npm run build:wasm && npm run build:ts","clean":"rm -rf dist wasm","build:ts":"tsup","lint:fix":"eslint src --ext .ts,.tsx --fix","typecheck":"tsc --noEmit","build:wasm":"wasm-pack build ../cognitum-gate-kernel --target web --out-dir ../packages/cognitum-gate-wasm/wasm","test:watch":"vitest","build:types":"tsc --emitDeclarationOnly","test:browser":"vitest run --environment jsdom","test:coverage":"vitest run --coverage","prepublishOnly":"npm run clean && npm run build && npm run test"},"_npmUser":{"name":"aigentic","email":"engineering@aigentic.net"},"repository":{"url":"git+https://github.com/ruvnet/ruvector.git","type":"git","directory":"packages/cognitum-gate-wasm"},"_npmVersion":"11.12.0","description":"Browser and Node.js coherence gate for AI agent safety - real-time permit/defer/deny decisions in microseconds","directories":{},"sideEffects":false,"_nodeVersion":"22.22.1","dependencies":{"@noble/hashes":"^1.3.3"},"_hasShrinkwrap":false,"devDependencies":{"tsup":"^8.0.0","jsdom":"^23.0.0","eslint":"^8.55.0","vitest":"^1.0.0","typescript":"^5.3.0","@types/node":"^20.10.0","@vitest/coverage-v8":"^1.0.0","@typescript-eslint/parser":"^6.13.0","@typescript-eslint/eslint-plugin":"^6.13.0"},"peerDependencies":{"claude-flow":">=2.0.0"},"peerDependenciesMeta":{"claude-flow":{"optional":true}},"_npmOperationalInternal":{"tmp":"tmp/cognitum-gate-kernel_0.1.0_1779091116779_0.2746129337093379","host":"s3://npm-registry-packages-npm-production"}},"0.1.1":{"name":"@aigentic/cognitum-gate-kernel","version":"0.1.1","keywords":["ai","agent","safety","coherence","wasm","webassembly","permission","audit","claude","llm"],"author":{"name":"RuVector","email":"hello@ruv.io"},"license":"(MIT OR Apache-2.0)","_id":"@aigentic/cognitum-gate-kernel@0.1.1","maintainers":[{"name":"aigentic","email":"engineering@aigentic.net"}],"homepage":"https://github.com/ruvnet/ruvector/tree/main/packages/cognitum-gate-wasm","bugs":{"url":"https://github.com/ruvnet/ruvector/issues"},"dist":{"shasum":"7802ba35803e875fb8e2cbd419a38dcb20cdf5e3","tarball":"https://registry.npmjs.org/@aigentic/cognitum-gate-kernel/-/cognitum-gate-kernel-0.1.1.tgz","fileCount":2,"integrity":"sha512-SqqayTm4R9bOCh5HCg0BJbd8lWDTmUVEL2QrYCSW8QBVX7XK65YjUA9fkikslmyQUJHEY/Yh8VtijJaOEvOnhw==","signatures":[{"sig":"MEUCIQDg6flNN/beEFE9OwcXhXbXRHgKzdA2bbDj6OyTjarJagIgRZ1mQiPECxH7MFs28J4lhUODKvJxgjEkCD9bWEkQan0=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":35370},"main":"./dist/cjs/index.js","types":"./dist/types/index.d.ts","module":"./dist/esm/index.js","engines":{"node":">=16.0.0"},"exports":{".":{"types":"./dist/types/index.d.ts","import":"./dist/esm/index.js","require":"./dist/cjs/index.js"},"./sw":{"types":"./dist/types/sw.d.ts","import":"./dist/esm/sw.js"},"./node":{"types":"./dist/types/node.d.ts","import":"./dist/esm/node.js","require":"./dist/cjs/node.js"},"./wasm":{"types":"./dist/types/wasm.d.ts","import":"./dist/esm/wasm.js","require":"./dist/cjs/wasm.js"},"./experimental":{"types":"./dist/types/experimental.d.ts","import":"./dist/esm/experimental.js"}},"gitHead":"06426cbc6e70f09762e996a98517b0b1fd1c7c4e","scripts":{"lint":"eslint src --ext .ts,.tsx","test":"vitest run","build":"npm run build:wasm && npm run build:ts","clean":"rm -rf dist wasm","build:ts":"tsup","lint:fix":"eslint src --ext .ts,.tsx --fix","typecheck":"tsc --noEmit","build:wasm":"wasm-pack build ../cognitum-gate-kernel --target web --out-dir ../packages/cognitum-gate-wasm/wasm","test:watch":"vitest","build:types":"tsc --emitDeclarationOnly","test:browser":"vitest run --environment jsdom","test:coverage":"vitest run --coverage","prepublishOnly":"npm run clean && npm run build && npm run test"},"_npmUser":{"name":"aigentic","email":"engineering@aigentic.net"},"repository":{"url":"git+https://github.com/ruvnet/ruvector.git","type":"git","directory":"packages/cognitum-gate-wasm"},"_npmVersion":"11.12.0","description":"Browser and Node.js coherence gate for AI agent safety - real-time permit/defer/deny decisions in microseconds","directories":{},"sideEffects":false,"_nodeVersion":"22.22.1","dependencies":{"@noble/hashes":"^1.3.3"},"_hasShrinkwrap":false,"devDependencies":{"tsup":"^8.0.0","jsdom":"^23.0.0","eslint":"^8.55.0","vitest":"^1.0.0","typescript":"^5.3.0","@types/node":"^20.10.0","@vitest/coverage-v8":"^1.0.0","@typescript-eslint/parser":"^6.13.0","@typescript-eslint/eslint-plugin":"^6.13.0"},"peerDependencies":{"claude-flow":">=2.0.0"},"peerDependenciesMeta":{"claude-flow":{"optional":true}},"_npmOperationalInternal":{"tmp":"tmp/cognitum-gate-kernel_0.1.1_1779092815527_0.004641726248400868","host":"s3://npm-registry-packages-npm-production"}}},"time":{"created":"2026-05-18T07:58:36.664Z","modified":"2026-09-13T15:30:27.954Z","0.1.0":"2026-05-18T07:58:36.933Z","0.1.1":"2026-05-18T08:26:55.661Z"},"bugs":{"url":"https://github.com/ruvnet/ruvector/issues"},"author":{"name":"RuVector","email":"hello@ruv.io"},"license":"(MIT OR Apache-2.0)","homepage":"https://github.com/ruvnet/ruvector/tree/main/packages/cognitum-gate-wasm","keywords":["ai","agent","safety","coherence","wasm","webassembly","permission","audit","claude","llm"],"repository":{"url":"git+https://github.com/ruvnet/ruvector.git","type":"git","directory":"packages/cognitum-gate-wasm"},"description":"Browser and Node.js coherence gate for AI agent safety - real-time permit/defer/deny decisions in microseconds","maintainers":[{"email":"engineering@aigentic.net","name":"aiggy"}],"readme":"# @cognitum/gate\n\n[![npm version](https://img.shields.io/npm/v/@cognitum/gate.svg)](https://www.npmjs.com/package/@cognitum/gate)\n[![bundle size](https://img.shields.io/bundlephobia/minzip/@cognitum/gate)](https://bundlephobia.com/package/@cognitum/gate)\n[![license](https://img.shields.io/npm/l/@cognitum/gate.svg)](https://github.com/ruvnet/ruvector/blob/main/LICENSE)\n[![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue.svg)](https://www.typescriptlang.org/)\n[![WASM](https://img.shields.io/badge/WebAssembly-1.0-654FF0.svg)](https://webassembly.org/)\n\n**Browser and Node.js coherence gate for AI agent safety**\n\n---\n\n## Introduction\n\nThe 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.\n\nUnlike 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.\n\n**Attention becomes a permission system, not a popularity contest.**\n\nThe 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.\n\n**Created by [ruv.io](https://ruv.io) and [RuVector](https://github.com/ruvnet/ruvector)**\n\n---\n\n## Quick Start\n\n```bash\nnpm install @cognitum/gate\n```\n\n```typescript\nimport { CognitumGate } from '@cognitum/gate';\n\n// Initialize the gate with default configuration\nconst gate = await CognitumGate.init({\n  tileCount: 16,\n  coherenceThreshold: 0.85,\n  maxContextTokens: 8192,\n});\n\n// Request permission for an agent action\nconst result = await gate.permitAction({\n  agentId: 'agent-001',\n  action: 'file_write',\n  target: '/app/config.json',\n  context: { reason: 'Update user preferences' },\n});\n\nif (result.verdict === 'permit') {\n  console.log('Action permitted:', result.token);\n  // Proceed with the action...\n\n  // Get the witness receipt for audit trail\n  const receipt = await gate.getReceipt(result.token);\n  console.log('Receipt hash:', receipt.witnessHash);\n} else if (result.verdict === 'defer') {\n  console.log('Action deferred, retry after:', result.deferMs, 'ms');\n} else {\n  console.log('Action denied:', result.reason);\n}\n```\n\n---\n\n<details>\n<summary><h2>Architecture</h2></summary>\n\n### How WASM Tiles Work in Browser/Node\n\nThe 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:\n\n- **Parallel Processing**: Multiple tiles process requests concurrently\n- **Fault Isolation**: A failing tile doesn't crash the entire system\n- **Horizontal Scaling**: Add more tiles as load increases\n\n```\n+---------------------------------------------------------------+\n|                      CognitumGate API                         |\n+---------------------------------------------------------------+\n|                     Tile Coordinator                          |\n+-------+-------+-------+-------+-------+-------+-------+-------+\n|Tile 0 |Tile 1 |Tile 2 |Tile 3 |  ...  |Tile N |Arbiter|Witness|\n| WASM  | WASM  | WASM  | WASM  |       | WASM  | Tile  | Store |\n+-------+-------+-------+-------+-------+-------+-------+-------+\n    |       |       |       |               |       |\n    +-------+-------+-------+---------------+-------+\n              SharedArrayBuffer / MessageChannel\n```\n\n### Web Worker Distribution (Browser)\n\nIn browser environments, each tile runs in its own Web Worker for true parallelism:\n\n```typescript\n// The gate automatically spawns workers\nconst gate = await CognitumGate.init({\n  tileCount: navigator.hardwareConcurrency || 4,\n  workerUrl: '/cognitum-worker.js', // Optional custom worker\n});\n\n// Check active workers\nconsole.log('Active tiles:', gate.getStats().activeTiles);\n```\n\nWorkers communicate through `SharedArrayBuffer` when available (requires cross-origin isolation) or fall back to `MessageChannel` for broader compatibility.\n\n### Worker Threads (Node.js)\n\nOn Node.js, the gate uses `worker_threads` for true parallelism:\n\n```typescript\nimport { CognitumGate } from '@cognitum/gate/node';\nimport os from 'os';\n\nconst gate = await CognitumGate.init({\n  tileCount: os.cpus().length,\n  threadPoolSize: 4,\n});\n```\n\n### SharedArrayBuffer for Tile Communication\n\nWhen cross-origin isolation is enabled, tiles share memory through `SharedArrayBuffer`:\n\n```typescript\n// Check if SharedArrayBuffer is available\nif (gate.supportsSharedMemory) {\n  console.log('Using SharedArrayBuffer for zero-copy communication');\n} else {\n  console.log('Falling back to structured clone');\n}\n```\n\nRequired headers for cross-origin isolation:\n\n```\nCross-Origin-Opener-Policy: same-origin\nCross-Origin-Embedder-Policy: require-corp\n```\n\n### Memory Layout Per Tile\n\nEach tile maintains approximately 41KB of state:\n\n```typescript\ninterface TileState {\n  graphShard: Uint8Array;      // ~32KB - compact neighborhood graph\n  featureWindow: Float32Array; // ~8KB - rolling normality scores\n  coherence: number;           // f32 - local coherence score\n  boundaryEdges: Uint32Array;  // 8 edges - local boundary candidates\n  eAccumulator: number;        // f64 - local E-value accumulator\n  tick: bigint;                // u64 - tick counter\n}\n```\n\n</details>\n\n---\n\n<details>\n<summary><h2>Technical Deep Dive</h2></summary>\n\n### WASM Module Loading\n\nThe gate loads WASM modules asynchronously with streaming compilation when supported:\n\n```typescript\nimport { loadWasmModule } from '@cognitum/gate/wasm';\n\n// Manual WASM loading (usually handled automatically)\nconst wasmModule = await loadWasmModule({\n  url: '/cognitum-gate.wasm',\n  streaming: true, // Use WebAssembly.instantiateStreaming\n  cache: 'persistent', // Cache in IndexedDB\n});\n```\n\nThe WASM binary is approximately 180KB gzipped and includes:\n- Coherence scoring algorithms\n- Cryptographic witness generation (BLAKE3/SHA-256)\n- Tile state management\n- Receipt serialization\n\n### Memory Management (LinearMemory)\n\nEach WASM tile operates with its own `WebAssembly.Memory` instance:\n\n```typescript\ninterface TileMemoryConfig {\n  initial: number;  // Initial pages (64KB each)\n  maximum: number;  // Maximum pages\n  shared: boolean;  // Use SharedArrayBuffer\n}\n\nconst gate = await CognitumGate.init({\n  tileMemory: {\n    initial: 16,    // 1MB initial\n    maximum: 256,   // 16MB maximum\n    shared: true,   // Enable shared memory\n  },\n});\n\n// Monitor memory usage\nconst stats = gate.getStats();\nconsole.log('Memory per tile:', stats.memoryPerTile);\n```\n\nMemory lifecycle:\n1. **Allocation**: Memory allocated on tile creation\n2. **Growth**: Automatic growth up to `maximum` pages\n3. **Compaction**: Periodic compaction during idle periods\n4. **Release**: Memory freed when gate is destroyed\n\n### TypeScript Type Definitions\n\nFull type coverage for all APIs:\n\n```typescript\n// Core types\ntype Verdict = 'permit' | 'defer' | 'deny';\n\ninterface PermitRequest {\n  agentId: string;\n  action: string;\n  target?: string;\n  context?: Record<string, unknown>;\n  priority?: 'low' | 'normal' | 'high' | 'critical';\n  timeoutMs?: number;\n}\n\ninterface PermitResult {\n  verdict: Verdict;\n  token: string;           // Unique permit token\n  coherenceScore: number;  // 0.0 - 1.0\n  tileId: number;          // Processing tile\n  latencyUs: number;       // Processing time in microseconds\n  reason?: string;         // Human-readable reason for defer/deny\n  deferMs?: number;        // Suggested retry delay\n}\n\ninterface WitnessReceipt {\n  token: string;\n  witnessHash: string;     // BLAKE3/SHA-256 hash\n  timestamp: number;       // Unix timestamp (ms)\n  agentId: string;\n  action: string;\n  verdict: Verdict;\n  coherenceScore: number;\n  parentHash?: string;     // Chain to previous receipt\n  signature?: Uint8Array;  // Optional Ed25519 signature\n  outcome?: ActionOutcome; // Recorded outcome\n}\n```\n\n### Performance Characteristics\n\n| Operation | Latency (p50) | Latency (p99) | Throughput |\n|-----------|---------------|---------------|------------|\n| `permitAction` | 45 us | 120 us | 22,000 req/s |\n| `getReceipt` | 12 us | 35 us | 80,000 req/s |\n| `batchPermit` (100) | 2.1 ms | 4.5 ms | 47,000 req/s |\n| Tile cold start | 8 ms | 15 ms | N/A |\n\nBenchmarked on:\n- Browser: Chrome 120, M2 MacBook Pro\n- Node.js: v20.10, 8-core AMD EPYC\n\n</details>\n\n---\n\n<details>\n<summary><h2>Tutorials and Examples</h2></summary>\n\n### Example 1: React Integration\n\n```tsx\n// hooks/useCognitumGate.ts\nimport { useState, useEffect, useCallback } from 'react';\nimport { CognitumGate, GateConfig, PermitRequest, PermitResult } from '@cognitum/gate';\n\nexport function useCognitumGate(config?: Partial<GateConfig>) {\n  const [gate, setGate] = useState<CognitumGate | null>(null);\n  const [isReady, setIsReady] = useState(false);\n  const [error, setError] = useState<Error | null>(null);\n\n  useEffect(() => {\n    let mounted = true;\n    let gateInstance: CognitumGate | null = null;\n\n    CognitumGate.init(config).then((g) => {\n      if (mounted) {\n        gateInstance = g;\n        setGate(g);\n        setIsReady(true);\n      }\n    }).catch((e) => {\n      if (mounted) setError(e);\n    });\n\n    return () => {\n      mounted = false;\n      gateInstance?.destroy();\n    };\n  }, []);\n\n  const permit = useCallback(\n    async (action: string, target?: string): Promise<PermitResult | null> => {\n      if (!gate) return null;\n      return gate.permitAction({ agentId: 'react-app', action, target });\n    },\n    [gate]\n  );\n\n  return { gate, isReady, error, permit };\n}\n\n// components/AgentAction.tsx\nimport { useCognitumGate } from '../hooks/useCognitumGate';\n\nfunction AgentAction() {\n  const { permit, isReady } = useCognitumGate();\n  const [status, setStatus] = useState<string>('');\n\n  const handleAction = async () => {\n    const result = await permit('send_message', 'user-chat');\n\n    if (result?.verdict === 'permit') {\n      setStatus(`Permitted: ${result.token.slice(0, 16)}...`);\n      // Execute the action\n    } else if (result?.verdict === 'defer') {\n      setStatus(`Deferred: retry in ${result.deferMs}ms`);\n    } else {\n      setStatus(`Denied: ${result?.reason || 'Unknown'}`);\n    }\n  };\n\n  return (\n    <div>\n      <button onClick={handleAction} disabled={!isReady}>\n        {isReady ? 'Send Message' : 'Loading Gate...'}\n      </button>\n      {status && <p>{status}</p>}\n    </div>\n  );\n}\n```\n\n### Example 2: Express Middleware\n\n```typescript\n// middleware/cognitum.ts\nimport { Request, Response, NextFunction } from 'express';\nimport { CognitumGate, PermitResult } from '@cognitum/gate/node';\n\ndeclare global {\n  namespace Express {\n    interface Request {\n      permitToken?: string;\n      permitResult?: PermitResult;\n    }\n  }\n}\n\nlet gate: CognitumGate;\n\nexport async function initGateMiddleware() {\n  gate = await CognitumGate.init({\n    tileCount: 4,\n    coherenceThreshold: 0.9,\n  });\n  console.log('Cognitum Gate initialized');\n}\n\nexport function requirePermit(action: string) {\n  return async (req: Request, res: Response, next: NextFunction) => {\n    const result = await gate.permitAction({\n      agentId: req.headers['x-agent-id'] as string || 'anonymous',\n      action,\n      target: req.path,\n      context: {\n        method: req.method,\n        ip: req.ip,\n        userAgent: req.headers['user-agent'],\n      },\n    });\n\n    req.permitResult = result;\n\n    if (result.verdict === 'permit') {\n      req.permitToken = result.token;\n      res.setHeader('X-Permit-Token', result.token);\n      res.setHeader('X-Coherence-Score', result.coherenceScore.toFixed(4));\n      next();\n    } else if (result.verdict === 'defer') {\n      res.status(429).json({\n        error: 'Action deferred',\n        reason: result.reason,\n        retryAfter: result.deferMs,\n      });\n    } else {\n      res.status(403).json({\n        error: 'Action denied',\n        reason: result.reason,\n      });\n    }\n  };\n}\n\n// app.ts\nimport express from 'express';\nimport { initGateMiddleware, requirePermit } from './middleware/cognitum';\n\nconst app = express();\napp.use(express.json());\n\nasync function main() {\n  await initGateMiddleware();\n\n  app.post('/api/files', requirePermit('file_create'), (req, res) => {\n    // Handler only runs if permit granted\n    res.json({ success: true, token: req.permitToken });\n  });\n\n  app.delete('/api/files/:id', requirePermit('file_delete'), (req, res) => {\n    res.json({ deleted: req.params.id });\n  });\n\n  app.listen(3000, () => console.log('Server running on :3000'));\n}\n\nmain();\n```\n\n### Example 3: Deno/Bun Usage\n\n**Deno:**\n\n```typescript\nimport { CognitumGate } from 'npm:@cognitum/gate';\n\nconst gate = await CognitumGate.init({\n  tileCount: 4,\n  runtime: 'deno',\n});\n\nDeno.serve({ port: 8000 }, async (req) => {\n  const url = new URL(req.url);\n\n  const result = await gate.permitAction({\n    agentId: 'deno-server',\n    action: 'handle_request',\n    target: url.pathname,\n  });\n\n  if (result.verdict !== 'permit') {\n    return new Response(JSON.stringify({\n      error: 'Forbidden',\n      reason: result.reason\n    }), {\n      status: 403,\n      headers: { 'Content-Type': 'application/json' }\n    });\n  }\n\n  return new Response('Hello from Deno!', {\n    headers: {\n      'X-Permit-Token': result.token,\n      'X-Coherence-Score': result.coherenceScore.toString()\n    }\n  });\n});\n```\n\n**Bun:**\n\n```typescript\nimport { CognitumGate } from '@cognitum/gate';\n\nconst gate = await CognitumGate.init({\n  tileCount: Bun.cpuCount || 4,\n  runtime: 'bun',\n});\n\nBun.serve({\n  port: 3000,\n  async fetch(req) {\n    const result = await gate.permitAction({\n      agentId: 'bun-server',\n      action: 'handle_request',\n      target: new URL(req.url).pathname,\n    });\n\n    if (result.verdict === 'permit') {\n      return new Response('Hello from Bun!', {\n        headers: { 'X-Permit-Token': result.token }\n      });\n    }\n\n    return new Response('Forbidden', { status: 403 });\n  },\n});\n\nconsole.log('Bun server running on :3000');\n```\n\n### Example 4: Claude-Flow Agent Integration\n\n```typescript\nimport { CognitumGate, AgentPolicy } from '@cognitum/gate';\n\n// Define agent-specific policies\nconst policies: AgentPolicy[] = [\n  {\n    agentId: 'coder',\n    permissions: {\n      'file_read': { threshold: 0.7 },\n      'file_write': { threshold: 0.9, targets: ['src/**', 'tests/**'] },\n      'file_delete': { threshold: 0.99 },\n      'bash_execute': { threshold: 0.95, denyPatterns: ['rm -rf', 'sudo'] },\n    },\n  },\n  {\n    agentId: 'researcher',\n    permissions: {\n      'file_read': { threshold: 0.5 },\n      'web_fetch': { threshold: 0.6 },\n      'file_write': { verdict: 'deny' }, // Never permit writes\n    },\n  },\n];\n\nconst gate = await CognitumGate.init({\n  coherenceThreshold: 0.95, // Higher threshold for AI agents\n  maxContextTokens: 16384,\n  policies,\n});\n\n// Hook into Claude-Flow agent lifecycle\nasync function wrapToolUse(\n  agentId: string,\n  tool: { name: string },\n  args: Record<string, unknown>\n): Promise<{ permitToken: string }> {\n  const result = await gate.permitAction({\n    agentId,\n    action: `tool:${tool.name}`,\n    target: (args.path || args.target) as string,\n    context: { args },\n  });\n\n  if (result.verdict === 'deny') {\n    throw new Error(`Action denied: ${result.reason}`);\n  }\n\n  if (result.verdict === 'defer') {\n    // Wait and retry\n    await new Promise(r => setTimeout(r, result.deferMs || 1000));\n    return wrapToolUse(agentId, tool, args); // Retry\n  }\n\n  return { permitToken: result.token };\n}\n\n// After tool execution, record outcome\nasync function recordToolOutcome(\n  permitToken: string,\n  success: boolean,\n  error?: string\n): Promise<void> {\n  await gate.recordOutcome(permitToken, {\n    success,\n    error,\n    durationMs: Date.now() - performance.now(),\n  });\n}\n```\n\n</details>\n\n---\n\n<details>\n<summary><h2>Super Advanced Usage</h2></summary>\n\n### Custom Tile Topology\n\nCreate specialized tile arrangements for specific workloads:\n\n```typescript\nimport { CognitumGate, TileTopology } from '@cognitum/gate';\n\n// Ring topology: tiles pass state to neighbors\nconst ringTopology: TileTopology = {\n  type: 'ring',\n  tiles: 8,\n  connections: (tileId, total) => [(tileId + 1) % total],\n};\n\n// Hierarchical: fast local decisions, escalation for complex cases\nconst hierarchicalTopology: TileTopology = {\n  type: 'hierarchical',\n  levels: [\n    { tiles: 16, threshold: 0.7 },  // Fast layer\n    { tiles: 4, threshold: 0.85 },  // Review layer\n    { tiles: 1, threshold: 0.95 },  // Final arbiter\n  ],\n};\n\n// Mesh: full connectivity for consensus\nconst meshTopology: TileTopology = {\n  type: 'mesh',\n  tiles: 4,\n  quorum: 3, // 3 of 4 must agree\n};\n\nconst gate = await CognitumGate.init({\n  topology: hierarchicalTopology,\n});\n```\n\n### Streaming Decisions with AsyncIterator\n\nProcess high-volume action streams efficiently:\n\n```typescript\nimport { CognitumGate, PermitRequest, PermitResult } from '@cognitum/gate';\n\nconst gate = await CognitumGate.init({ tileCount: 16 });\n\n// Create an action stream\nasync function* actionStream(): AsyncGenerator<PermitRequest> {\n  const eventSource = new EventSource('/api/actions');\n\n  for await (const event of eventSource) {\n    const data = JSON.parse(event.data);\n    yield {\n      agentId: data.agentId,\n      action: data.type,\n      target: data.target,\n    };\n  }\n}\n\n// Process with backpressure handling\nconst results = gate.permitStream(actionStream(), {\n  concurrency: 100,\n  bufferSize: 1000,\n  onBackpressure: (pending) => {\n    console.warn(`Backpressure: ${pending} pending requests`);\n  },\n});\n\nfor await (const result of results) {\n  if (result.verdict === 'permit') {\n    await executeAction(result);\n  } else {\n    console.log(`${result.verdict}: ${result.reason}`);\n  }\n}\n```\n\n### Offline-First with IndexedDB Receipt Storage\n\nStore receipts locally for offline operation and later sync:\n\n```typescript\nimport { CognitumGate, IndexedDBReceiptStore } from '@cognitum/gate';\n\nconst receiptStore = new IndexedDBReceiptStore({\n  dbName: 'cognitum-receipts',\n  maxReceipts: 100000,\n  compactionThreshold: 0.8,\n});\n\nconst gate = await CognitumGate.init({\n  receiptStore,\n  offlineMode: {\n    enabled: true,\n    maxOfflineActions: 1000,\n    syncInterval: 30000, // Sync every 30s when online\n  },\n});\n\n// Check offline status\ngate.on('offline', () => {\n  console.log('Operating in offline mode');\n});\n\ngate.on('online', () => {\n  console.log('Back online, syncing receipts...');\n});\n\ngate.on('sync', (result) => {\n  console.log(`Synced ${result.receiptsUploaded} receipts`);\n});\n\n// Query local receipts\nconst recentDenials = await receiptStore.query({\n  agentId: 'my-agent',\n  since: Date.now() - 86400000, // Last 24 hours\n  verdict: 'deny',\n  limit: 100,\n});\n\nconsole.log(`Found ${recentDenials.length} denied actions in last 24h`);\n```\n\n### Service Worker Integration\n\nRun the gate in a Service Worker for cross-tab coherence:\n\n```typescript\n// sw.js - Service Worker\nimport { CognitumGate, PermitRequest } from '@cognitum/gate/sw';\n\nlet gate: CognitumGate;\n\nself.addEventListener('install', (event) => {\n  event.waitUntil(\n    CognitumGate.init({ tileCount: 4 }).then((g) => {\n      gate = g;\n      console.log('Gate initialized in Service Worker');\n    })\n  );\n});\n\nself.addEventListener('message', async (event) => {\n  if (event.data.type === 'permit') {\n    const result = await gate.permitAction(event.data.request as PermitRequest);\n    event.ports[0].postMessage(result);\n  }\n\n  if (event.data.type === 'get-stats') {\n    event.ports[0].postMessage(gate.getStats());\n  }\n});\n\n// client.js - Main thread\nclass ServiceWorkerGate {\n  private registration: ServiceWorkerRegistration;\n\n  constructor(registration: ServiceWorkerRegistration) {\n    this.registration = registration;\n  }\n\n  async permitAction(request: PermitRequest): Promise<PermitResult> {\n    const channel = new MessageChannel();\n\n    return new Promise((resolve) => {\n      channel.port1.onmessage = (e) => resolve(e.data);\n      this.registration.active?.postMessage(\n        { type: 'permit', request },\n        [channel.port2]\n      );\n    });\n  }\n\n  async getStats(): Promise<GateStats> {\n    const channel = new MessageChannel();\n\n    return new Promise((resolve) => {\n      channel.port1.onmessage = (e) => resolve(e.data);\n      this.registration.active?.postMessage(\n        { type: 'get-stats' },\n        [channel.port2]\n      );\n    });\n  }\n}\n\n// Usage\nconst reg = await navigator.serviceWorker.register('/sw.js');\nconst gate = new ServiceWorkerGate(reg);\nconst result = await gate.permitAction({ agentId: 'tab-1', action: 'fetch' });\n```\n\n### WebGPU Acceleration (Experimental)\n\nLeverage GPU compute for high-throughput scenarios:\n\n```typescript\nimport { CognitumGate, WebGPUAccelerator } from '@cognitum/gate/experimental';\n\n// Check WebGPU support\nif (!navigator.gpu) {\n  throw new Error('WebGPU not supported');\n}\n\nconst adapter = await navigator.gpu.requestAdapter();\nconst device = await adapter?.requestDevice();\n\nif (!device) {\n  throw new Error('Failed to get WebGPU device');\n}\n\nconst accelerator = new WebGPUAccelerator({\n  device,\n  workgroupSize: 256,\n  maxBatchSize: 4096,\n});\n\nconst gate = await CognitumGate.init({\n  accelerator,\n  batchingStrategy: 'gpu-optimized',\n});\n\n// Batch operations are automatically routed to GPU\nconst requests = Array.from({ length: 1000 }, (_, i) => ({\n  agentId: `agent-${i}`,\n  action: 'compute',\n  priority: 'normal' as const,\n}));\n\nconst results = await gate.batchPermit(requests);\n\nconst stats = {\n  permitted: results.filter(r => r.verdict === 'permit').length,\n  deferred: results.filter(r => r.verdict === 'defer').length,\n  denied: results.filter(r => r.verdict === 'deny').length,\n};\n\nconsole.log(`Processed ${results.length} requests on GPU:`, stats);\n```\n\n### Custom Coherence Scoring\n\nImplement domain-specific coherence algorithms:\n\n```typescript\nimport { CognitumGate, CoherenceScorer, PermitRequest, ScoringContext } from '@cognitum/gate';\n\nclass CustomCoherenceScorer implements CoherenceScorer {\n  private actionHistory: Map<string, number[]> = new Map();\n\n  async score(request: PermitRequest, context: ScoringContext): Promise<number> {\n    let score = 1.0;\n\n    // Penalize rapid repeated actions\n    const key = `${request.agentId}:${request.action}`;\n    const history = this.actionHistory.get(key) || [];\n    const recentCount = history.filter(t => Date.now() - t < 60000).length;\n    score -= recentCount * 0.1;\n\n    // Update history\n    history.push(Date.now());\n    if (history.length > 100) history.shift();\n    this.actionHistory.set(key, history);\n\n    // Boost for high-priority requests\n    if (request.priority === 'critical') {\n      score += 0.2;\n    } else if (request.priority === 'high') {\n      score += 0.1;\n    }\n\n    // Apply time-of-day adjustments\n    const hour = new Date().getHours();\n    if (hour < 6 || hour > 22) {\n      score -= 0.15; // Stricter during off-hours\n    }\n\n    // Consider tile load\n    if (context.tileLoad > 0.8) {\n      score -= 0.1; // Stricter under high load\n    }\n\n    return Math.max(0, Math.min(1, score));\n  }\n}\n\nconst gate = await CognitumGate.init({\n  coherenceScorer: new CustomCoherenceScorer(),\n});\n```\n\n</details>\n\n---\n\n## API Reference\n\n### CognitumGate Class\n\n```typescript\nclass CognitumGate {\n  /**\n   * Initialize a new CognitumGate instance\n   */\n  static init(config?: GateConfig): Promise<CognitumGate>;\n\n  /**\n   * Request permission for an action\n   */\n  permitAction(request: PermitRequest): Promise<PermitResult>;\n\n  /**\n   * Batch permission requests for efficiency\n   */\n  batchPermit(requests: PermitRequest[]): Promise<PermitResult[]>;\n\n  /**\n   * Stream permission decisions with backpressure handling\n   */\n  permitStream(\n    requests: AsyncIterable<PermitRequest>,\n    options?: StreamOptions\n  ): AsyncIterable<PermitResult>;\n\n  /**\n   * Retrieve a witness receipt by token\n   */\n  getReceipt(token: string): Promise<WitnessReceipt>;\n\n  /**\n   * Record the outcome of a permitted action\n   */\n  recordOutcome(token: string, outcome: ActionOutcome): Promise<void>;\n\n  /**\n   * Get current gate statistics\n   */\n  getStats(): GateStats;\n\n  /**\n   * Check if SharedArrayBuffer is available\n   */\n  readonly supportsSharedMemory: boolean;\n\n  /**\n   * Subscribe to gate events\n   */\n  on(event: GateEvent, handler: EventHandler): void;\n\n  /**\n   * Unsubscribe from gate events\n   */\n  off(event: GateEvent, handler: EventHandler): void;\n\n  /**\n   * Destroy the gate and release resources\n   */\n  destroy(): Promise<void>;\n}\n```\n\n### Type Definitions\n\n```typescript\ninterface GateConfig {\n  /** Number of WASM tiles (default: navigator.hardwareConcurrency || 4) */\n  tileCount?: number;\n\n  /** Minimum coherence score to permit (default: 0.85) */\n  coherenceThreshold?: number;\n\n  /** Maximum context tokens to consider (default: 8192) */\n  maxContextTokens?: number;\n\n  /** Custom tile topology */\n  topology?: TileTopology;\n\n  /** Custom receipt storage backend */\n  receiptStore?: ReceiptStore;\n\n  /** Tile memory configuration */\n  tileMemory?: TileMemoryConfig;\n\n  /** Custom coherence scoring implementation */\n  coherenceScorer?: CoherenceScorer;\n\n  /** Agent permission policies */\n  policies?: AgentPolicy[];\n\n  /** Default policy for unspecified agents */\n  defaultPolicy?: DefaultPolicy;\n\n  /** Offline mode configuration */\n  offlineMode?: OfflineModeConfig;\n\n  /** Runtime hint ('browser' | 'node' | 'deno' | 'bun') */\n  runtime?: RuntimeHint;\n}\n\ninterface PermitRequest {\n  /** Unique identifier for the requesting agent */\n  agentId: string;\n\n  /** Action being requested */\n  action: string;\n\n  /** Target resource (optional) */\n  target?: string;\n\n  /** Additional context for coherence scoring */\n  context?: Record<string, unknown>;\n\n  /** Request priority (default: 'normal') */\n  priority?: 'low' | 'normal' | 'high' | 'critical';\n\n  /** Timeout in milliseconds (default: 5000) */\n  timeoutMs?: number;\n}\n\ninterface PermitResult {\n  /** Decision: permit, defer, or deny */\n  verdict: 'permit' | 'defer' | 'deny';\n\n  /** Unique permit token (for receipts) */\n  token: string;\n\n  /** Coherence score (0.0 - 1.0) */\n  coherenceScore: number;\n\n  /** ID of the tile that processed the request */\n  tileId: number;\n\n  /** Processing latency in microseconds */\n  latencyUs: number;\n\n  /** Human-readable reason for defer/deny */\n  reason?: string;\n\n  /** Suggested delay for deferred requests (ms) */\n  deferMs?: number;\n}\n\ninterface WitnessReceipt {\n  /** Permit token */\n  token: string;\n\n  /** BLAKE3/SHA-256 witness hash */\n  witnessHash: string;\n\n  /** Unix timestamp (milliseconds) */\n  timestamp: number;\n\n  /** Agent that made the request */\n  agentId: string;\n\n  /** Requested action */\n  action: string;\n\n  /** Final verdict */\n  verdict: 'permit' | 'defer' | 'deny';\n\n  /** Coherence score at decision time */\n  coherenceScore: number;\n\n  /** Hash of the previous receipt (chain) */\n  parentHash?: string;\n\n  /** Optional Ed25519 signature */\n  signature?: Uint8Array;\n\n  /** Action outcome (if recorded) */\n  outcome?: ActionOutcome;\n}\n\ninterface ActionOutcome {\n  /** Whether the action succeeded */\n  success: boolean;\n\n  /** Error message if failed */\n  error?: string;\n\n  /** Execution duration in milliseconds */\n  durationMs?: number;\n\n  /** Additional outcome metadata */\n  metadata?: Record<string, unknown>;\n}\n\ninterface GateStats {\n  /** Total requests processed */\n  totalRequests: number;\n\n  /** Requests by verdict */\n  verdicts: {\n    permit: number;\n    defer: number;\n    deny: number;\n  };\n\n  /** Average latency in microseconds */\n  avgLatencyUs: number;\n\n  /** P99 latency in microseconds */\n  p99LatencyUs: number;\n\n  /** Active tiles */\n  activeTiles: number;\n\n  /** Memory usage per tile (bytes) */\n  memoryPerTile: number[];\n\n  /** Uptime in milliseconds */\n  uptimeMs: number;\n}\n\ntype GateEvent =\n  | 'permit'\n  | 'defer'\n  | 'deny'\n  | 'error'\n  | 'offline'\n  | 'online'\n  | 'sync'\n  | 'tile-error'\n  | 'tile-restart';\n```\n\n---\n\n## Claude-Flow Integration\n\n### MCP Server Setup\n\nAdd the Cognitum Gate MCP server to your Claude Code configuration:\n\n```bash\nclaude mcp add cognitum-gate npx @cognitum/gate mcp start\n```\n\nOr configure in `.claude/settings.json`:\n\n```json\n{\n  \"mcpServers\": {\n    \"cognitum-gate\": {\n      \"command\": \"npx\",\n      \"args\": [\"@cognitum/gate\", \"mcp\", \"start\"],\n      \"env\": {\n        \"COGNITUM_THRESHOLD\": \"0.9\",\n        \"COGNITUM_TILES\": \"8\"\n      }\n    }\n  }\n}\n```\n\n### Using with Claude Code\n\nOnce configured, the gate automatically integrates with Claude Code's hook system:\n\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Edit|Write|Bash\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"npx @cognitum/gate permit --action $TOOL_NAME --target \\\"$TOOL_INPUT_file_path\\\"\"\n          }\n        ]\n      }\n    ],\n    \"PostToolUse\": [\n      {\n        \"matcher\": \"Edit|Write|Bash\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"npx @cognitum/gate record-outcome --token \\\"$PERMIT_TOKEN\\\" --success $TOOL_SUCCESS\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n### Agent Permission Patterns\n\nDefine granular permissions for different agent types:\n\n```typescript\nimport { CognitumGate, AgentPolicy } from '@cognitum/gate';\n\nconst policies: AgentPolicy[] = [\n  {\n    agentId: 'coder',\n    permissions: {\n      'file_read': { threshold: 0.7 },\n      'file_write': { threshold: 0.9, targets: ['src/**', 'tests/**'] },\n      'file_delete': { threshold: 0.99 },\n      'bash_execute': { threshold: 0.95, denyPatterns: ['rm -rf', 'sudo', 'chmod 777'] },\n    },\n  },\n  {\n    agentId: 'researcher',\n    permissions: {\n      'file_read': { threshold: 0.5 },\n      'web_fetch': { threshold: 0.6 },\n      'file_write': { verdict: 'deny' }, // Never permit writes\n    },\n  },\n  {\n    agentId: 'reviewer',\n    permissions: {\n      'file_read': { threshold: 0.5 },\n      'git_command': { threshold: 0.8 },\n      'file_write': { verdict: 'deny' },\n    },\n  },\n];\n\nconst gate = await CognitumGate.init({\n  policies,\n  defaultPolicy: {\n    threshold: 0.95, // Strict default for unknown agents\n  },\n});\n```\n\n---\n\n## Browser Support\n\n| Browser | Version | SharedArrayBuffer | WebGPU | Notes |\n|---------|---------|-------------------|--------|-------|\n| Chrome | 89+ | Yes | Yes | Full support |\n| Firefox | 79+ | Yes | Partial | WebGPU behind flag |\n| Safari | 15.2+ | Yes | Yes | Requires COOP/COEP |\n| Edge | 89+ | Yes | Yes | Full support |\n| Node.js | 16+ | Yes | N/A | Full support |\n| Deno | 1.25+ | Yes | Partial | Full support |\n| Bun | 0.6+ | Yes | N/A | Full support |\n\n**Note**: SharedArrayBuffer requires cross-origin isolation headers:\n\n```\nCross-Origin-Opener-Policy: same-origin\nCross-Origin-Embedder-Policy: require-corp\n```\n\n### CSP Requirements\n\nIf using Content Security Policy, ensure WASM is allowed:\n\n```\nContent-Security-Policy: script-src 'self' 'wasm-unsafe-eval';\n```\n\n---\n\n## License\n\nLicensed under either of:\n\n- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)\n- MIT License ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)\n\nat your option.\n\n### Contribution\n\nUnless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.\n\n---\n\n**Created by [ruv.io](https://ruv.io) and [RuVector](https://github.com/ruvnet/ruvector)**\n\n*Attention becomes a permission system, not a popularity contest.*\n","readmeFilename":"README.md"}