npm package: @longarc/mdash
Description: Cryptographic attestation protocol for autonomous AI agents
Author: Long Arc Studios
Latest version: 3.1.3

# mdash v3.0

> **"The best defense is the fastest seal."**

Accountability infrastructure for autonomous AI agents. Cryptographic attestation + warrant evaluation in a single protocol — from sub-millisecond commitments to zero-knowledge proofs.

## Architecture

```
┌─────────────────────────────────────────────────────────────────────────┐
│                         APPLICATION LAYER                                │
│                            Kiwi │ Enterprise                            │
├─────────────────────────────────────────────────────────────────────────┤
│                          mdash v3.0 PROTOCOL                             │
│       Warrants │ Physics │ Checkpoints │ SCA │ MCCA │ Recovery          │
├─────────────────────────────────────────────────────────────────────────┤
│                      THREE-LAYER ATTESTATION                             │
│  L1: Commitment (<1ms) │ L2: TEE (<10ms) │ L3: ZK Proofs (async)        │
├─────────────────────────────────────────────────────────────────────────┤
│                        CRYPTOGRAPHIC CORE                                │
│              SHA-256 │ HMAC-SHA256 │ HKDF │ Web Crypto API              │
└─────────────────────────────────────────────────────────────────────────┘
```

## Installation

```bash
npm install @longarcstudios/mdash
```

## Quick Start

```typescript
import { createMdash } from '@longarcstudios/mdash';

// Initialize protocol with all layers
const mdash = createMdash({
  sealKey: process.env.MDASH_SEAL_KEY!,
  teePlatform: 'simulated', // 'nitro' | 'sgx' | 'simulated'
  enableZKProofs: true,
  enableMCCA: true,
});
await mdash.initialize();

// Pre-stage a warrant
await mdash.prestageWarrant({
  agentId: 'trading-bot-001',
  policyId: 'financial-transfer-v2',
  tier: 'T2',
  constraints: { maxAmount: 10000 },
  durationMs: 30 * 24 * 60 * 60 * 1000,
  issuedBy: 'admin@example.com',
});

// Execute with full three-layer attestation
const result = await mdash.execute({
  agentId: 'trading-bot-001',
  action: 'transfer',
  actionParams: { amount: 500, destination: 'account-123' },
  execute: async () => {
    return { success: true, txId: 'tx-abc123' };
  },
  generateZKProof: true, // For accountability proofs
});

console.log(result.attestation.platform); // 'simulated' | 'nitro' | 'sgx'
console.log(result.zkProof?.status);       // 'queued' -> 'verified'
```

## Full Accountability Lifecycle

The `AccountabilityEngine` is the simplest way to add accountability to any agent. One class: authorize before execution, attest after.

```typescript
import { AccountabilityEngine } from '@longarc/mdash';

const engine = new AccountabilityEngine();
await engine.initialize('your-seal-key-minimum-32-characters');

// Issue a warrant — define what the agent is authorized to do
await engine.issueWarrant('data-agent', {
  allowedActions: ['query-database', 'read-file', 'summarize'],
  forbiddenActions: ['delete-database', 'execute-shell'],
  ttlMs: 60000
});

// Authorized action → executes and gets cryptographic attestation
const result = await engine.executeAction('data-agent', 'query-database', {
  table: 'users', limit: 100
});
console.log(result.executed);  // true
console.log(result.verified);  // true — seal is cryptographically valid

// Unauthorized action → denied before execution
const denied = await engine.executeAction('data-agent', 'delete-database', {
  target: 'users'
});
console.log(denied.executed);   // false
console.log(denied.violation);  // { type: 'FORBIDDEN_ACTION', ... }

// Full audit trail
const audit = engine.getAuditSummary();
console.log(audit.authorized);  // 1
console.log(audit.denied);      // 1
```

For advanced use cases (speculative warrants, TEE attestation, ZK proofs), use `MdashProtocol` directly.

## Three-Layer Attestation Model

### L1: Commitment Layer (<1ms)
Instant cryptographic sealing for every operation.

```typescript
// Direct commitment
const seal = await mdash.commitment.commit(data, 'operation-id');

// Verify with O(log n) proof
const valid = await mdash.commitment.verify(seal);
```

### L2: TEE Attestation (<10ms)
Hardware-rooted attestation via AWS Nitro Enclaves or Intel SGX.

```typescript
// Attest with hardware TEE
const attestation = await mdash.tee.attest(data, commitmentId);

// Verify remote attestation
const verifier = new TEEVerifier();
verifier.trustMeasurement(attestation.measurement);
const result = await verifier.verifyRemote(attestation);
```

**Supported Platforms:**
| Platform | Memory Encryption | Remote Attestation | Key Sealing |
|----------|------------------|-------------------|-------------|
| AWS Nitro | ✓ | ✓ (PCR) | ✓ |
| Intel SGX | ✓ | ✓ (Quote) | ✓ |
| Simulated | ✗ | ✓ | HMAC |

### L3: ZK Proofs (async)
Mathematically bulletproof attestation for disputes and accountability.

```typescript
// Request proof (returns immediately)
const zkDoc = await mdash.zk.requestProof({
  type: 'action_compliance',
  statement: {
    description: 'Prove action met constraints',
    claim: { action, warrant, result },
  },
  priority: 'high',
});

// Wait for completion
const completed = await mdash.zk.waitForProof(zkDoc.id, 30000);
```

**Circuit Types:**
| Circuit | Use Case | Est. Proving Time |
|---------|----------|-------------------|
| commitment_inclusion | Prove data in Merkle tree | ~500ms |
| warrant_validity | Prove warrant was valid | ~1s |
| checkpoint_chain | Prove checkpoint sequence | ~5s |
| action_compliance | Prove action met constraints | ~1.5s |
| audit_trail | Complete audit proof | ~20s |

## MCCA v3 (Manifold-Constrained Context Architecture)

Based on DeepSeek's research on constrained context windows.

```typescript
// Add context with influence tracking
const fragment = await mdash.mcca.addFragment({
  content: { message: 'User request' },
  source_class: 'user',
  region: 'task',
  token_count: 50,
});

// Check context health
const health = await mdash.contextWindow.getHealth();
console.log(health.drift.severity); // 'none' | 'low' | 'medium' | 'high' | 'critical'

// Generate manifold commitment proof
const proof = await mdash.mcca.generateCommitmentProof();
```

**Influence Budget (Default):**
| Source Class | Budget | Description |
|--------------|--------|-------------|
| system | 30% | System prompts, policies |
| user | 35% | User messages |
| agent | 15% | Agent-generated content |
| tool | 10% | Tool outputs |
| memory | 5% | Retrieved memories |
| external | 5% | External APIs, web content |

## Latency SLAs

| Operation | P50 | P99 | Breach Action |
|-----------|-----|-----|---------------|
| L1 Commitment | <0.5ms | <1ms | Log warning |
| L2 TEE Attestation | <5ms | <10ms | Fallback to simulated |
| Warrant Activation | <5ms | <10ms | Reject if exceeded |
| Checkpoint Creation | <0.5ms | <1ms | Log warning |
| ZK Proof | 100ms-20s | async | Queue with priority |

## Accountability Proofs

Generate accountability-grade proofs:

```typescript
import { InsuranceClaimProof } from '@longarcstudios/mdash';

const helper = new InsuranceClaimProof(mdash.zk);

const claimProof = await helper.generateClaim({
  claimId: 'CLM-2026-001',
  policyId: 'POL-ENTERPRISE-001',
  incidentDescription: 'Unauthorized transaction',
  warrantId: 'w-12345678',
  checkpointIds: ['cp-001', 'cp-002'],
  actionDetails: { type: 'transfer', amount: 50000 },
  amount: 50000,
  currency: 'USD',
});

// Wait for proof generation
const verified = await mdash.zk.waitForProof(claimProof.id, 60000);
```

## Warrant System

Three-tier warrant hierarchy with speculative issuance:

```typescript
// T1: Low risk (auto-approve)
// T2: Medium risk (policy-based)
// T3: High risk (manual approval required)

const warrant = await mdash.prestageWarrant({
  agentId: 'agent-001',
  policyId: 'api-access-v1',
  tier: 'T2',
  constraints: {
    maxCalls: 1000,
    maxAmount: 10000,
    allowedDomains: ['api.example.com'],
  },
  durationMs: 24 * 60 * 60 * 1000, // 24 hours
  issuedBy: 'admin@company.com',
});

// Revoke with audit trail
await mdash.revokeWarrant(warrant.id, 'policy violation', {
  type: 'user',
  id: 'admin@company.com',
});
```

## Testing

```bash
npm test              # Run all tests
npm run test:watch    # Watch mode
npm run test:coverage # Coverage report
```

## API Reference

### MdashProtocol

| Method | Description |
|--------|-------------|
| `initialize()` | Initialize all engines |
| `execute(params)` | Execute action with full attestation |
| `prestageWarrant(params)` | Pre-stage speculative warrant |
| `revokeWarrant(id, reason, actor)` | Revoke warrant |
| `generateAuditProof(params)` | Generate ZK audit proof |
| `getStats()` | Get comprehensive statistics |
| `shutdown()` | Clean shutdown |

### Engines

| Engine | Access | Purpose |
|--------|--------|---------|
| `commitment` | `mdash.commitment` | L1 Merkle sealing |
| `warrant` | `mdash.warrant` | Warrant lifecycle |
| `checkpoint` | `mdash.checkpoint` | Event-driven checkpoints |
| `physics` | `mdash.physics` | Constraint validation |
| `tee` | `mdash.tee` | L2 hardware attestation |
| `zk` | `mdash.zk` | L3 ZK proofs |
| `mcca` | `mdash.mcca` | Context architecture |

## Version

```typescript
import { VERSION } from '@longarcstudios/mdash';

console.log(VERSION);
// {
//   protocol: '3.0.0',
//   codename: 'Sealed Execution',
//   releaseDate: '2026-01',
//   features: [...]
// }
```

## License

MIT © Long Arc Studios

---

*Governance without control. Complexity without chaos.* 🫡