@longarc/mdash 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +278 -0
  2. package/dist/checkpoint/engine.d.ts +208 -0
  3. package/dist/checkpoint/engine.d.ts.map +1 -0
  4. package/dist/checkpoint/engine.js +369 -0
  5. package/dist/checkpoint/engine.js.map +1 -0
  6. package/dist/context/engine.d.ts +197 -0
  7. package/dist/context/engine.d.ts.map +1 -0
  8. package/dist/context/engine.js +392 -0
  9. package/dist/context/engine.js.map +1 -0
  10. package/dist/core/commitment.d.ts +154 -0
  11. package/dist/core/commitment.d.ts.map +1 -0
  12. package/dist/core/commitment.js +305 -0
  13. package/dist/core/commitment.js.map +1 -0
  14. package/dist/core/crypto.d.ts +100 -0
  15. package/dist/core/crypto.d.ts.map +1 -0
  16. package/dist/core/crypto.js +243 -0
  17. package/dist/core/crypto.js.map +1 -0
  18. package/dist/index.d.ts +121 -0
  19. package/dist/index.d.ts.map +1 -0
  20. package/dist/index.js +234 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/mcca/engine.d.ts +260 -0
  23. package/dist/mcca/engine.d.ts.map +1 -0
  24. package/dist/mcca/engine.js +518 -0
  25. package/dist/mcca/engine.js.map +1 -0
  26. package/dist/physics/engine.d.ts +165 -0
  27. package/dist/physics/engine.d.ts.map +1 -0
  28. package/dist/physics/engine.js +371 -0
  29. package/dist/physics/engine.js.map +1 -0
  30. package/dist/tee/engine.d.ts +285 -0
  31. package/dist/tee/engine.d.ts.map +1 -0
  32. package/dist/tee/engine.js +505 -0
  33. package/dist/tee/engine.js.map +1 -0
  34. package/dist/warrant/engine.d.ts +195 -0
  35. package/dist/warrant/engine.d.ts.map +1 -0
  36. package/dist/warrant/engine.js +409 -0
  37. package/dist/warrant/engine.js.map +1 -0
  38. package/dist/zk/engine.d.ts +243 -0
  39. package/dist/zk/engine.d.ts.map +1 -0
  40. package/dist/zk/engine.js +489 -0
  41. package/dist/zk/engine.js.map +1 -0
  42. package/package.json +25 -0
  43. package/src/__tests__/phase1.test.ts +1120 -0
  44. package/src/__tests__/phase2-4.test.ts +898 -0
  45. package/src/checkpoint/engine.ts +532 -0
  46. package/src/context/engine.ts +598 -0
  47. package/src/core/commitment.ts +438 -0
  48. package/src/core/crypto.ts +304 -0
  49. package/src/index.ts +320 -0
  50. package/src/mcca/engine.ts +778 -0
  51. package/src/physics/engine.ts +563 -0
  52. package/src/tee/engine.ts +810 -0
  53. package/src/warrant/engine.ts +625 -0
  54. package/src/zk/engine.ts +730 -0
  55. package/tsconfig.json +21 -0
@@ -0,0 +1,898 @@
1
+ /**
2
+ * mdash v3.0 - Phase 2-4 Test Suite
3
+ *
4
+ * Tests for:
5
+ * - L2 TEE Attestation Engine
6
+ * - L3 ZK Proofs Engine
7
+ * - MCCA v3 Engine
8
+ *
9
+ * @version 3.0.0
10
+ */
11
+
12
+ import { describe, it, expect, beforeAll, afterAll } from 'vitest';
13
+ import { CommitmentEngine } from '../core/commitment.js';
14
+ import { TEEAttestationEngine, TEEVerifier, AttestationBridge, PLATFORM_CAPABILITIES } from '../tee/engine.js';
15
+ import { ZKProofsEngine, ClaimBuilder, InsuranceClaimProof, CIRCUIT_CONFIGS } from '../zk/engine.js';
16
+ import { MCCAEngine, ContextWindowManager, DEFAULT_INFLUENCE_BUDGET } from '../mcca/engine.js';
17
+ import { generateTimestamp } from '../core/crypto.js';
18
+
19
+ const TEST_SEAL_KEY = 'test-seal-key-phase-2-4-v3.0.0';
20
+
21
+ // ============================================================================
22
+ // L2 TEE ATTESTATION TESTS
23
+ // ============================================================================
24
+
25
+ describe('L2 TEE Attestation Engine', () => {
26
+ let commitmentEngine: CommitmentEngine;
27
+ let teeEngine: TEEAttestationEngine;
28
+
29
+ beforeAll(async () => {
30
+ commitmentEngine = new CommitmentEngine();
31
+ await commitmentEngine.initialize(TEST_SEAL_KEY);
32
+
33
+ teeEngine = new TEEAttestationEngine(commitmentEngine, {
34
+ platform: 'simulated',
35
+ attestationTTL: 60000,
36
+ enableCache: true,
37
+ cacheTTL: 30000,
38
+ rateLimit: 1000,
39
+ });
40
+ await teeEngine.initialize(TEST_SEAL_KEY);
41
+ });
42
+
43
+ describe('Platform Capabilities', () => {
44
+ it('should define capabilities for all platforms', () => {
45
+ expect(PLATFORM_CAPABILITIES.nitro).toBeDefined();
46
+ expect(PLATFORM_CAPABILITIES.sgx).toBeDefined();
47
+ expect(PLATFORM_CAPABILITIES.simulated).toBeDefined();
48
+ });
49
+
50
+ it('should report correct capabilities for simulated platform', () => {
51
+ const caps = teeEngine.getCapabilities();
52
+ expect(caps.remoteAttestation).toBe(true);
53
+ expect(caps.keySealing).toBe(true);
54
+ });
55
+
56
+ it('nitro should support PCR', () => {
57
+ expect(PLATFORM_CAPABILITIES.nitro.pcrSupport).toBe(true);
58
+ });
59
+
60
+ it('sgx should support quote generation', () => {
61
+ expect(PLATFORM_CAPABILITIES.sgx.quoteGeneration).toBe(true);
62
+ });
63
+ });
64
+
65
+ describe('Attestation Generation', () => {
66
+ it('should generate attestation document', async () => {
67
+ const data = { action: 'transfer', amount: 100 };
68
+ const commitmentId = 'test-commitment-001';
69
+
70
+ const attestation = await teeEngine.attest(data, commitmentId);
71
+
72
+ expect(attestation.id).toBeTruthy();
73
+ expect(attestation.platform).toBe('simulated');
74
+ expect(attestation.status).toBe('verified');
75
+ expect(attestation.attested_data).toBeTruthy();
76
+ expect(attestation.measurement).toBeTruthy();
77
+ expect(attestation.seal).toBeTruthy();
78
+ });
79
+
80
+ it('should attest within 10ms target (simulated)', async () => {
81
+ const data = { test: 'latency', timestamp: Date.now() };
82
+ const commitmentId = 'latency-test-001';
83
+
84
+ const startTime = performance.now();
85
+ await teeEngine.attest(data, commitmentId);
86
+ const elapsed = performance.now() - startTime;
87
+
88
+ // Simulated should be very fast
89
+ expect(elapsed).toBeLessThan(50); // Allow some margin
90
+ });
91
+
92
+ it('should use cache for identical attestations', async () => {
93
+ const data = { cacheTest: true, value: 42 };
94
+ const commitmentId = 'cache-test-001';
95
+
96
+ // First attestation
97
+ await teeEngine.attest(data, commitmentId);
98
+ const statsAfterFirst = teeEngine.getStats();
99
+
100
+ // Second attestation (should hit cache)
101
+ await teeEngine.attest(data, commitmentId);
102
+ const statsAfterSecond = teeEngine.getStats();
103
+
104
+ expect(statsAfterSecond.cacheHits).toBe(statsAfterFirst.cacheHits + 1);
105
+ });
106
+
107
+ it('should include platform-specific attestation', async () => {
108
+ const attestation = await teeEngine.attest(
109
+ { test: 'platform' },
110
+ 'platform-test-001'
111
+ );
112
+
113
+ expect(attestation.platform_attestation).toBeDefined();
114
+ // Simulated attestation structure
115
+ const simAttest = attestation.platform_attestation as any;
116
+ expect(simAttest.type).toBe('simulated');
117
+ expect(simAttest.simulated_pcrs).toBeDefined();
118
+ });
119
+ });
120
+
121
+ describe('Attestation Verification', () => {
122
+ it('should verify valid attestation', async () => {
123
+ const attestation = await teeEngine.attest(
124
+ { verify: 'test' },
125
+ 'verify-test-001'
126
+ );
127
+
128
+ const result = await teeEngine.verify(attestation);
129
+
130
+ expect(result.valid).toBe(true);
131
+ expect(result.errors).toHaveLength(0);
132
+ });
133
+
134
+ it('should detect expired attestation', async () => {
135
+ const attestation = await teeEngine.attest(
136
+ { expire: 'test' },
137
+ 'expire-test-001'
138
+ );
139
+
140
+ // Manually expire the attestation
141
+ (attestation as any).expires_at = new Date(Date.now() - 1000).toISOString();
142
+
143
+ const result = await teeEngine.verify(attestation);
144
+
145
+ expect(result.valid).toBe(false);
146
+ expect(result.errors).toContain('Attestation document expired');
147
+ });
148
+ });
149
+
150
+ describe('TEE Verifier (Remote Attestation)', () => {
151
+ it('should verify trusted measurements', async () => {
152
+ const verifier = new TEEVerifier();
153
+
154
+ const attestation = await teeEngine.attest(
155
+ { remote: 'test' },
156
+ 'remote-test-001'
157
+ );
158
+
159
+ // Trust the measurement
160
+ verifier.trustMeasurement(attestation.measurement);
161
+
162
+ const result = await verifier.verifyRemote(attestation);
163
+
164
+ expect(result.trusted).toBe(true);
165
+ });
166
+
167
+ it('should reject unknown measurements', async () => {
168
+ const verifier = new TEEVerifier();
169
+
170
+ const attestation = await teeEngine.attest(
171
+ { unknown: 'measurement' },
172
+ 'unknown-test-001'
173
+ );
174
+
175
+ // Don't trust any measurements
176
+
177
+ const result = await verifier.verifyRemote(attestation);
178
+
179
+ expect(result.trusted).toBe(false);
180
+ expect(result.reasons.some(r => r.includes('Unknown enclave measurement'))).toBe(true);
181
+ });
182
+ });
183
+
184
+ describe('Attestation Bridge (L1 <-> L2)', () => {
185
+ it('should commit and attest in one operation', async () => {
186
+ const bridge = new AttestationBridge(teeEngine, commitmentEngine);
187
+ const data = { bridgeTest: true, value: 'hello' };
188
+
189
+ const { commitment, attestation } = await bridge.commitAndAttest(
190
+ data,
191
+ 'bridge-test-001'
192
+ );
193
+
194
+ expect(commitment).toBeTruthy();
195
+ expect(commitment.merkleRoot).toBeTruthy();
196
+ expect(attestation).toBeTruthy();
197
+ expect(attestation.commitment_id).toBe('bridge-test-001');
198
+ });
199
+
200
+ it('should verify both layers', async () => {
201
+ const bridge = new AttestationBridge(teeEngine, commitmentEngine);
202
+ const data = { verifyBoth: true, timestamp: Date.now() };
203
+
204
+ const { commitment, attestation } = await bridge.commitAndAttest(
205
+ data,
206
+ 'verify-both-001'
207
+ );
208
+
209
+ const result = await bridge.verifyBoth(commitment, attestation);
210
+
211
+ expect(result.l1Valid).toBe(true);
212
+ expect(result.l2Valid).toBe(true);
213
+ expect(result.crossLayerValid).toBe(true);
214
+ expect(result.errors).toHaveLength(0);
215
+ });
216
+ });
217
+
218
+ describe('Statistics', () => {
219
+ it('should track attestation metrics', () => {
220
+ const stats = teeEngine.getStats();
221
+
222
+ expect(stats.platform).toBe('simulated');
223
+ expect(stats.attestations).toBeGreaterThan(0);
224
+ expect(stats.avgLatencyMs).toBeGreaterThan(0);
225
+ });
226
+ });
227
+ });
228
+
229
+ // ============================================================================
230
+ // L3 ZK PROOFS TESTS
231
+ // ============================================================================
232
+
233
+ describe('L3 ZK Proofs Engine', () => {
234
+ let commitmentEngine: CommitmentEngine;
235
+ let zkEngine: ZKProofsEngine;
236
+
237
+ beforeAll(async () => {
238
+ commitmentEngine = new CommitmentEngine();
239
+ await commitmentEngine.initialize(TEST_SEAL_KEY);
240
+
241
+ zkEngine = new ZKProofsEngine(commitmentEngine, 4);
242
+ await zkEngine.initialize(TEST_SEAL_KEY);
243
+ });
244
+
245
+ afterAll(() => {
246
+ zkEngine.stopProcessing();
247
+ });
248
+
249
+ describe('Circuit Configurations', () => {
250
+ it('should define all circuit types', () => {
251
+ expect(CIRCUIT_CONFIGS.commitment_inclusion).toBeDefined();
252
+ expect(CIRCUIT_CONFIGS.warrant_validity).toBeDefined();
253
+ expect(CIRCUIT_CONFIGS.checkpoint_chain).toBeDefined();
254
+ expect(CIRCUIT_CONFIGS.action_compliance).toBeDefined();
255
+ expect(CIRCUIT_CONFIGS.audit_trail).toBeDefined();
256
+ expect(CIRCUIT_CONFIGS.custom).toBeDefined();
257
+ });
258
+
259
+ it('should have valid circuit configurations', () => {
260
+ for (const [type, config] of Object.entries(CIRCUIT_CONFIGS)) {
261
+ expect(config.name).toBeTruthy();
262
+ expect(config.numPublicInputs).toBeGreaterThan(0);
263
+ expect(config.estimatedGates).toBeGreaterThan(0);
264
+ expect(config.estimatedProvingTimeMs).toBeGreaterThan(0);
265
+ }
266
+ });
267
+ });
268
+
269
+ describe('Proof Request', () => {
270
+ it('should queue proof request', async () => {
271
+ const request = {
272
+ type: 'commitment_inclusion' as const,
273
+ statement: {
274
+ description: 'Prove data inclusion',
275
+ claim: { data: 'test', root: 'merkle-root' },
276
+ },
277
+ priority: 'normal' as const,
278
+ };
279
+
280
+ const document = await zkEngine.requestProof(request);
281
+
282
+ expect(document.id).toBeTruthy();
283
+ expect(document.status).toBe('queued');
284
+ expect(document.type).toBe('commitment_inclusion');
285
+ expect(document.statement.claim_hash).toBeTruthy();
286
+ });
287
+
288
+ it('should process proof in background', async () => {
289
+ const request = {
290
+ type: 'warrant_validity' as const,
291
+ statement: {
292
+ description: 'Prove warrant was valid',
293
+ claim: {
294
+ warrant: { id: 'w-12345678' },
295
+ timestamp: generateTimestamp(),
296
+ agent_id: 'agent-001',
297
+ action: 'transfer',
298
+ },
299
+ },
300
+ priority: 'high' as const,
301
+ };
302
+
303
+ const document = await zkEngine.requestProof(request);
304
+
305
+ // Wait for processing
306
+ const completed = await zkEngine.waitForProof(document.id, 5000);
307
+
308
+ expect(completed.status).toBe('verified');
309
+ expect(completed.proof).toBeTruthy();
310
+ expect(completed.proof!.proof).toBeTruthy();
311
+ expect(completed.proof!.public_inputs.length).toBeGreaterThan(0);
312
+ });
313
+
314
+ it('should handle high priority proofs first', async () => {
315
+ // Queue low priority
316
+ const lowPriority = await zkEngine.requestProof({
317
+ type: 'custom',
318
+ statement: { description: 'Low priority', claim: { priority: 'low' } },
319
+ priority: 'low',
320
+ });
321
+
322
+ // Queue high priority
323
+ const highPriority = await zkEngine.requestProof({
324
+ type: 'custom',
325
+ statement: { description: 'High priority', claim: { priority: 'high' } },
326
+ priority: 'high',
327
+ });
328
+
329
+ // High priority should be queued with higher priority value
330
+ const completed1 = await zkEngine.waitForProof(highPriority.id, 5000);
331
+ const completed2 = await zkEngine.waitForProof(lowPriority.id, 5000);
332
+
333
+ expect(completed1.status).toBe('verified');
334
+ expect(completed2.status).toBe('verified');
335
+ });
336
+ });
337
+
338
+ describe('Claim Builder', () => {
339
+ it('should build proof request fluently', () => {
340
+ const request = new ClaimBuilder('action_compliance')
341
+ .withDescription('Test action compliance')
342
+ .withClaim('action', 'transfer')
343
+ .withClaim('amount', 1000)
344
+ .withClaim('constraints', { maxAmount: 5000 })
345
+ .withCommitments('cp-001', 'cp-002')
346
+ .withAttestations('att-001')
347
+ .build('high');
348
+
349
+ expect(request.type).toBe('action_compliance');
350
+ expect(request.statement.description).toBe('Test action compliance');
351
+ expect(request.statement.claim.action).toBe('transfer');
352
+ expect(request.commitmentIds).toContain('cp-001');
353
+ expect(request.attestationIds).toContain('att-001');
354
+ expect(request.priority).toBe('high');
355
+ });
356
+ });
357
+
358
+ describe('Proof Verification', () => {
359
+ it('should verify completed proof', async () => {
360
+ const request = {
361
+ type: 'commitment_inclusion' as const,
362
+ statement: {
363
+ description: 'Verify test',
364
+ claim: { test: 'verify' },
365
+ },
366
+ };
367
+
368
+ const document = await zkEngine.requestProof(request);
369
+ const completed = await zkEngine.waitForProof(document.id, 5000);
370
+
371
+ const result = await zkEngine.verifyProof(completed);
372
+
373
+ expect(result.valid).toBe(true);
374
+ expect(result.errors).toHaveLength(0);
375
+ });
376
+
377
+ it('should reject expired proof', async () => {
378
+ const request = {
379
+ type: 'custom' as const,
380
+ statement: {
381
+ description: 'Expire test',
382
+ claim: { test: 'expire' },
383
+ },
384
+ };
385
+
386
+ const document = await zkEngine.requestProof(request);
387
+ const completed = await zkEngine.waitForProof(document.id, 5000);
388
+
389
+ // Manually expire
390
+ (completed as any).expires_at = new Date(Date.now() - 1000).toISOString();
391
+
392
+ const result = await zkEngine.verifyProof(completed);
393
+
394
+ expect(result.valid).toBe(false);
395
+ expect(result.errors).toContain('Proof expired');
396
+ });
397
+ });
398
+
399
+ describe('Insurance Claim Helper', () => {
400
+ it('should generate insurance claim proof', async () => {
401
+ const helper = new InsuranceClaimProof(zkEngine);
402
+
403
+ const document = await helper.generateClaim({
404
+ claimId: 'CLM-2026-001',
405
+ policyId: 'POL-ENTERPRISE-001',
406
+ incidentDescription: 'Unauthorized transaction detected',
407
+ warrantId: 'w-12345678',
408
+ checkpointIds: ['cp-001', 'cp-002', 'cp-003'],
409
+ actionDetails: {
410
+ type: 'transfer',
411
+ amount: 50000,
412
+ destination: 'unknown-account',
413
+ },
414
+ amount: 50000,
415
+ currency: 'USD',
416
+ });
417
+
418
+ expect(document.type).toBe('action_compliance');
419
+ expect(document.statement.claim.claim_id).toBe('CLM-2026-001');
420
+ expect(document.statement.claim.amount).toBe(50000);
421
+
422
+ // Wait for processing
423
+ const completed = await zkEngine.waitForProof(document.id, 5000);
424
+ expect(completed.status).toBe('verified');
425
+ });
426
+ });
427
+
428
+ describe('Statistics', () => {
429
+ it('should track proof metrics', () => {
430
+ const stats = zkEngine.getStats();
431
+
432
+ expect(stats.proofsGenerated).toBeGreaterThan(0);
433
+ expect(stats.avgProvingTimeMs).toBeGreaterThan(0);
434
+ });
435
+
436
+ it('should report queue statistics', () => {
437
+ const queueStats = zkEngine.getQueueStats();
438
+
439
+ expect(queueStats.queued).toBeGreaterThanOrEqual(0);
440
+ expect(queueStats.processing).toBeGreaterThanOrEqual(0);
441
+ });
442
+ });
443
+ });
444
+
445
+ // ============================================================================
446
+ // MCCA v3 TESTS
447
+ // ============================================================================
448
+
449
+ describe('MCCA v3 Engine', () => {
450
+ let commitmentEngine: CommitmentEngine;
451
+ let mccaEngine: MCCAEngine;
452
+
453
+ beforeAll(async () => {
454
+ commitmentEngine = new CommitmentEngine();
455
+ await commitmentEngine.initialize(TEST_SEAL_KEY);
456
+
457
+ mccaEngine = new MCCAEngine(commitmentEngine, {
458
+ budget: DEFAULT_INFLUENCE_BUDGET,
459
+ maxFragments: 100,
460
+ maxTokens: 10000,
461
+ driftThreshold: 0.3,
462
+ autoPrune: true,
463
+ });
464
+ await mccaEngine.initialize(TEST_SEAL_KEY);
465
+ });
466
+
467
+ describe('Influence Budget', () => {
468
+ it('should have valid default budget', () => {
469
+ const total = Object.values(DEFAULT_INFLUENCE_BUDGET).reduce((a, b) => a + b, 0);
470
+ expect(total).toBeCloseTo(1.0, 5);
471
+ });
472
+
473
+ it('should prioritize system and user influence', () => {
474
+ expect(DEFAULT_INFLUENCE_BUDGET.system).toBeGreaterThan(DEFAULT_INFLUENCE_BUDGET.external);
475
+ expect(DEFAULT_INFLUENCE_BUDGET.user).toBeGreaterThan(DEFAULT_INFLUENCE_BUDGET.agent);
476
+ });
477
+ });
478
+
479
+ describe('Fragment Management', () => {
480
+ it('should add fragment to manifold', async () => {
481
+ const fragment = await mccaEngine.addFragment({
482
+ content: { message: 'Hello, world!' },
483
+ source_class: 'user',
484
+ region: 'task',
485
+ token_count: 50,
486
+ });
487
+
488
+ expect(fragment.id).toBeTruthy();
489
+ expect(fragment.source_class).toBe('user');
490
+ expect(fragment.region).toBe('task');
491
+ expect(fragment.content_hash).toBeTruthy();
492
+ expect(fragment.seal).toBeTruthy();
493
+ });
494
+
495
+ it('should calculate position in manifold', async () => {
496
+ const fragment = await mccaEngine.addFragment({
497
+ content: 'Test positioning',
498
+ source_class: 'system',
499
+ region: 'core',
500
+ token_count: 100,
501
+ });
502
+
503
+ expect(fragment.position.x).toBeGreaterThan(0);
504
+ expect(fragment.position.y).toBeGreaterThan(0);
505
+ expect(fragment.position.z).toBeGreaterThan(0);
506
+ expect(fragment.position.x).toBeLessThanOrEqual(1);
507
+ expect(fragment.position.y).toBeLessThanOrEqual(1);
508
+ expect(fragment.position.z).toBeLessThanOrEqual(1);
509
+ });
510
+
511
+ it('should retrieve fragment by ID', async () => {
512
+ const fragment = await mccaEngine.addFragment({
513
+ content: 'Retrieve test',
514
+ source_class: 'agent',
515
+ region: 'history',
516
+ token_count: 30,
517
+ });
518
+
519
+ const retrieved = mccaEngine.getFragment(fragment.id);
520
+
521
+ expect(retrieved).not.toBeNull();
522
+ expect(retrieved!.id).toBe(fragment.id);
523
+ });
524
+
525
+ it('should get fragments by region', async () => {
526
+ await mccaEngine.addFragment({
527
+ content: 'Reference content',
528
+ source_class: 'memory',
529
+ region: 'reference',
530
+ token_count: 40,
531
+ });
532
+
533
+ const fragments = mccaEngine.getRegionFragments('reference');
534
+
535
+ expect(fragments.length).toBeGreaterThan(0);
536
+ expect(fragments.every(f => f.region === 'reference')).toBe(true);
537
+ });
538
+
539
+ it('should get fragments by source', async () => {
540
+ await mccaEngine.addFragment({
541
+ content: 'Tool output',
542
+ source_class: 'tool',
543
+ region: 'task',
544
+ token_count: 25,
545
+ });
546
+
547
+ const fragments = mccaEngine.getSourceFragments('tool');
548
+
549
+ expect(fragments.length).toBeGreaterThan(0);
550
+ expect(fragments.every(f => f.source_class === 'tool')).toBe(true);
551
+ });
552
+
553
+ it('should track state correctly', async () => {
554
+ const stateBefore = mccaEngine.getState();
555
+
556
+ await mccaEngine.addFragment({
557
+ content: 'State test',
558
+ source_class: 'external',
559
+ region: 'ephemeral',
560
+ token_count: 20,
561
+ });
562
+
563
+ const stateAfter = mccaEngine.getState();
564
+
565
+ expect(stateAfter.totalFragments).toBe(stateBefore.totalFragments + 1);
566
+ expect(stateAfter.totalTokens).toBe(stateBefore.totalTokens + 20);
567
+ });
568
+ });
569
+
570
+ describe('Commitment Proofs', () => {
571
+ it('should generate manifold commitment proof', async () => {
572
+ const proof = await mccaEngine.generateCommitmentProof();
573
+
574
+ expect(proof.id).toBeTruthy();
575
+ expect(proof.merkle_root).toBeTruthy();
576
+ expect(proof.fragment_count).toBeGreaterThan(0);
577
+ expect(proof.influence_distribution).toBeDefined();
578
+ expect(proof.commitment_id).toBeTruthy();
579
+ expect(proof.seal).toBeTruthy();
580
+ });
581
+
582
+ it('should track influence distribution', async () => {
583
+ const proof = await mccaEngine.generateCommitmentProof();
584
+
585
+ const totalDistribution = Object.values(proof.influence_distribution)
586
+ .reduce((a, b) => a + b, 0);
587
+
588
+ // Should sum to ~1.0 (normalized)
589
+ expect(totalDistribution).toBeCloseTo(1.0, 1);
590
+ });
591
+ });
592
+
593
+ describe('Budget Compliance', () => {
594
+ it('should check budget compliance', () => {
595
+ const result = mccaEngine.checkBudgetCompliance();
596
+
597
+ expect(typeof result.compliant).toBe('boolean');
598
+ expect(Array.isArray(result.violations)).toBe(true);
599
+ });
600
+ });
601
+
602
+ describe('Drift Analysis', () => {
603
+ it('should analyze drift', async () => {
604
+ const analysis = await mccaEngine.analyzeDrift();
605
+
606
+ expect(analysis.score).toBeGreaterThanOrEqual(0);
607
+ expect(analysis.score).toBeLessThanOrEqual(1);
608
+ expect(['none', 'low', 'medium', 'high', 'critical']).toContain(analysis.severity);
609
+ expect(analysis.by_source).toBeDefined();
610
+ expect(Array.isArray(analysis.violations)).toBe(true);
611
+ expect(Array.isArray(analysis.recommendations)).toBe(true);
612
+ });
613
+
614
+ it('should classify severity correctly', async () => {
615
+ const analysis = await mccaEngine.analyzeDrift();
616
+
617
+ if (analysis.score < 0.1) {
618
+ expect(analysis.severity).toBe('none');
619
+ } else if (analysis.score < 0.25) {
620
+ expect(analysis.severity).toBe('low');
621
+ }
622
+ });
623
+ });
624
+
625
+ describe('Context Window Manager', () => {
626
+ it('should manage context window', async () => {
627
+ const manager = new ContextWindowManager(mccaEngine, 50000);
628
+
629
+ // Add system prompt
630
+ const systemFragment = await manager.addSystemPrompt(
631
+ 'You are a helpful assistant.',
632
+ 10
633
+ );
634
+ expect(systemFragment.source_class).toBe('system');
635
+ expect(systemFragment.region).toBe('core');
636
+
637
+ // Add user message
638
+ const userFragment = await manager.addUserMessage(
639
+ 'Hello, can you help me?',
640
+ 8
641
+ );
642
+ expect(userFragment.source_class).toBe('user');
643
+ expect(userFragment.region).toBe('task');
644
+
645
+ // Add agent response
646
+ const agentFragment = await manager.addAgentResponse(
647
+ 'Of course! How can I assist you today?',
648
+ 12
649
+ );
650
+ expect(agentFragment.source_class).toBe('agent');
651
+ expect(agentFragment.region).toBe('history');
652
+ });
653
+
654
+ it('should check context health', async () => {
655
+ const manager = new ContextWindowManager(mccaEngine, 50000);
656
+
657
+ const health = await manager.getHealth();
658
+
659
+ expect(typeof health.healthy).toBe('boolean');
660
+ expect(health.drift).toBeDefined();
661
+ expect(health.utilization).toBeGreaterThanOrEqual(0);
662
+ expect(health.utilization).toBeLessThanOrEqual(1);
663
+ });
664
+ });
665
+
666
+ describe('Statistics', () => {
667
+ it('should report engine statistics', () => {
668
+ const stats = mccaEngine.getStats();
669
+
670
+ expect(stats.fragments).toBeGreaterThan(0);
671
+ expect(stats.tokens).toBeGreaterThan(0);
672
+ expect(stats.config).toBeDefined();
673
+ expect(stats.budgetCompliance).toBeDefined();
674
+ });
675
+ });
676
+ });
677
+
678
+ // ============================================================================
679
+ // INTEGRATION TESTS (L1 + L2 + L3 + MCCA)
680
+ // ============================================================================
681
+
682
+ describe('Three-Layer Attestation Integration', () => {
683
+ let commitmentEngine: CommitmentEngine;
684
+ let teeEngine: TEEAttestationEngine;
685
+ let zkEngine: ZKProofsEngine;
686
+ let mccaEngine: MCCAEngine;
687
+
688
+ beforeAll(async () => {
689
+ commitmentEngine = new CommitmentEngine();
690
+ await commitmentEngine.initialize(TEST_SEAL_KEY);
691
+
692
+ teeEngine = new TEEAttestationEngine(commitmentEngine);
693
+ await teeEngine.initialize(TEST_SEAL_KEY);
694
+
695
+ zkEngine = new ZKProofsEngine(commitmentEngine);
696
+ await zkEngine.initialize(TEST_SEAL_KEY);
697
+
698
+ mccaEngine = new MCCAEngine(commitmentEngine);
699
+ await mccaEngine.initialize(TEST_SEAL_KEY);
700
+ });
701
+
702
+ afterAll(() => {
703
+ zkEngine.stopProcessing();
704
+ });
705
+
706
+ it('should chain L1 -> L2 -> L3 attestations', async () => {
707
+ const actionData = {
708
+ action: 'high-value-transfer',
709
+ amount: 1000000,
710
+ timestamp: generateTimestamp(),
711
+ };
712
+
713
+ // L1: Commitment (<1ms)
714
+ const l1Start = performance.now();
715
+ const commitment = await commitmentEngine.commit(actionData, 'chain-test-001');
716
+ const l1Elapsed = performance.now() - l1Start;
717
+ expect(l1Elapsed).toBeLessThan(5); // Should be <1ms, allow margin
718
+
719
+ // L2: TEE Attestation (<10ms)
720
+ const l2Start = performance.now();
721
+ const attestation = await teeEngine.attest(actionData, 'chain-test-001');
722
+ const l2Elapsed = performance.now() - l2Start;
723
+ expect(l2Elapsed).toBeLessThan(50); // Should be <10ms, allow margin
724
+
725
+ // L3: ZK Proof (async)
726
+ const zkRequest = new ClaimBuilder('action_compliance')
727
+ .withDescription('Chain test proof')
728
+ .withClaim('action', actionData)
729
+ .withClaim('commitment', commitment.merkleRoot)
730
+ .withClaim('attestation', attestation.id)
731
+ .withCommitments('chain-test-001')
732
+ .withAttestations(attestation.id)
733
+ .build('high');
734
+
735
+ const zkDocument = await zkEngine.requestProof(zkRequest);
736
+ const zkCompleted = await zkEngine.waitForProof(zkDocument.id, 10000);
737
+
738
+ expect(zkCompleted.status).toBe('verified');
739
+ expect(zkCompleted.references.commitments).toContain('chain-test-001');
740
+ expect(zkCompleted.references.attestations).toContain(attestation.id);
741
+ });
742
+
743
+ it('should integrate MCCA with attestation layers', async () => {
744
+ // Add context fragment
745
+ const fragment = await mccaEngine.addFragment({
746
+ content: { integration: 'test', value: 42 },
747
+ source_class: 'user',
748
+ region: 'task',
749
+ token_count: 50,
750
+ });
751
+
752
+ // Generate MCCA proof
753
+ const mccaProof = await mccaEngine.generateCommitmentProof();
754
+
755
+ // Attest MCCA state with TEE
756
+ const attestation = await teeEngine.attest(
757
+ { mcca_proof: mccaProof.id, fragment_count: mccaProof.fragment_count },
758
+ mccaProof.commitment_id
759
+ );
760
+
761
+ expect(attestation.status).toBe('verified');
762
+
763
+ // Generate ZK proof of MCCA state
764
+ const zkRequest = new ClaimBuilder('audit_trail')
765
+ .withDescription('MCCA state proof')
766
+ .withClaim('mcca_merkle_root', mccaProof.merkle_root)
767
+ .withClaim('fragment_count', mccaProof.fragment_count)
768
+ .withClaim('influence_distribution', mccaProof.influence_distribution)
769
+ .withCommitments(mccaProof.commitment_id)
770
+ .withAttestations(attestation.id)
771
+ .build('normal');
772
+
773
+ const zkDocument = await zkEngine.requestProof(zkRequest);
774
+ const zkCompleted = await zkEngine.waitForProof(zkDocument.id, 15000);
775
+
776
+ expect(zkCompleted.status).toBe('verified');
777
+ });
778
+
779
+ it('should provide complete audit trail', async () => {
780
+ // Simulate a complete agent action flow
781
+ const agentId = 'test-agent-001';
782
+ const action = {
783
+ type: 'api-call',
784
+ endpoint: '/process-payment',
785
+ params: { amount: 500 },
786
+ };
787
+
788
+ // 1. Context setup (MCCA)
789
+ await mccaEngine.addFragment({
790
+ content: { system_prompt: 'Process payments safely' },
791
+ source_class: 'system',
792
+ region: 'core',
793
+ token_count: 100,
794
+ });
795
+
796
+ await mccaEngine.addFragment({
797
+ content: { user_request: 'Process $500 payment' },
798
+ source_class: 'user',
799
+ region: 'task',
800
+ token_count: 50,
801
+ });
802
+
803
+ const mccaProof = await mccaEngine.generateCommitmentProof();
804
+
805
+ // 2. L1 Commitment
806
+ const commitment = await commitmentEngine.commit(
807
+ { action, context: mccaProof.merkle_root },
808
+ `action:${agentId}:${Date.now()}`
809
+ );
810
+
811
+ // 3. L2 TEE Attestation
812
+ const attestation = await teeEngine.attest(
813
+ { action, commitment: commitment.operationId },
814
+ commitment.operationId
815
+ );
816
+
817
+ // 4. L3 ZK Proof for audit
818
+ const auditProof = await zkEngine.requestProof(
819
+ new ClaimBuilder('audit_trail')
820
+ .withDescription('Complete action audit trail')
821
+ .withClaim('agent_id', agentId)
822
+ .withClaim('action', action)
823
+ .withClaim('context_proof', mccaProof.id)
824
+ .withClaim('events', [
825
+ { type: 'context_setup', timestamp: mccaProof.timestamp },
826
+ { type: 'commitment', timestamp: commitment.timestamp },
827
+ { type: 'attestation', timestamp: attestation.timestamp },
828
+ ])
829
+ .withClaim('num_events', 3)
830
+ .withClaim('start_time', mccaProof.timestamp)
831
+ .withClaim('end_time', attestation.timestamp)
832
+ .withCommitments(commitment.operationId, mccaProof.commitment_id)
833
+ .withAttestations(attestation.id)
834
+ .build('high')
835
+ );
836
+
837
+ const completedAudit = await zkEngine.waitForProof(auditProof.id, 20000);
838
+
839
+ expect(completedAudit.status).toBe('verified');
840
+ expect(completedAudit.proof).toBeTruthy();
841
+
842
+ // Verify the complete chain
843
+ const verifyResult = await zkEngine.verifyProof(completedAudit);
844
+ expect(verifyResult.valid).toBe(true);
845
+ });
846
+ });
847
+
848
+ // ============================================================================
849
+ // LATENCY SLA TESTS
850
+ // ============================================================================
851
+
852
+ describe('Latency SLA Compliance', () => {
853
+ let commitmentEngine: CommitmentEngine;
854
+ let teeEngine: TEEAttestationEngine;
855
+
856
+ beforeAll(async () => {
857
+ commitmentEngine = new CommitmentEngine();
858
+ await commitmentEngine.initialize(TEST_SEAL_KEY);
859
+
860
+ teeEngine = new TEEAttestationEngine(commitmentEngine);
861
+ await teeEngine.initialize(TEST_SEAL_KEY);
862
+ });
863
+
864
+ it('L1 commitment should complete in <1ms (P99)', async () => {
865
+ const latencies: number[] = [];
866
+
867
+ for (let i = 0; i < 100; i++) {
868
+ const start = performance.now();
869
+ await commitmentEngine.commit({ iteration: i }, `latency-l1-${i}`);
870
+ latencies.push(performance.now() - start);
871
+ }
872
+
873
+ // Sort and get P99
874
+ latencies.sort((a, b) => a - b);
875
+ const p99 = latencies[98];
876
+
877
+ // Note: In Node.js environment, actual latency may vary
878
+ // Target is <1ms, we allow 5ms for test stability
879
+ expect(p99).toBeLessThan(5);
880
+ });
881
+
882
+ it('L2 attestation should complete in <10ms (P99)', async () => {
883
+ const latencies: number[] = [];
884
+
885
+ for (let i = 0; i < 50; i++) {
886
+ const start = performance.now();
887
+ await teeEngine.attest({ iteration: i }, `latency-l2-${i}`);
888
+ latencies.push(performance.now() - start);
889
+ }
890
+
891
+ // Sort and get P99
892
+ latencies.sort((a, b) => a - b);
893
+ const p99 = latencies[Math.floor(latencies.length * 0.99)];
894
+
895
+ // Target is <10ms, we allow 50ms for test stability
896
+ expect(p99).toBeLessThan(50);
897
+ });
898
+ });