Merge commit 'd803bfe2b1fe7f5e219e50ac20d6801a0a58ac75' as 'vendor/ruvector'

This commit is contained in:
ruv
2026-02-28 14:39:40 -05:00
7854 changed files with 3522914 additions and 0 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,12 @@
/**
* Basic Coherence Gate Usage - TypeScript Example
*
* This example demonstrates:
* - Initializing the gate
* - Requesting action permission
* - Handling decisions
*
* Run with: npx ts-node examples/basic-usage.ts
*/
export {};
//# sourceMappingURL=basic-usage.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"basic-usage.d.ts","sourceRoot":"","sources":["basic-usage.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG"}

View File

@@ -0,0 +1,87 @@
"use strict";
/**
* Basic Coherence Gate Usage - TypeScript Example
*
* This example demonstrates:
* - Initializing the gate
* - Requesting action permission
* - Handling decisions
*
* Run with: npx ts-node examples/basic-usage.ts
*/
Object.defineProperty(exports, "__esModule", { value: true });
const gate_1 = require("@cognitum/gate");
async function main() {
console.log('=== Cognitum Gate - Basic Usage ===\n');
// Initialize the gate
const gate = await gate_1.CognitumGate.init({
thresholds: {
minCut: 10.0,
maxShift: 0.5,
eDeny: 0.01,
ePermit: 100.0,
},
storage: 'memory', // Use 'indexeddb' for persistence
});
console.log('Gate initialized\n');
// Define an action
const action = {
actionId: 'deploy-v2.1.0',
actionType: 'deployment',
agentId: 'ci-agent',
target: 'production-cluster',
metadata: {
version: '2.1.0',
changedFiles: 42,
},
};
console.log('Requesting permission for:', action.actionId);
// Request permission
const result = await gate.permitAction(action);
// Handle the decision
switch (result.decision) {
case gate_1.GateDecision.Permit:
console.log('\n✅ PERMITTED');
console.log('Token:', result.token.slice(0, 50) + '...');
console.log('Valid until:', new Date(result.validUntilNs / 1000000).toISOString());
// Agent can now proceed with the action
await performDeployment(action, result.token);
break;
case gate_1.GateDecision.Defer:
console.log('\n⏸ DEFERRED - Human review required');
console.log('Reason:', result.reason);
console.log('Escalation URL:', result.escalation?.contextUrl);
// Wait for human decision or timeout
const humanDecision = await waitForHumanDecision(result.receiptSequence);
if (humanDecision.approved) {
await performDeployment(action, humanDecision.token);
}
break;
case gate_1.GateDecision.Deny:
console.log('\n❌ DENIED');
console.log('Reason:', result.reason);
console.log('Witness:', result.witness);
// Log the denial for review
await logDeniedAction(action, result);
break;
}
// Audit: Get the receipt
const receipt = await gate.getReceipt(result.receiptSequence);
console.log('\nReceipt hash:', receipt.hash.slice(0, 16) + '...');
console.log('\n=== Example Complete ===');
}
async function performDeployment(action, token) {
console.log(`\nDeploying ${action.metadata?.version} to ${action.target}...`);
console.log('(Deployment would happen here with token validation)');
}
async function waitForHumanDecision(sequence) {
console.log(`\nWaiting for human decision on sequence ${sequence}...`);
// In production, this would poll an API or use WebSocket
return { approved: true, token: 'human-approved-token' };
}
async function logDeniedAction(action, result) {
console.log(`\nLogging denied action: ${action.actionId}`);
// In production, send to logging/alerting system
}
main().catch(console.error);
//# sourceMappingURL=basic-usage.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"basic-usage.js","sourceRoot":"","sources":["basic-usage.ts"],"names":[],"mappings":";AAAA;;;;;;;;;GASG;;AAEH,yCAA2E;AAE3E,KAAK,UAAU,IAAI;IACjB,OAAO,CAAC,GAAG,CAAC,uCAAuC,CAAC,CAAC;IAErD,sBAAsB;IACtB,MAAM,IAAI,GAAG,MAAM,mBAAY,CAAC,IAAI,CAAC;QACnC,UAAU,EAAE;YACV,MAAM,EAAE,IAAI;YACZ,QAAQ,EAAE,GAAG;YACb,KAAK,EAAE,IAAI;YACX,OAAO,EAAE,KAAK;SACf;QACD,OAAO,EAAE,QAAQ,EAAE,kCAAkC;KACtD,CAAC,CAAC;IAEH,OAAO,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC;IAElC,mBAAmB;IACnB,MAAM,MAAM,GAAkB;QAC5B,QAAQ,EAAE,eAAe;QACzB,UAAU,EAAE,YAAY;QACxB,OAAO,EAAE,UAAU;QACnB,MAAM,EAAE,oB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C"}

View File

@@ -0,0 +1,103 @@
/**
* Basic Coherence Gate Usage - TypeScript Example
*
* This example demonstrates:
* - Initializing the gate
* - Requesting action permission
* - Handling decisions
*
* Run with: npx ts-node examples/basic-usage.ts
*/
import { CognitumGate, GateDecision, ActionContext } from '@cognitum/gate';
async function main() {
console.log('=== Cognitum Gate - Basic Usage ===\n');
// Initialize the gate
const gate = await CognitumGate.init({
thresholds: {
minCut: 10.0,
maxShift: 0.5,
eDeny: 0.01,
ePermit: 100.0,
},
storage: 'memory', // Use 'indexeddb' for persistence
});
console.log('Gate initialized\n');
// Define an action
const action: ActionContext = {
actionId: 'deploy-v2.1.0',
actionType: 'deployment',
agentId: 'ci-agent',
target: 'production-cluster',
metadata: {
version: '2.1.0',
changedFiles: 42,
},
};
console.log('Requesting permission for:', action.actionId);
// Request permission
const result = await gate.permitAction(action);
// Handle the decision
switch (result.decision) {
case GateDecision.Permit:
console.log('\n✅ PERMITTED');
console.log('Token:', result.token.slice(0, 50) + '...');
console.log('Valid until:', new Date(result.validUntilNs / 1_000_000).toISOString());
// Agent can now proceed with the action
await performDeployment(action, result.token);
break;
case GateDecision.Defer:
console.log('\n⏸ DEFERRED - Human review required');
console.log('Reason:', result.reason);
console.log('Escalation URL:', result.escalation?.contextUrl);
// Wait for human decision or timeout
const humanDecision = await waitForHumanDecision(result.receiptSequence);
if (humanDecision.approved) {
await performDeployment(action, humanDecision.token);
}
break;
case GateDecision.Deny:
console.log('\n❌ DENIED');
console.log('Reason:', result.reason);
console.log('Witness:', result.witness);
// Log the denial for review
await logDeniedAction(action, result);
break;
}
// Audit: Get the receipt
const receipt = await gate.getReceipt(result.receiptSequence);
console.log('\nReceipt hash:', receipt.hash.slice(0, 16) + '...');
console.log('\n=== Example Complete ===');
}
async function performDeployment(action: ActionContext, token: string) {
console.log(`\nDeploying ${action.metadata?.version} to ${action.target}...`);
console.log('(Deployment would happen here with token validation)');
}
async function waitForHumanDecision(sequence: number) {
console.log(`\nWaiting for human decision on sequence ${sequence}...`);
// In production, this would poll an API or use WebSocket
return { approved: true, token: 'human-approved-token' };
}
async function logDeniedAction(action: ActionContext, result: any) {
console.log(`\nLogging denied action: ${action.actionId}`);
// In production, send to logging/alerting system
}
main().catch(console.error);

View File

@@ -0,0 +1,16 @@
/**
* Express Middleware Example
*
* This example shows how to use Cognitum Gate as Express middleware
* to protect API endpoints with coherence-based access control.
*
* Run with: npx ts-node examples/express-middleware.ts
*/
declare module 'express' {
interface Request {
gateToken?: string;
gateReceipt?: number;
}
}
export {};
//# sourceMappingURL=express-middleware.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"express-middleware.d.ts","sourceRoot":"","sources":["express-middleware.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAMH,OAAO,QAAQ,SAAS,CAAC;IACvB,UAAU,OAAO;QACf,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,WAAW,CAAC,EAAE,MAAM,CAAC;KACtB;CACF"}

View File

@@ -0,0 +1,151 @@
"use strict";
/**
* Express Middleware Example
*
* This example shows how to use Cognitum Gate as Express middleware
* to protect API endpoints with coherence-based access control.
*
* Run with: npx ts-node examples/express-middleware.ts
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const gate_1 = require("@cognitum/gate");
// Initialize the gate (singleton)
let gate;
async function initGate() {
gate = await gate_1.CognitumGate.init({
thresholds: {
minCut: 10.0,
maxShift: 0.5,
eDeny: 0.01,
ePermit: 100.0,
},
storage: 'memory',
});
}
/**
* Gate middleware factory
* Creates middleware that checks coherence before allowing actions
*/
function gateMiddleware(actionType) {
return async (req, res, next) => {
const action = {
actionId: `${req.method}-${req.path}-${Date.now()}`,
actionType,
agentId: req.headers['x-agent-id'] || 'anonymous',
target: req.path,
metadata: {
method: req.method,
ip: req.ip,
userAgent: req.headers['user-agent'],
},
};
try {
const result = await gate.permitAction(action);
switch (result.decision) {
case gate_1.GateDecision.Permit:
// Attach token and continue
req.gateToken = result.token;
req.gateReceipt = result.receiptSequence;
next();
break;
case gate_1.GateDecision.Defer:
// Return 202 Accepted with escalation info
res.status(202).json({
status: 'deferred',
message: 'Human approval required',
escalation: {
url: result.escalation?.contextUrl,
timeout: result.escalation?.timeoutNs,
},
receiptSequence: result.receiptSequence,
});
break;
case gate_1.GateDecision.Deny:
// Return 403 Forbidden with witness
res.status(403).json({
status: 'denied',
reason: result.reason,
witness: {
structural: result.witness?.structural,
evidential: result.witness?.evidential,
},
receiptSequence: result.receiptSequence,
});
break;
}
}
catch (error) {
// Gate error - fail closed
res.status(500).json({
status: 'error',
message: 'Gate evaluation failed',
});
}
};
}
// Create Express app
const app = (0, express_1.default)();
app.use(express_1.default.json());
// Public endpoints (no gate)
app.get('/health', (req, res) => {
res.json({ status: 'healthy' });
});
// Protected read endpoint
app.get('/api/config/:id', gateMiddleware('config_read'), (req, res) => {
res.json({
id: req.params.id,
value: 'some-config-value',
_gateReceipt: req.gateReceipt,
});
});
// Protected write endpoint (higher scrutiny)
app.post('/api/config/:id', gateMiddleware('config_write'), (req, res) => {
res.json({
id: req.params.id,
updated: true,
_gateReceipt: req.gateReceipt,
});
});
// Critical endpoint (deployment)
app.post('/api/deploy', gateMiddleware('deployment'), (req, res) => {
res.json({
deployed: true,
version: req.body.version,
_gateReceipt: req.gateReceipt,
});
});
// Audit endpoint
app.get('/api/audit/receipts', async (req, res) => {
const from = parseInt(req.query.from) || 0;
const limit = parseInt(req.query.limit) || 100;
const receipts = await gate.getReceipts(from, limit);
res.json({
receipts,
chainValid: await gate.verifyChain(),
});
});
// Start server
async function main() {
await initGate();
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Cognitum Gate Express example listening on port ${PORT}`);
console.log(`
Endpoints:
GET /health - Health check (no gate)
GET /api/config/:id - Read config (gated)
POST /api/config/:id - Write config (gated)
POST /api/deploy - Deploy (gated, high scrutiny)
GET /api/audit/receipts - Audit trail
Test with:
curl http://localhost:${PORT}/api/config/123 -H "X-Agent-Id: test-agent"
`);
});
}
main().catch(console.error);
//# sourceMappingURL=express-middleware.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"express-middleware.js","sourceRoot":"","sources":["express-middleware.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;;;AAEH,sDAAmE;AACnE,yCAA2E;AAU3E,kCAAkC;AAClC,IAAI,IAAkB,CAAC;AAEvB,KAAK,UAAU,QAAQ;IACrB,IAAI,GAAG,MAAM,mBAAY,CAAC,IAAI,CAAC;QAC7B,UAAU,EAAE;YACV,MAAM,EAAE,IAAI;YACZ,QAAQ,EAAE,GAAG;YACb,KAAK,EAAE,IAAI;YACX,OAAO,EAAE,KAAK;SACf;QACD,OAAO,EAAE,QAAQ;KAClB,CAAC,CAAC;AACL,CAAC;AAED;;;GAGG;AACH,SAAS,cAAc,CAAC,UAAkB;IACxC,OAAO,KAAK,EAAE,GAAY,EAAE,GAAa,EAAE,IAAkB,EAAE,EAAE;QAC/D,MAAM,MAAM,GAAkB;YAC5B,QAAQ,EAAE,GAAG,GAAG,CAAC,MAAM,IAAI,GAAG,CAAC,IAAI,IAAI,IAAI,CAAC,GAAG,EAAE,EAAE;YACnD,UAAU;YACV,OAAO,EAAE,GAAG,CAAC,OAAO,CAAC,YAAY,CAAW,IAAI,WAAW;YAC3D,MAAM,EAAE,GAAG,CAAC,IAAI;YAChB,QAAQ,EAAE;gBACR,MAAM,EAAE,GAAG,CAAC,MAAM;gBAClB,EAAE,EAAE,GAAG,CAAC,EAAE;gBACV,SAAS,EAAE,GAAG,CAAC,OAAO,CAAC,YAAY,CAAC;aACrC;SACF,CAAC;QAEF,IAAI,CAAC;YACH,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC;YAE/C,QAAQ,MAAM,CAAC,QAAQ,EAAE,CAAC;gBACxB,KAAK,mBAAY,CAAC,MAAM;oBACtB,4BA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G,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAC,IAAc,CAAC,IAAI,CAAC,CAAC;IACrD,MAAM,KAAK,GAAG,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAC,KAAe,CAAC,IAAI,GAAG,CAAC;IAEzD,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IACrD,GAAG,CAAC,IAAI,CAAC;QACP,QAAQ;QACR,UAAU,EAAE,MAAM,IAAI,CAAC,WAAW,EAAE;KACrC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,eAAe;AACf,KAAK,UAAU,IAAI;IACjB,MAAM,QAAQ,EAAE,CAAC;IAEjB,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,IAAI,IAAI,IAAI,CAAC;IACtC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,EAAE;QACpB,OAAO,CAAC,GAAG,CAAC,mDAAmD,IAAI,EAAE,CAAC,CAAC;QACvE,OAAO,CAAC,GAAG,CAAC;;;;;;;;;0BASU,IAAI;KACzB,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC"}

View File

@@ -0,0 +1,179 @@
/**
* Express Middleware Example
*
* This example shows how to use Cognitum Gate as Express middleware
* to protect API endpoints with coherence-based access control.
*
* Run with: npx ts-node examples/express-middleware.ts
*/
import express, { Request, Response, NextFunction } from 'express';
import { CognitumGate, GateDecision, ActionContext } from '@cognitum/gate';
// Extend Express Request to include gate context
declare module 'express' {
interface Request {
gateToken?: string;
gateReceipt?: number;
}
}
// Initialize the gate (singleton)
let gate: CognitumGate;
async function initGate() {
gate = await CognitumGate.init({
thresholds: {
minCut: 10.0,
maxShift: 0.5,
eDeny: 0.01,
ePermit: 100.0,
},
storage: 'memory',
});
}
/**
* Gate middleware factory
* Creates middleware that checks coherence before allowing actions
*/
function gateMiddleware(actionType: string) {
return async (req: Request, res: Response, next: NextFunction) => {
const action: ActionContext = {
actionId: `${req.method}-${req.path}-${Date.now()}`,
actionType,
agentId: req.headers['x-agent-id'] as string || 'anonymous',
target: req.path,
metadata: {
method: req.method,
ip: req.ip,
userAgent: req.headers['user-agent'],
},
};
try {
const result = await gate.permitAction(action);
switch (result.decision) {
case GateDecision.Permit:
// Attach token and continue
req.gateToken = result.token;
req.gateReceipt = result.receiptSequence;
next();
break;
case GateDecision.Defer:
// Return 202 Accepted with escalation info
res.status(202).json({
status: 'deferred',
message: 'Human approval required',
escalation: {
url: result.escalation?.contextUrl,
timeout: result.escalation?.timeoutNs,
},
receiptSequence: result.receiptSequence,
});
break;
case GateDecision.Deny:
// Return 403 Forbidden with witness
res.status(403).json({
status: 'denied',
reason: result.reason,
witness: {
structural: result.witness?.structural,
evidential: result.witness?.evidential,
},
receiptSequence: result.receiptSequence,
});
break;
}
} catch (error) {
// Gate error - fail closed
res.status(500).json({
status: 'error',
message: 'Gate evaluation failed',
});
}
};
}
// Create Express app
const app = express();
app.use(express.json());
// Public endpoints (no gate)
app.get('/health', (req, res) => {
res.json({ status: 'healthy' });
});
// Protected read endpoint
app.get('/api/config/:id',
gateMiddleware('config_read'),
(req, res) => {
res.json({
id: req.params.id,
value: 'some-config-value',
_gateReceipt: req.gateReceipt,
});
}
);
// Protected write endpoint (higher scrutiny)
app.post('/api/config/:id',
gateMiddleware('config_write'),
(req, res) => {
res.json({
id: req.params.id,
updated: true,
_gateReceipt: req.gateReceipt,
});
}
);
// Critical endpoint (deployment)
app.post('/api/deploy',
gateMiddleware('deployment'),
(req, res) => {
res.json({
deployed: true,
version: req.body.version,
_gateReceipt: req.gateReceipt,
});
}
);
// Audit endpoint
app.get('/api/audit/receipts', async (req, res) => {
const from = parseInt(req.query.from as string) || 0;
const limit = parseInt(req.query.limit as string) || 100;
const receipts = await gate.getReceipts(from, limit);
res.json({
receipts,
chainValid: await gate.verifyChain(),
});
});
// Start server
async function main() {
await initGate();
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Cognitum Gate Express example listening on port ${PORT}`);
console.log(`
Endpoints:
GET /health - Health check (no gate)
GET /api/config/:id - Read config (gated)
POST /api/config/:id - Write config (gated)
POST /api/deploy - Deploy (gated, high scrutiny)
GET /api/audit/receipts - Audit trail
Test with:
curl http://localhost:${PORT}/api/config/123 -H "X-Agent-Id: test-agent"
`);
});
}
main().catch(console.error);

View File

@@ -0,0 +1,40 @@
/**
* React Hook Example
*
* This example shows how to use Cognitum Gate in React applications
* with a custom hook for action permission.
*
* Usage in your React app:
* import { useGate, GateProvider } from './react-hook';
*/
import { ReactNode } from 'react';
interface GateProviderProps {
children: ReactNode;
config?: {
minCut?: number;
maxShift?: number;
storage?: 'memory' | 'indexeddb';
};
}
export declare function GateProvider({ children, config }: GateProviderProps): any;
export declare function useGate(): any;
export declare function usePermitAction(): {
requestPermit: any;
isLoading: any;
error: any;
lastResult: any;
isReady: any;
};
interface ProtectedButtonProps {
actionId: string;
actionType: string;
target: string;
onPermitted: (token: string) => void;
onDeferred: (sequence: number) => void;
onDenied: (reason: string) => void;
children: ReactNode;
}
export declare function ProtectedButton({ actionId, actionType, target, onPermitted, onDeferred, onDenied, children, }: ProtectedButtonProps): any;
export declare function ExampleApp(): any;
export default ExampleApp;
//# sourceMappingURL=react-hook.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"react-hook.d.ts","sourceRoot":"","sources":["react-hook.tsx"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAc,EAA+D,SAAS,EAAE,MAAM,OAAO,CAAC;AActG,UAAU,iBAAiB;IACzB,QAAQ,EAAE,SAAS,CAAC;IACpB,MAAM,CAAC,EAAE;QACP,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,OAAO,CAAC,EAAE,QAAQ,GAAG,WAAW,CAAC;KAClC,CAAC;CACH;AAED,wBAAgB,YAAY,CAAC,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,iBAAiB,OAoCnE;AAGD,wBAAgB,OAAO,QAMtB;AAGD,wBAAgB,eAAe;;;;;;EA4B9B;AAGD,UAAU,oBAAoB;IAC5B,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IACrC,UAAU,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAC;IACvC,QAAQ,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC;IACnC,QAAQ,EAAE,SAAS,CAAC;CACrB;AAED,wBAAgB,eAAe,CAAC,EAC9B,QAAQ,EACR,UAAU,EACV,MAAM,EACN,WAAW,EACX,UAAU,EACV,QAAQ,EACR,QAAQ,GACT,EAAE,oBAAoB,OAiCtB;AAGD,wBAAgB,UAAU,QA+BzB;AAwCD,eAAe,UAAU,CAAC"}

View File

@@ -0,0 +1,204 @@
"use strict";
/**
* React Hook Example
*
* This example shows how to use Cognitum Gate in React applications
* with a custom hook for action permission.
*
* Usage in your React app:
* import { useGate, GateProvider } from './react-hook';
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.GateProvider = GateProvider;
exports.useGate = useGate;
exports.usePermitAction = usePermitAction;
exports.ProtectedButton = ProtectedButton;
exports.ExampleApp = ExampleApp;
const react_1 = __importStar(require("react"));
const gate_1 = require("@cognitum/gate");
const GateContext = (0, react_1.createContext)(null);
function GateProvider({ children, config }) {
const [gate, setGate] = (0, react_1.useState)(null);
const [isReady, setIsReady] = (0, react_1.useState)(false);
const [pendingActions] = (0, react_1.useState)(new Map());
(0, react_1.useEffect)(() => {
gate_1.CognitumGate.init({
thresholds: {
minCut: config?.minCut ?? 10.0,
maxShift: config?.maxShift ?? 0.5,
eDeny: 0.01,
ePermit: 100.0,
},
storage: config?.storage ?? 'indexeddb',
}).then((g) => {
setGate(g);
setIsReady(true);
});
}, [config]);
const permitAction = (0, react_1.useCallback)(async (action) => {
if (!gate)
throw new Error('Gate not initialized');
const result = await gate.permitAction(action);
if (result.decision === gate_1.GateDecision.Defer) {
pendingActions.set(result.receiptSequence, action);
}
return result;
}, [gate, pendingActions]);
return (<GateContext.Provider value={{ gate, isReady, permitAction, pendingActions }}>
{children}
</GateContext.Provider>);
}
// useGate Hook
function useGate() {
const context = (0, react_1.useContext)(GateContext);
if (!context) {
throw new Error('useGate must be used within a GateProvider');
}
return context;
}
// usePermitAction Hook - simplified action permission
function usePermitAction() {
const { permitAction, isReady } = useGate();
const [isLoading, setIsLoading] = (0, react_1.useState)(false);
const [error, setError] = (0, react_1.useState)(null);
const [lastResult, setLastResult] = (0, react_1.useState)(null);
const requestPermit = (0, react_1.useCallback)(async (action) => {
if (!isReady) {
setError(new Error('Gate not ready'));
return null;
}
setIsLoading(true);
setError(null);
try {
const result = await permitAction(action);
setLastResult(result);
return result;
}
catch (e) {
setError(e);
return null;
}
finally {
setIsLoading(false);
}
}, [permitAction, isReady]);
return { requestPermit, isLoading, error, lastResult, isReady };
}
function ProtectedButton({ actionId, actionType, target, onPermitted, onDeferred, onDenied, children, }) {
const { requestPermit, isLoading, error } = usePermitAction();
const handleClick = async () => {
const result = await requestPermit({
actionId,
actionType,
agentId: 'web-user',
target,
metadata: { timestamp: Date.now() },
});
if (!result)
return;
switch (result.decision) {
case gate_1.GateDecision.Permit:
onPermitted(result.token);
break;
case gate_1.GateDecision.Defer:
onDeferred(result.receiptSequence);
break;
case gate_1.GateDecision.Deny:
onDenied(result.reason || 'Action denied');
break;
}
};
return (<button onClick={handleClick} disabled={isLoading}>
{isLoading ? 'Checking...' : children}
{error && <span className="error">{error.message}</span>}
</button>);
}
// Example App
function ExampleApp() {
const [status, setStatus] = (0, react_1.useState)('');
return (<GateProvider config={{ storage: 'indexeddb' }}>
<div className="app">
<h1>Cognitum Gate - React Example</h1>
<ProtectedButton actionId="deploy-button" actionType="deployment" target="production" onPermitted={(token) => {
setStatus(`✅ Permitted! Token: ${token.slice(0, 20)}...`);
}} onDeferred={(seq) => {
setStatus(`⏸️ Deferred - Human review needed (seq: ${seq})`);
}} onDenied={(reason) => {
setStatus(`❌ Denied: ${reason}`);
}}>
Deploy to Production
</ProtectedButton>
<p>{status}</p>
<AuditLog />
</div>
</GateProvider>);
}
// Audit Log Component
function AuditLog() {
const { gate, isReady } = useGate();
const [receipts, setReceipts] = (0, react_1.useState)([]);
(0, react_1.useEffect)(() => {
if (isReady && gate) {
gate.getReceipts(0, 10).then(setReceipts);
}
}, [gate, isReady]);
return (<div className="audit-log">
<h2>Recent Decisions</h2>
<table>
<thead>
<tr>
<th>Seq</th>
<th>Action</th>
<th>Decision</th>
<th>Time</th>
</tr>
</thead>
<tbody>
{receipts.map((r) => (<tr key={r.sequence}>
<td>{r.sequence}</td>
<td>{r.token.actionId}</td>
<td>{r.token.decision}</td>
<td>{new Date(r.token.timestamp / 1000000).toLocaleString()}</td>
</tr>))}
</tbody>
</table>
</div>);
}
exports.default = ExampleApp;
//# sourceMappingURL=react-hook.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,238 @@
/**
* React Hook Example
*
* This example shows how to use Cognitum Gate in React applications
* with a custom hook for action permission.
*
* Usage in your React app:
* import { useGate, GateProvider } from './react-hook';
*/
import React, { createContext, useContext, useState, useEffect, useCallback, ReactNode } from 'react';
import { CognitumGate, GateDecision, ActionContext, PermitResult } from '@cognitum/gate';
// Gate Context
interface GateContextValue {
gate: CognitumGate | null;
isReady: boolean;
permitAction: (action: ActionContext) => Promise<PermitResult>;
pendingActions: Map<number, ActionContext>;
}
const GateContext = createContext<GateContextValue | null>(null);
// Gate Provider
interface GateProviderProps {
children: ReactNode;
config?: {
minCut?: number;
maxShift?: number;
storage?: 'memory' | 'indexeddb';
};
}
export function GateProvider({ children, config }: GateProviderProps) {
const [gate, setGate] = useState<CognitumGate | null>(null);
const [isReady, setIsReady] = useState(false);
const [pendingActions] = useState(new Map<number, ActionContext>());
useEffect(() => {
CognitumGate.init({
thresholds: {
minCut: config?.minCut ?? 10.0,
maxShift: config?.maxShift ?? 0.5,
eDeny: 0.01,
ePermit: 100.0,
},
storage: config?.storage ?? 'indexeddb',
}).then((g) => {
setGate(g);
setIsReady(true);
});
}, [config]);
const permitAction = useCallback(async (action: ActionContext) => {
if (!gate) throw new Error('Gate not initialized');
const result = await gate.permitAction(action);
if (result.decision === GateDecision.Defer) {
pendingActions.set(result.receiptSequence, action);
}
return result;
}, [gate, pendingActions]);
return (
<GateContext.Provider value={{ gate, isReady, permitAction, pendingActions }}>
{children}
</GateContext.Provider>
);
}
// useGate Hook
export function useGate() {
const context = useContext(GateContext);
if (!context) {
throw new Error('useGate must be used within a GateProvider');
}
return context;
}
// usePermitAction Hook - simplified action permission
export function usePermitAction() {
const { permitAction, isReady } = useGate();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
const [lastResult, setLastResult] = useState<PermitResult | null>(null);
const requestPermit = useCallback(async (action: ActionContext) => {
if (!isReady) {
setError(new Error('Gate not ready'));
return null;
}
setIsLoading(true);
setError(null);
try {
const result = await permitAction(action);
setLastResult(result);
return result;
} catch (e) {
setError(e as Error);
return null;
} finally {
setIsLoading(false);
}
}, [permitAction, isReady]);
return { requestPermit, isLoading, error, lastResult, isReady };
}
// Example Component: Protected Button
interface ProtectedButtonProps {
actionId: string;
actionType: string;
target: string;
onPermitted: (token: string) => void;
onDeferred: (sequence: number) => void;
onDenied: (reason: string) => void;
children: ReactNode;
}
export function ProtectedButton({
actionId,
actionType,
target,
onPermitted,
onDeferred,
onDenied,
children,
}: ProtectedButtonProps) {
const { requestPermit, isLoading, error } = usePermitAction();
const handleClick = async () => {
const result = await requestPermit({
actionId,
actionType,
agentId: 'web-user',
target,
metadata: { timestamp: Date.now() },
});
if (!result) return;
switch (result.decision) {
case GateDecision.Permit:
onPermitted(result.token);
break;
case GateDecision.Defer:
onDeferred(result.receiptSequence);
break;
case GateDecision.Deny:
onDenied(result.reason || 'Action denied');
break;
}
};
return (
<button onClick={handleClick} disabled={isLoading}>
{isLoading ? 'Checking...' : children}
{error && <span className="error">{error.message}</span>}
</button>
);
}
// Example App
export function ExampleApp() {
const [status, setStatus] = useState<string>('');
return (
<GateProvider config={{ storage: 'indexeddb' }}>
<div className="app">
<h1>Cognitum Gate - React Example</h1>
<ProtectedButton
actionId="deploy-button"
actionType="deployment"
target="production"
onPermitted={(token) => {
setStatus(`✅ Permitted! Token: ${token.slice(0, 20)}...`);
}}
onDeferred={(seq) => {
setStatus(`⏸️ Deferred - Human review needed (seq: ${seq})`);
}}
onDenied={(reason) => {
setStatus(`❌ Denied: ${reason}`);
}}
>
Deploy to Production
</ProtectedButton>
<p>{status}</p>
<AuditLog />
</div>
</GateProvider>
);
}
// Audit Log Component
function AuditLog() {
const { gate, isReady } = useGate();
const [receipts, setReceipts] = useState<any[]>([]);
useEffect(() => {
if (isReady && gate) {
gate.getReceipts(0, 10).then(setReceipts);
}
}, [gate, isReady]);
return (
<div className="audit-log">
<h2>Recent Decisions</h2>
<table>
<thead>
<tr>
<th>Seq</th>
<th>Action</th>
<th>Decision</th>
<th>Time</th>
</tr>
</thead>
<tbody>
{receipts.map((r) => (
<tr key={r.sequence}>
<td>{r.sequence}</td>
<td>{r.token.actionId}</td>
<td>{r.token.decision}</td>
<td>{new Date(r.token.timestamp / 1_000_000).toLocaleString()}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
export default ExampleApp;

View File

@@ -0,0 +1,104 @@
{
"name": "@cognitum/gate",
"version": "0.1.0",
"description": "Browser and Node.js coherence gate for AI agent safety - real-time permit/defer/deny decisions in microseconds",
"keywords": [
"ai",
"agent",
"safety",
"coherence",
"wasm",
"webassembly",
"permission",
"audit",
"claude",
"llm"
],
"author": "RuVector <hello@ruv.io>",
"license": "(MIT OR Apache-2.0)",
"homepage": "https://github.com/ruvnet/ruvector/tree/main/packages/cognitum-gate-wasm",
"repository": {
"type": "git",
"url": "git+https://github.com/ruvnet/ruvector.git",
"directory": "packages/cognitum-gate-wasm"
},
"bugs": {
"url": "https://github.com/ruvnet/ruvector/issues"
},
"main": "./dist/cjs/index.js",
"module": "./dist/esm/index.js",
"types": "./dist/types/index.d.ts",
"exports": {
".": {
"import": "./dist/esm/index.js",
"require": "./dist/cjs/index.js",
"types": "./dist/types/index.d.ts"
},
"./node": {
"import": "./dist/esm/node.js",
"require": "./dist/cjs/node.js",
"types": "./dist/types/node.d.ts"
},
"./sw": {
"import": "./dist/esm/sw.js",
"types": "./dist/types/sw.d.ts"
},
"./wasm": {
"import": "./dist/esm/wasm.js",
"require": "./dist/cjs/wasm.js",
"types": "./dist/types/wasm.d.ts"
},
"./experimental": {
"import": "./dist/esm/experimental.js",
"types": "./dist/types/experimental.d.ts"
}
},
"files": [
"dist",
"wasm",
"LICENSE-MIT",
"LICENSE-APACHE",
"README.md"
],
"engines": {
"node": ">=16.0.0"
},
"sideEffects": false,
"scripts": {
"build": "npm run build:wasm && npm run build:ts",
"build:wasm": "wasm-pack build ../cognitum-gate-kernel --target web --out-dir ../packages/cognitum-gate-wasm/wasm",
"build:ts": "tsup",
"build:types": "tsc --emitDeclarationOnly",
"test": "vitest run",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage",
"test:browser": "vitest run --environment jsdom",
"lint": "eslint src --ext .ts,.tsx",
"lint:fix": "eslint src --ext .ts,.tsx --fix",
"typecheck": "tsc --noEmit",
"clean": "rm -rf dist wasm",
"prepublishOnly": "npm run clean && npm run build && npm run test"
},
"dependencies": {
"@noble/hashes": "^1.3.3"
},
"devDependencies": {
"@types/node": "^20.10.0",
"@typescript-eslint/eslint-plugin": "^6.13.0",
"@typescript-eslint/parser": "^6.13.0",
"@vitest/coverage-v8": "^1.0.0",
"eslint": "^8.55.0",
"jsdom": "^23.0.0",
"tsup": "^8.0.0",
"typescript": "^5.3.0",
"vitest": "^1.0.0"
},
"peerDependencies": {
"claude-flow": ">=2.0.0"
},
"peerDependenciesMeta": {
"claude-flow": {
"optional": true
}
}
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff