-
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathtest.ts
More file actions
577 lines (486 loc) · 19 KB
/
test.ts
File metadata and controls
577 lines (486 loc) · 19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
/**
* SwarmOrchestrator Test Suite
*
* Run with: npx ts-node test.ts
*/
// ============================================================================
// MOCK OPENCLAW-CORE (since it's a hypothetical module)
// ============================================================================
// Mock the callSkill function to simulate agent responses
const mockAgentResponses: Record<string, unknown> = {
DataAnalyst: { metrics: { revenue: 1500000, growth: 12.5 }, status: 'analyzed' },
StrategyAdvisor: { scenarios: ['cut_costs', 'invest_growth', 'maintain'], recommendation: 'invest_growth' },
RiskAssessor: { riskLevel: 'medium', factors: ['market_volatility', 'competition'] },
};
// Override the module resolution for testing
const originalCallSkill = async (skillName: string, params: Record<string, unknown>) => {
console.log(` [>] [Mock] Calling skill: ${skillName}`);
// Simulate network delay
await new Promise(resolve => setTimeout(resolve, 100 + Math.random() * 200));
if (mockAgentResponses[skillName]) {
return { success: true, data: mockAgentResponses[skillName] };
}
throw new Error(`Unknown skill: ${skillName}`);
};
// Inject mock into global scope before importing
(global as any).__mockCallSkill = originalCallSkill;
// ============================================================================
// IMPORT THE ACTUAL CLASSES (they're exported)
// ============================================================================
import {
SharedBlackboard,
AuthGuardian,
createSwarmOrchestrator
} from './index';
// ============================================================================
// TEST UTILITIES
// ============================================================================
const colors = {
green: '\x1b[32m',
red: '\x1b[31m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
cyan: '\x1b[36m',
reset: '\x1b[0m',
bold: '\x1b[1m',
};
function log(message: string, color: keyof typeof colors = 'reset') {
console.log(`${colors[color]}${message}${colors.reset}`);
}
function header(title: string) {
console.log('\n' + '='.repeat(60));
log(` ${title}`, 'bold');
console.log('='.repeat(60));
}
function pass(test: string) {
log(` [PASS] PASS: ${test}`, 'green');
}
function fail(test: string, error?: string) {
log(` [FAIL] FAIL: ${test}`, 'red');
if (error) log(` Error: ${error}`, 'red');
}
// ============================================================================
// TEST 1: SHARED BLACKBOARD
// ============================================================================
async function testBlackboard() {
header('TEST 1: Shared Blackboard');
const blackboard = new SharedBlackboard(process.cwd());
// Register test agent with wildcard namespace access
blackboard.registerAgent('test-agent', 'test-token', ['*']);
blackboard.registerAgent('agent1', 'token1', ['*']);
blackboard.registerAgent('agent2', 'token2', ['*']);
// Test write
const entry = blackboard.write('test:key1', { data: 'hello world' }, 'test-agent', undefined, 'test-token');
if (entry.key === 'test:key1' && (entry.value as any).data === 'hello world') {
pass('Write to blackboard');
} else {
fail('Write to blackboard');
}
// Test read
const readEntry = blackboard.read('test:key1');
if (readEntry && (readEntry.value as any).data === 'hello world') {
pass('Read from blackboard');
} else {
fail('Read from blackboard');
}
// Test exists
if (blackboard.exists('test:key1') && !blackboard.exists('nonexistent')) {
pass('Exists check');
} else {
fail('Exists check');
}
// Test TTL expiration
blackboard.write('test:expiring', { temp: true }, 'test-agent', 1, 'test-token'); // 1 second TTL
if (blackboard.read('test:expiring')) {
pass('TTL entry created');
} else {
fail('TTL entry created');
}
// Wait for expiration
await new Promise(resolve => setTimeout(resolve, 1500));
if (!blackboard.read('test:expiring')) {
pass('TTL expiration works');
} else {
fail('TTL expiration works');
}
// Test snapshot
blackboard.write('test:snap1', { a: 1 }, 'agent1', undefined, 'token1');
blackboard.write('test:snap2', { b: 2 }, 'agent2', undefined, 'token2');
const snapshot = blackboard.getSnapshot();
if (Object.keys(snapshot).length >= 2) {
pass('Snapshot retrieval');
log(` Found ${Object.keys(snapshot).length} entries`, 'cyan');
} else {
fail('Snapshot retrieval');
}
}
// ============================================================================
// TEST 2: AUTH GUARDIAN (PERMISSION WALL)
// ============================================================================
async function testAuthGuardian() {
header('TEST 2: AuthGuardian Permission Wall');
const authGuardian = new AuthGuardian();
// Test permission request with good justification
const grant1 = await authGuardian.requestPermission(
'orchestrator',
'SAP_API',
'Need to retrieve invoice data for Q3 financial analysis task-789. This is required for the quarterly report generation.',
'read:invoices'
);
if (grant1.granted && grant1.grantToken) {
pass('Permission granted with good justification');
log(` Token: ${grant1.grantToken.substring(0, 20)}...`, 'cyan');
log(` Expires: ${grant1.expiresAt}`, 'cyan');
log(` Restrictions: ${grant1.restrictions.join(', ')}`, 'cyan');
} else {
fail('Permission granted with good justification', grant1.reason);
}
// Test token validation
if (grant1.grantToken && authGuardian.validateToken(grant1.grantToken)) {
pass('Token validation works');
} else {
fail('Token validation works');
}
// Test permission request with poor justification
const grant2 = await authGuardian.requestPermission(
'orchestrator',
'FINANCIAL_API',
'test', // Too short, contains "test"
'*' // Broad scope
);
if (!grant2.granted) {
pass('Permission denied for poor justification');
log(` Reason: ${grant2.reason}`, 'yellow');
} else {
fail('Permission denied for poor justification');
}
// Test permission for untrusted agent
const grant3 = await authGuardian.requestPermission(
'unknown_agent', // Low trust level
'DATA_EXPORT',
'Need to export all customer data for external processing',
'write:all'
);
if (!grant3.granted) {
pass('Permission denied for risky operation');
log(` Reason: ${grant3.reason}`, 'yellow');
} else {
fail('Permission denied for risky operation');
}
// Test token revocation
if (grant1.grantToken) {
authGuardian.revokeToken(grant1.grantToken);
if (!authGuardian.validateToken(grant1.grantToken)) {
pass('Token revocation works');
} else {
fail('Token revocation works');
}
}
// Test active grants list
const activeGrants = authGuardian.getActiveGrants();
log(` Active grants: ${activeGrants.length}`, 'cyan');
pass('Active grants retrieval');
// Test HMAC token signature verification
const hmacGuardian = new AuthGuardian();
const hmacGrant = await hmacGuardian.requestPermission(
'orchestrator', 'FILE_SYSTEM',
'Need to read configuration files for build pipeline task-101',
'read'
);
if (hmacGrant.granted && hmacGrant.grantToken) {
if (hmacGuardian.verifyTokenSignature(hmacGrant.grantToken)) {
pass('HMAC token signature verification');
} else {
fail('HMAC token signature verification');
}
if (hmacGuardian.getSigningAlgorithm() === 'hmac-sha256') {
pass('HMAC signing algorithm reported correctly');
} else {
fail('HMAC signing algorithm reported correctly');
}
if (hmacGuardian.exportPublicKey() === null) {
pass('HMAC guardian returns null public key');
} else {
fail('HMAC guardian returns null public key');
}
} else {
fail('HMAC grant for signature test');
}
}
// ============================================================================
// TEST 2b: AuthGuardian Ed25519 Signing
// ============================================================================
async function testAuthGuardianEd25519() {
header('TEST 2b: AuthGuardian Ed25519 Signing');
const guardian = new AuthGuardian({ algorithm: 'ed25519' });
// Algorithm should be ed25519
if (guardian.getSigningAlgorithm() === 'ed25519') {
pass('Ed25519 signing algorithm configured');
} else {
fail('Ed25519 signing algorithm configured');
}
// Public key should be exportable
const pubKey = guardian.exportPublicKey();
if (pubKey && pubKey.includes('BEGIN PUBLIC KEY')) {
pass('Ed25519 public key exported in PEM format');
log(` Public key: ${pubKey.split('\n')[1].substring(0, 30)}...`, 'cyan');
} else {
fail('Ed25519 public key exported in PEM format');
}
// Grant a permission and verify the token is signed
const grant = await guardian.requestPermission(
'orchestrator',
'FILE_SYSTEM',
'Need to read workspace files for code review analysis task-202',
'read'
);
if (grant.granted && grant.grantToken) {
pass('Ed25519 permission granted');
log(` Token: ${grant.grantToken.substring(0, 40)}...`, 'cyan');
// Token should contain a dot separator (payload.signature)
if (grant.grantToken.includes('.')) {
pass('Ed25519 token contains signature');
} else {
fail('Ed25519 token contains signature');
}
// Signature should verify
if (guardian.verifyTokenSignature(grant.grantToken)) {
pass('Ed25519 token signature verifies');
} else {
fail('Ed25519 token signature verifies');
}
// Tampered token should not verify
const tampered = grant.grantToken.slice(0, -3) + 'xxx';
if (!guardian.verifyTokenSignature(tampered)) {
pass('Tampered Ed25519 token rejected');
} else {
fail('Tampered Ed25519 token rejected');
}
// Token should still validate (active, not expired)
if (guardian.validateToken(grant.grantToken)) {
pass('Ed25519 token validates as active');
} else {
fail('Ed25519 token validates as active');
}
// Revocation should work
guardian.revokeToken(grant.grantToken);
if (!guardian.validateToken(grant.grantToken)) {
pass('Ed25519 token revocation works');
} else {
fail('Ed25519 token revocation works');
}
} else {
fail('Ed25519 permission granted', grant.reason);
}
// A different Ed25519 guardian should not verify tokens from the first
const guardian2 = new AuthGuardian({ algorithm: 'ed25519' });
const grant3 = await guardian2.requestPermission(
'orchestrator', 'FILE_SYSTEM',
'Need to read build output files for quality check task-404',
'read'
);
if (grant3.granted && grant3.grantToken) {
// guardian (different keypair) should not verify guardian2's token
if (!guardian.verifyTokenSignature(grant3.grantToken)) {
pass('Cross-guardian Ed25519 verification correctly fails');
} else {
fail('Cross-guardian Ed25519 verification correctly fails');
}
}
}
// ============================================================================
// TEST 3: SWARM ORCHESTRATOR CAPABILITIES
// ============================================================================
async function testSwarmOrchestrator() {
header('TEST 3: SwarmOrchestrator Capabilities');
const orchestrator = createSwarmOrchestrator({
enableTracing: true,
maxParallelAgents: 3,
});
const mockContext = {
agentId: 'orchestrator',
taskId: 'test-task-001',
sessionId: 'test-session',
};
// Test: Update blackboard
log('\n [LOG] Testing update_blackboard capability...', 'blue');
const bbResult = await orchestrator.execute('update_blackboard', {
key: 'test:orchestrator:data',
value: { message: 'Hello from orchestrator test' },
ttl: 3600,
}, mockContext);
if (bbResult.success) {
pass('update_blackboard capability');
} else {
fail('update_blackboard capability', bbResult.error?.message);
}
// Test: Query swarm state
log('\n [#] Testing query_swarm_state capability...', 'blue');
const stateResult = await orchestrator.execute('query_swarm_state', {
scope: 'all',
includeHistory: true,
}, mockContext);
if (stateResult.success && stateResult.data) {
pass('query_swarm_state capability');
const state = stateResult.data as any;
log(` Timestamp: ${state.timestamp}`, 'cyan');
log(` Blackboard entries: ${Object.keys(state.blackboardSnapshot || {}).length}`, 'cyan');
} else {
fail('query_swarm_state capability', stateResult.error?.message);
}
// Test: Request permission
log('\n [SEC] Testing request_permission capability...', 'blue');
const permResult = await orchestrator.execute('request_permission', {
resourceType: 'SAP_API',
justification: 'Need to access SAP invoice data for the quarterly financial reconciliation task. This is a scheduled operation.',
scope: 'read:invoices:q4_2025',
}, mockContext);
if (permResult.success) {
pass('request_permission capability');
const grant = permResult.data as any;
log(` Granted: ${grant.granted}`, 'cyan');
if (grant.granted) {
log(` Restrictions: ${grant.restrictions.join(', ')}`, 'cyan');
}
} else {
fail('request_permission capability');
}
// Test: Register agents
log('\n [+] Testing agent registration...', 'blue');
orchestrator.registerAgent('DataAnalyst', 'available');
orchestrator.registerAgent('StrategyAdvisor', 'available');
orchestrator.registerAgent('RiskAssessor', 'busy');
pass('Agent registration');
// Query state to verify agents
const state2 = await orchestrator.execute('query_swarm_state', {
scope: 'agents',
}, mockContext);
if (state2.success) {
const agents = (state2.data as any).activeAgents || [];
log(` Registered agents: ${agents.length}`, 'cyan');
agents.forEach((a: any) => {
log(` - ${a.agentId}: ${a.status}`, 'cyan');
});
}
// Test: Unknown action handling
log('\n [WARN] Testing error handling...', 'blue');
const errorResult = await orchestrator.execute('unknown_action', {}, mockContext);
if (!errorResult.success && errorResult.error?.code === 'UNKNOWN_ACTION') {
pass('Unknown action error handling');
} else {
fail('Unknown action error handling');
}
}
// ============================================================================
// TEST 4: TASK DELEGATION (with mocked callSkill)
// ============================================================================
async function testTaskDelegation() {
header('TEST 4: Task Delegation Flow');
log('\n [!] This test simulates the full delegation flow...', 'blue');
log(' (Note: callSkill is mocked since openclaw-core is hypothetical)\n', 'yellow');
// We'll test the blackboard caching behavior
const orchestrator = createSwarmOrchestrator();
const mockContext = {
agentId: 'orchestrator',
taskId: 'delegation-test-001',
};
// First, write a cached result to blackboard
await orchestrator.execute('update_blackboard', {
key: 'task:DataAnalyst:{"instruction":"Analyze Q3 data","context":{"q',
value: { cached: true, result: 'Pre-computed analysis' },
ttl: 3600,
}, mockContext);
log(' [PKG] Pre-cached a task result in blackboard', 'cyan');
// Now try to delegate - it should find the cached result
// (Note: actual delegation would require the real callSkill)
const state = await orchestrator.execute('query_swarm_state', {
scope: 'blackboard',
}, mockContext);
if (state.success) {
const snapshot = (state.data as any).blackboardSnapshot;
const cachedKeys = Object.keys(snapshot).filter(k => k.startsWith('task:'));
if (cachedKeys.length > 0) {
pass('Blackboard caching for task delegation');
log(` Cached task keys: ${cachedKeys.length}`, 'cyan');
}
}
pass('Delegation flow structure verified');
}
// ============================================================================
// TEST 5: FILE PERSISTENCE
// ============================================================================
async function testFilePersistence() {
header('TEST 5: Blackboard File Persistence');
const fs = await import('fs');
const path = await import('path');
const blackboardPath = path.join(process.cwd(), 'swarm-blackboard.md');
if (fs.existsSync(blackboardPath)) {
pass('Blackboard file created');
const content = fs.readFileSync(blackboardPath, 'utf-8');
if (content.includes('# Swarm Blackboard')) {
pass('Blackboard has correct header');
} else {
fail('Blackboard has correct header');
}
if (content.includes('## Knowledge Cache')) {
pass('Blackboard has Knowledge Cache section');
} else {
fail('Blackboard has Knowledge Cache section');
}
if (content.includes('## Active Tasks')) {
pass('Blackboard has Active Tasks section');
} else {
fail('Blackboard has Active Tasks section');
}
// Show file stats
const stats = fs.statSync(blackboardPath);
log(` File size: ${stats.size} bytes`, 'cyan');
log(` Last modified: ${stats.mtime.toISOString()}`, 'cyan');
// Show a preview of the content
log('\n [DOC] Blackboard Preview:', 'blue');
const lines = content.split('\n').slice(0, 15);
lines.forEach(line => log(` ${line}`, 'cyan'));
if (content.split('\n').length > 15) {
log(` ... (${content.split('\n').length - 15} more lines)`, 'cyan');
}
} else {
fail('Blackboard file created');
}
}
// ============================================================================
// RUN ALL TESTS
// ============================================================================
async function runAllTests() {
console.log('\n');
log('+============================================================+', 'bold');
log('| SWARM ORCHESTRATOR TEST SUITE |', 'bold');
log('| Testing core functionality locally |', 'bold');
log('+============================================================+', 'bold');
const startTime = Date.now();
try {
await testBlackboard();
await testAuthGuardian();
await testAuthGuardianEd25519();
await testSwarmOrchestrator();
await testTaskDelegation();
await testFilePersistence();
const duration = Date.now() - startTime;
header('TEST SUMMARY');
log(`\n [*] All tests completed in ${duration}ms`, 'green');
log('\n The SwarmOrchestrator skill is working correctly!', 'green');
log(' Core components verified:', 'cyan');
log(' * SharedBlackboard: Read/Write/TTL/Persistence [PASS]', 'cyan');
log(' * AuthGuardian: Permission Wall enforcement [PASS]', 'cyan');
log(' * AuthGuardian: Ed25519 signing & verification [PASS]', 'cyan');
log(' * SwarmOrchestrator: All capabilities [PASS]', 'cyan');
log(' * File persistence: Markdown blackboard [PASS]', 'cyan');
log('', 'reset');
} catch (error) {
header('TEST FAILURE');
log(`\n [FAIL] Tests failed with error:`, 'red');
console.error(error);
process.exit(1);
}
}
// Run tests
runAllTests();