diff --git a/crates/cognitum-gate-tilezero/Cargo.toml b/crates/cognitum-gate-tilezero/Cargo.toml index 3f0d0506..624fd49b 100644 --- a/crates/cognitum-gate-tilezero/Cargo.toml +++ b/crates/cognitum-gate-tilezero/Cargo.toml @@ -49,3 +49,15 @@ harness = false [[bench]] name = "benchmarks" harness = false + +[[example]] +name = "basic_gate" +required-features = [] + +[[example]] +name = "human_escalation" +required-features = [] + +[[example]] +name = "receipt_audit" +required-features = [] diff --git a/crates/cognitum-gate-tilezero/examples/basic_gate.rs b/crates/cognitum-gate-tilezero/examples/basic_gate.rs new file mode 100644 index 00000000..e88ad09f --- /dev/null +++ b/crates/cognitum-gate-tilezero/examples/basic_gate.rs @@ -0,0 +1,87 @@ +//! Basic Coherence Gate Example +//! +//! This example demonstrates: +//! - Creating a TileZero arbiter +//! - Evaluating an action +//! - Verifying the permit token +//! +//! Run with: cargo run --example basic_gate + +use cognitum_gate_tilezero::{ + ActionContext, ActionMetadata, ActionTarget, GateDecision, GateThresholds, TileZero, +}; +use std::collections::HashMap; + +#[tokio::main] +async fn main() -> Result<(), Box> { + println!("=== Cognitum Coherence Gate - Basic Example ===\n"); + + // Create TileZero with default thresholds + let thresholds = GateThresholds::default(); + let tilezero = TileZero::new(thresholds); + + println!("TileZero initialized with thresholds:"); + println!(" Min cut: {}", tilezero.thresholds().min_cut); + println!(" Max shift: {}", tilezero.thresholds().max_shift); + println!(" Deny threshold (tau_deny): {}", tilezero.thresholds().tau_deny); + println!(" Permit threshold (tau_permit): {}", tilezero.thresholds().tau_permit); + println!(); + + // Create an action context + let action = ActionContext { + action_id: "config-push-001".to_string(), + action_type: "config_change".to_string(), + target: ActionTarget { + device: Some("router-west-03".to_string()), + path: Some("/network/interfaces/eth0".to_string()), + extra: HashMap::new(), + }, + context: ActionMetadata { + agent_id: "ops-agent-12".to_string(), + session_id: Some("sess-abc123".to_string()), + prior_actions: vec![], + urgency: "normal".to_string(), + }, + }; + + println!("Evaluating action:"); + println!(" ID: {}", action.action_id); + println!(" Type: {}", action.action_type); + println!(" Agent: {}", action.context.agent_id); + println!(" Target: {:?}", action.target.device); + println!(); + + // Evaluate the action + let token = tilezero.decide(&action).await; + + // Display result + match token.decision { + GateDecision::Permit => { + println!("Decision: PERMIT"); + println!(" The action is allowed to proceed."); + } + GateDecision::Defer => { + println!("Decision: DEFER"); + println!(" Human review required."); + } + GateDecision::Deny => { + println!("Decision: DENY"); + println!(" Action blocked due to safety concerns."); + } + } + + println!("\nToken details:"); + println!(" Sequence: {}", token.sequence); + println!(" Valid until: {} ns", token.timestamp + token.ttl_ns); + println!(" Witness hash: {:02x?}", &token.witness_hash[..8]); + + // Verify the token + let verifier = tilezero.verifier(); + match verifier.verify(&token) { + Ok(()) => println!("\nToken signature: VALID"), + Err(e) => println!("\nToken signature: INVALID - {:?}", e), + } + + println!("\n=== Example Complete ==="); + Ok(()) +} diff --git a/crates/cognitum-gate-tilezero/examples/human_escalation.rs b/crates/cognitum-gate-tilezero/examples/human_escalation.rs new file mode 100644 index 00000000..5a606910 --- /dev/null +++ b/crates/cognitum-gate-tilezero/examples/human_escalation.rs @@ -0,0 +1,115 @@ +//! Human Escalation Example +//! +//! This example demonstrates the hybrid agent/human workflow: +//! - Detecting when human review is needed (DEFER) +//! - Presenting the escalation context +//! +//! Run with: cargo run --example human_escalation + +use cognitum_gate_tilezero::{ + ActionContext, ActionMetadata, ActionTarget, GateDecision, GateThresholds, TileZero, +}; +use std::collections::HashMap; +use std::io::{self, Write}; + +#[tokio::main] +async fn main() -> Result<(), Box> { + println!("=== Cognitum Coherence Gate - Human Escalation Example ===\n"); + + // Create TileZero with conservative thresholds to trigger DEFER + let thresholds = GateThresholds { + min_cut: 15.0, // Higher threshold + max_shift: 0.3, // Lower tolerance for shift + tau_deny: 0.01, + tau_permit: 100.0, + permit_ttl_ns: 300_000_000_000, // 5 minutes + theta_uncertainty: 10.0, + theta_confidence: 3.0, + }; + let tilezero = TileZero::new(thresholds); + + // Simulate a risky action + let action = ActionContext { + action_id: "critical-update-042".to_string(), + action_type: "database_migration".to_string(), + target: ActionTarget { + device: Some("production-db-primary".to_string()), + path: Some("/data/schema".to_string()), + extra: HashMap::new(), + }, + context: ActionMetadata { + agent_id: "migration-agent".to_string(), + session_id: Some("migration-session".to_string()), + prior_actions: vec![], + urgency: "high".to_string(), + }, + }; + + println!("Evaluating high-risk action:"); + println!(" Type: {}", action.action_type); + println!(" Target: {:?}", action.target.device); + println!(); + + // Evaluate - this may trigger DEFER due to conservative thresholds + let token = tilezero.decide(&action).await; + + if token.decision == GateDecision::Defer { + println!("Decision: DEFER - Human review required\n"); + + // Display escalation context + println!("┌─────────────────────────────────────────────────────┐"); + println!("│ HUMAN DECISION REQUIRED │"); + println!("├─────────────────────────────────────────────────────┤"); + println!("│ Action: {} │", action.action_id); + println!("│ Target: {:?} │", action.target.device); + println!("│ │"); + println!("│ Why deferred: │"); + println!("│ • High-risk target (production database) │"); + println!("│ • Action type: database_migration │"); + println!("│ │"); + println!("│ Options: │"); + println!("│ [1] APPROVE - Allow the action │"); + println!("│ [2] DENY - Block the action │"); + println!("│ [3] ESCALATE - Need more review │"); + println!("└─────────────────────────────────────────────────────┘"); + println!(); + + // Get human input + print!("Enter your decision (1/2/3): "); + io::stdout().flush()?; + + let mut input = String::new(); + io::stdin().read_line(&mut input)?; + + match input.trim() { + "1" => { + println!("\nYou chose: APPROVE"); + println!("In production, this would:"); + println!(" - Record the approval with your identity"); + println!(" - Generate a new PERMIT token"); + println!(" - Log the decision to the audit trail"); + } + "2" => { + println!("\nYou chose: DENY"); + println!("In production, this would:"); + println!(" - Record the denial with your identity"); + println!(" - Block the action permanently"); + println!(" - Alert the requesting agent"); + } + _ => { + println!("\nYou chose: ESCALATE"); + println!("In production, this would:"); + println!(" - Forward to Tier 3 (policy team)"); + println!(" - Extend the timeout"); + println!(" - Provide additional context"); + } + } + + } else { + println!("Decision: {:?}", token.decision); + println!("(Automatic - no human review needed)"); + } + + println!("\n=== Example Complete ==="); + Ok(()) +} diff --git a/crates/cognitum-gate-tilezero/examples/receipt_audit.rs b/crates/cognitum-gate-tilezero/examples/receipt_audit.rs new file mode 100644 index 00000000..8776bb7d --- /dev/null +++ b/crates/cognitum-gate-tilezero/examples/receipt_audit.rs @@ -0,0 +1,99 @@ +//! Receipt Audit Trail Example +//! +//! This example demonstrates: +//! - Generating multiple decisions +//! - Accessing the receipt log +//! - Verifying hash chain integrity +//! +//! Run with: cargo run --example receipt_audit + +use cognitum_gate_tilezero::{ + ActionContext, ActionMetadata, ActionTarget, GateThresholds, TileZero, +}; +use std::collections::HashMap; + +#[tokio::main] +async fn main() -> Result<(), Box> { + println!("=== Cognitum Coherence Gate - Receipt Audit Example ===\n"); + + let tilezero = TileZero::new(GateThresholds::default()); + + // Generate several decisions + let actions = vec![ + ("action-001", "config_read", "agent-1", "router-1"), + ("action-002", "config_write", "agent-1", "router-1"), + ("action-003", "restart", "agent-2", "service-a"), + ("action-004", "deploy", "agent-3", "cluster-prod"), + ("action-005", "rollback", "agent-3", "cluster-prod"), + ]; + + println!("Generating decisions...\n"); + + for (id, action_type, agent, target) in &actions { + let action = ActionContext { + action_id: id.to_string(), + action_type: action_type.to_string(), + target: ActionTarget { + device: Some(target.to_string()), + path: None, + extra: HashMap::new(), + }, + context: ActionMetadata { + agent_id: agent.to_string(), + session_id: None, + prior_actions: vec![], + urgency: "normal".to_string(), + }, + }; + + let token = tilezero.decide(&action).await; + println!(" {} -> {:?}", id, token.decision); + } + + println!("\n--- Audit Trail ---\n"); + + // Verify the hash chain + match tilezero.verify_receipt_chain().await { + Ok(()) => println!("Hash chain: VERIFIED"), + Err(e) => println!("Hash chain: BROKEN - {:?}", e), + } + + // Display receipt summary + println!("\nReceipts:"); + println!("{:-<60}", ""); + println!("{:<10} {:<15} {:<12} {:<20}", "Seq", "Action", "Decision", "Hash (first 8)"); + println!("{:-<60}", ""); + + for seq in 0..actions.len() as u64 { + if let Some(receipt) = tilezero.get_receipt(seq).await { + let hash = receipt.hash(); + let hash_hex = hex::encode(&hash[..4]); + println!( + "{:<10} {:<15} {:<12} {}...", + receipt.sequence, + receipt.token.action_id, + format!("{:?}", receipt.token.decision), + hash_hex + ); + } + } + + println!("{:-<60}", ""); + + // Export for compliance + println!("\nExporting audit log..."); + + let audit_json = tilezero.export_receipts_json().await?; + let filename = format!("audit_log_{}.json", + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() + ); + + println!(" Would write {} bytes to {}", audit_json.len(), filename); + println!(" (Skipping actual file write in example)"); + + println!("\n=== Example Complete ==="); + Ok(()) +} diff --git a/crates/cognitum-gate-tilezero/src/lib.rs b/crates/cognitum-gate-tilezero/src/lib.rs index 8a2f9440..4b2a79e4 100644 --- a/crates/cognitum-gate-tilezero/src/lib.rs +++ b/crates/cognitum-gate-tilezero/src/lib.rs @@ -281,6 +281,28 @@ impl TileZero { pub fn verifier(&self) -> Verifier { self.permit_state.verifier() } + + /// Get the thresholds configuration + pub fn thresholds(&self) -> &GateThresholds { + &self.thresholds + } + + /// Verify the entire receipt chain + pub async fn verify_receipt_chain(&self) -> Result<(), ChainVerifyError> { + let log = self.receipt_log.read().await; + let len = log.len(); + if len == 0 { + return Ok(()); + } + log.verify_chain_to(len as u64 - 1) + } + + /// Export all receipts as JSON + pub async fn export_receipts_json(&self) -> Result { + let log = self.receipt_log.read().await; + let receipts: Vec<&WitnessReceipt> = log.iter().collect(); + serde_json::to_string_pretty(&receipts) + } } /// Result of replaying a decision diff --git a/crates/cognitum-gate-tilezero/src/receipt.rs b/crates/cognitum-gate-tilezero/src/receipt.rs index 372b2c90..3b103f84 100644 --- a/crates/cognitum-gate-tilezero/src/receipt.rs +++ b/crates/cognitum-gate-tilezero/src/receipt.rs @@ -194,6 +194,11 @@ impl ReceiptLog { pub fn is_empty(&self) -> bool { self.receipts.is_empty() } + + /// Iterate over receipts + pub fn iter(&self) -> impl Iterator { + self.receipts.values() + } } impl Default for ReceiptLog { diff --git a/packages/cognitum-gate-wasm/examples/basic-usage.ts b/packages/cognitum-gate-wasm/examples/basic-usage.ts new file mode 100644 index 00000000..3b83f644 --- /dev/null +++ b/packages/cognitum-gate-wasm/examples/basic-usage.ts @@ -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); diff --git a/packages/cognitum-gate-wasm/examples/express-middleware.ts b/packages/cognitum-gate-wasm/examples/express-middleware.ts new file mode 100644 index 00000000..dd9dd4ef --- /dev/null +++ b/packages/cognitum-gate-wasm/examples/express-middleware.ts @@ -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); diff --git a/packages/cognitum-gate-wasm/examples/react-hook.tsx b/packages/cognitum-gate-wasm/examples/react-hook.tsx new file mode 100644 index 00000000..971c846c --- /dev/null +++ b/packages/cognitum-gate-wasm/examples/react-hook.tsx @@ -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; + pendingActions: Map; +} + +const GateContext = createContext(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(null); + const [isReady, setIsReady] = useState(false); + const [pendingActions] = useState(new Map()); + + 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 ( + + {children} + + ); +} + +// 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(null); + const [lastResult, setLastResult] = useState(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 ( + + ); +} + +// Example App +export function ExampleApp() { + const [status, setStatus] = useState(''); + + return ( + +
+

Cognitum Gate - React Example

+ + { + setStatus(`✅ Permitted! Token: ${token.slice(0, 20)}...`); + }} + onDeferred={(seq) => { + setStatus(`⏸️ Deferred - Human review needed (seq: ${seq})`); + }} + onDenied={(reason) => { + setStatus(`❌ Denied: ${reason}`); + }} + > + Deploy to Production + + +

{status}

+ + +
+
+ ); +} + +// Audit Log Component +function AuditLog() { + const { gate, isReady } = useGate(); + const [receipts, setReceipts] = useState([]); + + useEffect(() => { + if (isReady && gate) { + gate.getReceipts(0, 10).then(setReceipts); + } + }, [gate, isReady]); + + return ( +
+

Recent Decisions

+ + + + + + + + + + + {receipts.map((r) => ( + + + + + + + ))} + +
SeqActionDecisionTime
{r.sequence}{r.token.actionId}{r.token.decision}{new Date(r.token.timestamp / 1_000_000).toLocaleString()}
+
+ ); +} + +export default ExampleApp;