-
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathtest-standalone.ts
More file actions
1591 lines (1370 loc) · 59.2 KB
/
test-standalone.ts
File metadata and controls
1591 lines (1370 loc) · 59.2 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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* SwarmOrchestrator Standalone Test Suite v3.0
*
* This test file contains embedded copies of the core classes
* to allow testing without requiring the hypothetical openclaw-core module.
* Updated for v3.0: universal domain support, scoped blackboard,
* restriction enforcement, identity verification.
*
* Run with: npx ts-node test-standalone.ts
*/
import { readFileSync, writeFileSync, existsSync } from 'fs';
import { join } from 'path';
import { randomUUID } from 'crypto';
import { BlackboardValidator, QualityGateAgent } from './lib/blackboard-validator';
// ============================================================================
// EMBEDDED TYPES (from index.ts v3.0)
// ============================================================================
interface BlackboardEntry {
key: string;
value: unknown;
sourceAgent: string;
timestamp: string;
ttl: number | null;
}
interface ActiveGrant {
grantToken: string;
resourceType: string;
agentId: string;
expiresAt: string;
restrictions: string[];
scope?: string;
}
interface PermissionGrant {
granted: boolean;
grantToken: string | null;
expiresAt: string | null;
restrictions: string[];
reason?: string;
}
interface ResourceProfile {
baseRisk: number;
defaultRestrictions: string[];
description: string;
}
interface AgentTrustConfig {
agentId: string;
trustLevel: number;
allowedNamespaces: string[];
allowedResources: string[];
}
// ============================================================================
// EMBEDDED CLASSES (from index.ts v3.0)
// ============================================================================
const CONFIG = {
blackboardPath: './swarm-blackboard.md',
maxParallelAgents: 3,
defaultTimeout: 30000,
enableTracing: true,
grantTokenTTL: 300000,
maxBlackboardValueSize: 1048576,
};
const DEFAULT_RESOURCE_PROFILES: Record<string, ResourceProfile> = {
// Financial
SAP_API: { baseRisk: 0.5, defaultRestrictions: ['read_only', 'max_records:100'], description: 'SAP system access' },
FINANCIAL_API: { baseRisk: 0.7, defaultRestrictions: ['read_only', 'no_pii_fields', 'audit_required'], description: 'Financial data API' },
DATA_EXPORT: { baseRisk: 0.6, defaultRestrictions: ['anonymize_pii', 'local_only'], description: 'Data export' },
// Coding
FILE_SYSTEM: { baseRisk: 0.5, defaultRestrictions: ['workspace_only', 'no_system_dirs'], description: 'File system access' },
SHELL_EXEC: { baseRisk: 0.8, defaultRestrictions: ['sandbox_only', 'no_sudo'], description: 'Shell execution' },
GIT: { baseRisk: 0.3, defaultRestrictions: ['read_only'], description: 'Git operations' },
PACKAGE_MANAGER: { baseRisk: 0.6, defaultRestrictions: ['sandbox_only'], description: 'Package manager' },
BUILD_TOOL: { baseRisk: 0.4, defaultRestrictions: ['workspace_only'], description: 'Build system access' },
// Infrastructure
DOCKER: { baseRisk: 0.7, defaultRestrictions: ['sandbox_only', 'no_sudo'], description: 'Docker operations' },
CLOUD_DEPLOY: { baseRisk: 0.9, defaultRestrictions: ['read_only', 'audit_required'], description: 'Cloud deployment' },
DATABASE: { baseRisk: 0.6, defaultRestrictions: ['read_only', 'max_records:100'], description: 'Database access' },
// Communication
EXTERNAL_SERVICE: { baseRisk: 0.4, defaultRestrictions: ['rate_limit:10_per_minute'], description: 'External service' },
EMAIL: { baseRisk: 0.5, defaultRestrictions: ['no_attachments', 'audit_required'], description: 'Email sending' },
WEBHOOK: { baseRisk: 0.4, defaultRestrictions: ['rate_limit:10_per_minute'], description: 'Webhook dispatch' },
};
const DEFAULT_AGENT_TRUST: AgentTrustConfig[] = [
{ agentId: 'orchestrator', trustLevel: 0.9, allowedNamespaces: ['*'], allowedResources: ['*'] },
{ agentId: 'data_analyst', trustLevel: 0.8, allowedNamespaces: ['analytics:', 'task:'], allowedResources: ['SAP_API', 'EXTERNAL_SERVICE', 'DATABASE'] },
{ agentId: 'strategy_advisor', trustLevel: 0.7, allowedNamespaces: ['strategy:', 'task:'], allowedResources: ['EXTERNAL_SERVICE'] },
{ agentId: 'risk_assessor', trustLevel: 0.85, allowedNamespaces: ['risk:', 'analytics:', 'task:'], allowedResources: ['FINANCIAL_API', 'EXTERNAL_SERVICE'] },
{ agentId: 'code_writer', trustLevel: 0.7, allowedNamespaces: ['code:', 'task:'], allowedResources: ['FILE_SYSTEM', 'SHELL_EXEC', 'GIT', 'PACKAGE_MANAGER', 'BUILD_TOOL'] },
{ agentId: 'code_reviewer', trustLevel: 0.75, allowedNamespaces: ['code:', 'review:', 'task:'], allowedResources: ['FILE_SYSTEM', 'GIT'] },
{ agentId: 'test_runner', trustLevel: 0.7, allowedNamespaces: ['test:', 'code:', 'task:'], allowedResources: ['FILE_SYSTEM', 'SHELL_EXEC', 'BUILD_TOOL'] },
{ agentId: 'devops_agent', trustLevel: 0.75, allowedNamespaces: ['infra:', 'deploy:', 'task:'], allowedResources: ['DOCKER', 'CLOUD_DEPLOY', 'SHELL_EXEC', 'GIT'] },
];
// ---------------------------------------------------------------------------
// SharedBlackboard v3 -- identity-verified, namespace-scoped
// ---------------------------------------------------------------------------
class SharedBlackboard {
private path: string;
private cache: Map<string, BlackboardEntry> = new Map();
private agentTokens: Map<string, string> = new Map();
private agentNamespaces: Map<string, string[]> = new Map();
constructor(basePath: string) {
this.path = join(basePath, 'swarm-blackboard.md');
this.initialize();
}
private initialize(): void {
const initialContent = `# Swarm Blackboard\nLast Updated: ${new Date().toISOString()}\n\n## Active Tasks\n| TaskID | Agent | Status | Started | Description |\n|--------|-------|--------|---------|-------------|\n\n## Knowledge Cache\n\n## Coordination Signals\n\n## Execution History\n`;
// 'wx' flag: exclusive create — atomic, no TOCTOU race condition
try { writeFileSync(this.path, initialContent, { flag: 'wx', encoding: 'utf-8' }); } catch { /* already exists */ }
this.loadFromDisk();
}
private loadFromDisk(): void {
try {
const content = readFileSync(this.path, 'utf-8');
const cacheSection = content.match(/## Knowledge Cache\n([\s\S]*?)(?=\n## |$)/);
if (cacheSection) {
const entries = cacheSection[1].matchAll(/### (\S+)\n([\s\S]*?)(?=\n### |$)/g);
for (const entry of entries) {
try { this.cache.set(entry[1], JSON.parse(entry[2].trim())); } catch { /* skip */ }
}
}
} catch { /* ignore load errors */ }
}
private persistToDisk(): void {
const sections = [
`# Swarm Blackboard`, `Last Updated: ${new Date().toISOString()}`, '',
`## Active Tasks`, `| TaskID | Agent | Status | Started | Description |`, `|--------|-------|--------|---------|-------------|`, '',
`## Knowledge Cache`,
];
for (const [key, entry] of this.cache.entries()) {
if (entry.ttl && Date.now() > new Date(entry.timestamp).getTime() + entry.ttl * 1000) {
this.cache.delete(key); continue;
}
sections.push(`### ${key}`, JSON.stringify(entry, null, 2), '');
}
sections.push(`## Coordination Signals`, `## Execution History`);
writeFileSync(this.path, sections.join('\n'), 'utf-8');
}
/** Register an agent's identity and allowed namespaces */
registerAgent(agentId: string, token: string, namespaces: string[]): void {
this.agentTokens.set(agentId, token);
this.agentNamespaces.set(agentId, namespaces);
}
/** Verify an agent token matches */
verifyAgent(agentId: string, token: string): boolean {
const stored = this.agentTokens.get(agentId);
return stored === token;
}
/** Check if an agent can access a key based on its namespace ACL */
canAccessKey(agentId: string, key: string): boolean {
const namespaces = this.agentNamespaces.get(agentId);
if (!namespaces) return false;
if (namespaces.includes('*')) return true;
return namespaces.some(ns => key.startsWith(ns));
}
/** Validate value size */
private validateValue(value: unknown): void {
const size = JSON.stringify(value).length;
if (size > CONFIG.maxBlackboardValueSize) {
throw new Error(`Value size ${size} exceeds max ${CONFIG.maxBlackboardValueSize}`);
}
}
/** Sanitize key to prevent injection */
private sanitizeKey(key: string): string {
return key.replace(/[#\[\]|`]/g, '_');
}
read(key: string): BlackboardEntry | null {
const entry = this.cache.get(key);
if (!entry) return null;
if (entry.ttl) {
const expiresAt = new Date(entry.timestamp).getTime() + entry.ttl * 1000;
if (Date.now() > expiresAt) { this.cache.delete(key); this.persistToDisk(); return null; }
}
return entry;
}
write(key: string, value: unknown, sourceAgent: string, ttl?: number, agentToken?: string): BlackboardEntry {
// If agent is registered, verify identity
if (this.agentTokens.has(sourceAgent)) {
if (!agentToken || !this.verifyAgent(sourceAgent, agentToken)) {
throw new Error(`Identity verification failed for agent ${sourceAgent}`);
}
}
// Namespace check
if (this.agentNamespaces.has(sourceAgent) && !this.canAccessKey(sourceAgent, key)) {
throw new Error(`Agent ${sourceAgent} cannot write to namespace of key: ${key}`);
}
const safeKey = this.sanitizeKey(key);
this.validateValue(value);
const entry: BlackboardEntry = {
key: safeKey,
value,
sourceAgent,
timestamp: new Date().toISOString(),
ttl: ttl ?? null,
};
this.cache.set(safeKey, entry);
this.persistToDisk();
return entry;
}
exists(key: string): boolean {
return this.read(key) !== null;
}
/** Full snapshot (orchestrator / legacy) */
getSnapshot(): Record<string, BlackboardEntry> {
const snapshot: Record<string, BlackboardEntry> = {};
for (const [key, entry] of this.cache.entries()) {
if (this.read(key)) snapshot[key] = entry;
}
return snapshot;
}
/** Namespace-scoped snapshot -- agent only sees keys it's allowed to access */
getScopedSnapshot(agentId: string): Record<string, BlackboardEntry> {
const snapshot: Record<string, BlackboardEntry> = {};
for (const [key, entry] of this.cache.entries()) {
if (this.read(key) && this.canAccessKey(agentId, key)) {
snapshot[key] = entry;
}
}
return snapshot;
}
clear(): void {
this.cache.clear();
this.persistToDisk();
}
}
// ---------------------------------------------------------------------------
// AuthGuardian v3 -- universal, configurable, restriction enforcement
// ---------------------------------------------------------------------------
class AuthGuardian {
private activeGrants: Map<string, ActiveGrant> = new Map();
private agentTrustLevels: Map<string, number> = new Map();
private resourceProfiles: Map<string, ResourceProfile> = new Map();
private auditLog: Array<{ timestamp: string; action: string; details: unknown }> = [];
constructor(options?: {
trustLevels?: AgentTrustConfig[];
resourceProfiles?: Record<string, ResourceProfile>;
}) {
// Load resource profiles
const profiles = options?.resourceProfiles ?? DEFAULT_RESOURCE_PROFILES;
for (const [type, profile] of Object.entries(profiles)) {
this.resourceProfiles.set(type, profile);
}
// Load trust configurations
const trusts = options?.trustLevels ?? DEFAULT_AGENT_TRUST;
for (const cfg of trusts) {
this.agentTrustLevels.set(cfg.agentId, cfg.trustLevel);
}
}
/** Register a new resource type at runtime */
registerResourceType(type: string, profile: ResourceProfile): void {
this.resourceProfiles.set(type, profile);
}
/** Register or update agent trust at runtime */
registerAgentTrust(config: AgentTrustConfig): void {
this.agentTrustLevels.set(config.agentId, config.trustLevel);
}
async requestPermission(
agentId: string,
resourceType: string,
justification: string,
scope?: string
): Promise<PermissionGrant> {
this.log('permission_request', { agentId, resourceType, justification, scope });
const evaluation = this.evaluateRequest(agentId, resourceType, justification, scope);
if (!evaluation.approved) {
return {
granted: false,
grantToken: null,
expiresAt: null,
restrictions: [],
reason: evaluation.reason,
};
}
const grantToken = this.generateGrantToken();
const expiresAt = new Date(Date.now() + CONFIG.grantTokenTTL).toISOString();
const grant: ActiveGrant = {
grantToken,
resourceType,
agentId,
expiresAt,
restrictions: evaluation.restrictions,
scope,
};
this.activeGrants.set(grantToken, grant);
this.log('permission_granted', { grantToken, agentId, resourceType, expiresAt, restrictions: evaluation.restrictions });
return {
granted: true,
grantToken,
expiresAt,
restrictions: evaluation.restrictions,
};
}
validateToken(token: string): boolean {
const grant = this.activeGrants.get(token);
if (!grant) return false;
if (new Date(grant.expiresAt) < new Date()) {
this.activeGrants.delete(token);
return false;
}
return true;
}
/** Validate token and return the bound grant data */
validateTokenWithGrant(token: string): ActiveGrant | null {
if (!this.validateToken(token)) return null;
return this.activeGrants.get(token) ?? null;
}
/** Enforce restrictions bound to a grant token */
enforceRestrictions(grantToken: string, operation: { type: string; count?: number; path?: string }): string | null {
const grant = this.activeGrants.get(grantToken);
if (!grant) return 'Invalid grant token';
for (const restriction of grant.restrictions) {
if (restriction === 'read_only' && operation.type !== 'read') {
return `Restriction violated: read_only -- attempted ${operation.type}`;
}
if (restriction.startsWith('max_records:') && operation.count) {
const max = parseInt(restriction.split(':')[1], 10);
if (operation.count > max) return `Restriction violated: max_records ${max} -- requested ${operation.count}`;
}
if (restriction === 'sandbox_only' && operation.path && !operation.path.includes('sandbox')) {
return `Restriction violated: sandbox_only`;
}
if (restriction === 'workspace_only' && operation.path && operation.path.startsWith('/')) {
return `Restriction violated: workspace_only`;
}
if (restriction === 'no_sudo' && operation.type === 'sudo') {
return `Restriction violated: no_sudo`;
}
if (restriction === 'no_system_dirs' && operation.path) {
const systemDirs = ['/etc', '/usr', '/bin', '/sbin', 'C:\\Windows', 'C:\\Program Files'];
if (systemDirs.some(d => operation.path!.startsWith(d))) {
return `Restriction violated: no_system_dirs`;
}
}
}
return null;
}
revokeToken(token: string): void {
this.activeGrants.delete(token);
this.log('permission_revoked', { token });
}
private evaluateRequest(
agentId: string,
resourceType: string,
justification: string,
scope?: string
): { approved: boolean; reason?: string; restrictions: string[] } {
const justificationScore = this.scoreJustification(justification, resourceType);
if (justificationScore < 0.3) {
return { approved: false, reason: 'Justification is insufficient. Please provide specific task context.', restrictions: [] };
}
const trustLevel = this.agentTrustLevels.get(agentId) ?? 0.5;
if (trustLevel < 0.4) {
return { approved: false, reason: 'Agent trust level is below threshold. Escalate to human operator.', restrictions: [] };
}
const riskScore = this.assessRisk(resourceType, scope);
if (riskScore > 0.8) {
return { approved: false, reason: 'Risk assessment exceeds acceptable threshold. Narrow the requested scope.', restrictions: [] };
}
// Get restrictions from resource profile (data-driven, not switch/case)
const profile = this.resourceProfiles.get(resourceType);
const restrictions = profile ? [...profile.defaultRestrictions] : [];
const weightedScore = (justificationScore * 0.4) + (trustLevel * 0.3) + ((1 - riskScore) * 0.3);
const approved = weightedScore >= 0.5;
return {
approved,
reason: approved ? undefined : 'Combined evaluation score below threshold.',
restrictions,
};
}
private scoreJustification(justification: string, resourceType?: string): number {
let score = 0;
if (justification.length > 20) score += 0.2;
if (justification.length > 50) score += 0.2;
if (/task|purpose|need|require/i.test(justification)) score += 0.2;
if (/specific|particular|exact/i.test(justification)) score += 0.2;
if (!/test|debug|try/i.test(justification)) score += 0.2;
// Resource-relevance bonus
if (resourceType) {
const relevancePatterns: Record<string, RegExp> = {
SAP_API: /sap|invoice|erp|vendor|purchase/i,
FINANCIAL_API: /financ|revenue|budget|ledger|account/i,
FILE_SYSTEM: /file|read|write|directory|path/i,
SHELL_EXEC: /compile|build|run|execute|script/i,
GIT: /commit|branch|merge|pull|push|repo/i,
DOCKER: /container|image|deploy|docker/i,
DATABASE: /query|record|table|schema|sql/i,
CLOUD_DEPLOY: /deploy|cloud|aws|azure|gcp/i,
};
const pattern = relevancePatterns[resourceType];
if (pattern && pattern.test(justification)) score += 0.1;
}
return Math.min(score, 1);
}
private assessRisk(resourceType: string, scope?: string): number {
const profile = this.resourceProfiles.get(resourceType);
let risk = profile?.baseRisk ?? 0.5;
if (!scope || scope === '*' || scope === 'all') risk += 0.2;
if (scope && /write|delete|update|modify/i.test(scope)) risk += 0.2;
return Math.min(risk, 1);
}
private generateGrantToken(): string {
return `grant_${randomUUID().replace(/-/g, '')}`;
}
private log(action: string, details: unknown): void {
this.auditLog.push({ timestamp: new Date().toISOString(), action, details });
}
getActiveGrants(): ActiveGrant[] {
const now = new Date();
for (const [token, grant] of this.activeGrants.entries()) {
if (new Date(grant.expiresAt) < now) this.activeGrants.delete(token);
}
return Array.from(this.activeGrants.values());
}
getAuditLog(): typeof this.auditLog {
return [...this.auditLog];
}
getResourceProfiles(): Record<string, ResourceProfile> {
const out: Record<string, ResourceProfile> = {};
for (const [k, v] of this.resourceProfiles) out[k] = v;
return out;
}
}
// ============================================================================
// 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));
}
let passCount = 0;
let failCount = 0;
function pass(test: string) {
passCount++;
log(` [PASS] PASS: ${test}`, 'green');
}
function fail(test: string, error?: string) {
failCount++;
log(` [FAIL] FAIL: ${test}`, 'red');
if (error) log(` Error: ${error}`, 'red');
}
// ============================================================================
// TEST 1: SHARED BLACKBOARD
// ============================================================================
async function testBlackboard() {
header('TEST 1: Shared Blackboard (v3 -- identity + namespace scoping)');
const blackboard = new SharedBlackboard(process.cwd());
blackboard.clear(); // Start fresh
// Register agents with tokens and namespaces
blackboard.registerAgent('orchestrator', 'orch-token-001', ['*']);
blackboard.registerAgent('data_analyst', 'analyst-token-002', ['analytics:', 'task:']);
blackboard.registerAgent('code_writer', 'code-token-003', ['code:', 'task:']);
pass('Agent registration');
// Test write with identity verification
const entry = blackboard.write('task:key1', { data: 'hello world', number: 42 }, 'orchestrator', undefined, 'orch-token-001');
if (entry.key === 'task:key1' && (entry.value as any).data === 'hello world') {
pass('Write with verified identity');
} else {
fail('Write with verified identity');
}
// Test write without token (unregistered agent -- still allowed)
const entry2 = blackboard.write('misc:unregistered', { data: 'free write' }, 'unknown_agent');
if (entry2.key === 'misc:unregistered') {
pass('Unregistered agent write allowed');
} else {
fail('Unregistered agent write allowed');
}
// Test write with BAD token (registered agent, wrong token)
let identityFailed = false;
try {
blackboard.write('task:bad', { data: 'hack' }, 'orchestrator', undefined, 'wrong-token');
} catch (e: any) {
if (e.message.includes('Identity verification failed')) identityFailed = true;
}
if (identityFailed) {
pass('Bad token rejected');
} else {
fail('Bad token rejected');
}
// Test namespace restriction
let namespaceFailed = false;
try {
blackboard.write('strategy:forbidden', { data: 'out of bounds' }, 'data_analyst', undefined, 'analyst-token-002');
} catch (e: any) {
if (e.message.includes('cannot write to namespace')) namespaceFailed = true;
}
if (namespaceFailed) {
pass('Namespace restriction enforced');
} else {
fail('Namespace restriction enforced');
}
// Test valid namespace write
const analystEntry = blackboard.write('analytics:q3:revenue', { amount: 1500000, currency: 'USD' }, 'data_analyst', undefined, 'analyst-token-002');
if (analystEntry.key === 'analytics:q3:revenue') {
pass('Namespace-allowed write succeeds');
} else {
fail('Namespace-allowed write succeeds');
}
// Test read
const readEntry = blackboard.read('task:key1');
if (readEntry && (readEntry.value as any).data === 'hello world') {
pass('Read from blackboard');
} else {
fail('Read from blackboard');
}
// Test exists
if (blackboard.exists('task:key1') && !blackboard.exists('nonexistent')) {
pass('Exists check');
} else {
fail('Exists check');
}
// Test scoped snapshot -- data_analyst should only see analytics: and task: keys
blackboard.write('code:main.ts', { content: '...' }, 'code_writer', undefined, 'code-token-003');
blackboard.write('analytics:q3:costs', { amount: 800000 }, 'data_analyst', undefined, 'analyst-token-002');
const analystSnapshot = blackboard.getScopedSnapshot('data_analyst');
const analystKeys = Object.keys(analystSnapshot);
const codeKeys = analystKeys.filter(k => k.startsWith('code:'));
const analyticsKeys = analystKeys.filter(k => k.startsWith('analytics:'));
if (codeKeys.length === 0 && analyticsKeys.length >= 2) {
pass(`Scoped snapshot correct (analyst sees ${analystKeys.length} keys, 0 code keys)`);
} else {
fail(`Scoped snapshot: analyst saw ${codeKeys.length} code keys, ${analyticsKeys.length} analytics keys`);
}
// Orchestrator should see everything
const orchSnapshot = blackboard.getScopedSnapshot('orchestrator');
if (Object.keys(orchSnapshot).length > analystKeys.length) {
pass(`Orchestrator sees all keys (${Object.keys(orchSnapshot).length} total)`);
} else {
fail('Orchestrator scoped snapshot');
}
// Test key sanitization (markdown injection prevention)
const _injectedEntry = blackboard.write('task:normal', { safe: true }, 'orchestrator', undefined, 'orch-token-001');
// Keys with | # [ ] ` should be sanitized
const injectionKey = 'task:#inject|test`bad[key]';
const sanitized = blackboard.write(injectionKey, { x: 1 }, 'orchestrator', undefined, 'orch-token-001');
if (!sanitized.key.includes('#') && !sanitized.key.includes('|') && !sanitized.key.includes('`')) {
pass('Key sanitization strips markdown chars');
} else {
fail('Key sanitization');
}
// Test value size validation
let sizeFailed = false;
try {
const hugeValue = 'x'.repeat(CONFIG.maxBlackboardValueSize + 100);
blackboard.write('task:huge', hugeValue, 'orchestrator', undefined, 'orch-token-001');
} catch (e: any) {
if (e.message.includes('exceeds max')) sizeFailed = true;
}
if (sizeFailed) {
pass('Value size validation enforced');
} else {
fail('Value size validation enforced');
}
// Test TTL expiration
log('\n [TIME] Testing TTL expiration (2 second wait)...', 'yellow');
blackboard.write('task:expiring', { temp: true }, 'orchestrator', 1, 'orch-token-001');
if (blackboard.read('task:expiring')) {
pass('TTL entry created');
} else {
fail('TTL entry created');
}
await new Promise(resolve => setTimeout(resolve, 1500));
if (!blackboard.read('task:expiring')) {
pass('TTL expiration works');
} else {
fail('TTL expiration works');
}
}
// ============================================================================
// TEST 2: AUTH GUARDIAN (PERMISSION WALL)
// ============================================================================
async function testAuthGuardian() {
header('TEST 2: AuthGuardian Permission Wall (v3 -- universal + restrictions)');
const authGuardian = new AuthGuardian();
// Test 1: Good justification, trusted agent, narrow scope
log('\n [SEC] Test: Valid permission request (SAP_API)...', 'blue');
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:q3'
);
if (grant1.granted && grant1.grantToken) {
pass('Permission granted with good justification');
log(` Token: ${grant1.grantToken.substring(0, 25)}...`, 'cyan');
log(` Restrictions: ${grant1.restrictions.join(', ')}`, 'cyan');
} else {
fail('Permission granted with good justification', grant1.reason);
}
// Test 2: Token validation
if (grant1.grantToken && authGuardian.validateToken(grant1.grantToken)) {
pass('Token validation works');
} else {
fail('Token validation works');
}
// Test 2b: Token + grant data validation
if (grant1.grantToken) {
const grantData = authGuardian.validateTokenWithGrant(grant1.grantToken);
if (grantData && grantData.restrictions.length > 0 && grantData.agentId === 'orchestrator') {
pass('validateTokenWithGrant returns bound restrictions');
} else {
fail('validateTokenWithGrant');
}
}
// Test 3: Invalid token
if (!authGuardian.validateToken('fake_token_12345')) {
pass('Invalid token rejected');
} else {
fail('Invalid token rejected');
}
// Test 4: Poor justification (too short, contains "test")
log('\n [SEC] Test: Poor justification...', 'blue');
const grant2 = await authGuardian.requestPermission(
'orchestrator',
'FINANCIAL_API',
'test',
'*'
);
if (!grant2.granted) {
pass('Permission denied for poor justification');
log(` Reason: ${grant2.reason}`, 'yellow');
} else {
fail('Permission denied for poor justification');
}
// Test 5: High-risk operation
log('\n [SEC] Test: High-risk operation...', 'blue');
const grant3 = await authGuardian.requestPermission(
'malicious_bot',
'FINANCIAL_API',
'Need to modify all financial records for data migration',
'write:delete:all'
);
if (!grant3.granted) {
pass('Permission denied for risky operation');
log(` Reason: ${grant3.reason}`, 'yellow');
} else {
log(' Note: Permission was granted with restrictions', 'yellow');
pass('Permission evaluated (granted with restrictions)');
}
// Test 6: Token revocation
log('\n [SEC] Test: Token revocation...', 'blue');
if (grant1.grantToken) {
authGuardian.revokeToken(grant1.grantToken);
if (!authGuardian.validateToken(grant1.grantToken)) {
pass('Token revocation works');
} else {
fail('Token revocation works');
}
}
// ----- NEW v3 TESTS: Universal resource types -----
log('\n [SEC] Test: Coding-domain resource types...', 'blue');
const codeGrant = await authGuardian.requestPermission(
'code_writer',
'FILE_SYSTEM',
'Need to read source file to refactor the authentication module for task-42',
'read:src/auth'
);
if (codeGrant.granted && codeGrant.restrictions.includes('workspace_only')) {
pass('FILE_SYSTEM permission granted to code_writer with workspace_only restriction');
} else {
fail('FILE_SYSTEM permission for code_writer', codeGrant.reason);
}
const shellGrant = await authGuardian.requestPermission(
'test_runner',
'SHELL_EXEC',
'Need to execute test suite to verify build passes for CI pipeline deployment',
'read:test'
);
if (shellGrant.granted && shellGrant.restrictions.includes('sandbox_only')) {
pass('SHELL_EXEC permission granted with sandbox_only restriction');
} else {
fail('SHELL_EXEC permission for test_runner', shellGrant.reason);
}
// Test: Custom resource type registered at runtime
log('\n [SEC] Test: Custom resource type registration...', 'blue');
authGuardian.registerResourceType('CUSTOM_ML_MODEL', {
baseRisk: 0.6,
defaultRestrictions: ['read_only', 'max_inference:100'],
description: 'ML model inference endpoint',
});
authGuardian.registerAgentTrust({
agentId: 'ml_engineer',
trustLevel: 0.8,
allowedNamespaces: ['ml:'],
allowedResources: ['CUSTOM_ML_MODEL'],
});
const mlGrant = await authGuardian.requestPermission(
'ml_engineer',
'CUSTOM_ML_MODEL',
'Need to run inference on the fraud detection model for quarterly risk analysis task',
'read:inference'
);
if (mlGrant.granted && mlGrant.restrictions.includes('max_inference:100')) {
pass('Custom resource type registered and used at runtime');
} else {
fail('Custom resource type registration', mlGrant.reason);
}
// ----- Restriction Enforcement Tests -----
log('\n [SEC] Test: Restriction enforcement...', 'blue');
// Get a fresh grant with restrictions
const freshGrant = await authGuardian.requestPermission(
'data_analyst',
'SAP_API',
'Need to access inventory data for supply chain analysis task',
'read:inventory'
);
if (freshGrant.granted && freshGrant.grantToken) {
// Enforce read_only -- attempt write should fail
const writeViolation = authGuardian.enforceRestrictions(freshGrant.grantToken, { type: 'write' });
if (writeViolation && writeViolation.includes('read_only')) {
pass('Restriction: read_only blocks write operations');
} else {
fail('Restriction: read_only enforcement');
}
// Enforce read -- should pass
const readOk = authGuardian.enforceRestrictions(freshGrant.grantToken, { type: 'read' });
if (!readOk) {
pass('Restriction: read_only allows read operations');
} else {
fail('Restriction: read_only allows read');
}
// Enforce max_records -- over limit should fail
const recordsViolation = authGuardian.enforceRestrictions(freshGrant.grantToken, { type: 'read', count: 500 });
if (recordsViolation && recordsViolation.includes('max_records')) {
pass('Restriction: max_records blocks excessive queries');
} else {
fail('Restriction: max_records enforcement');
}
// Under limit should pass
const recordsOk = authGuardian.enforceRestrictions(freshGrant.grantToken, { type: 'read', count: 50 });
if (!recordsOk) {
pass('Restriction: max_records allows within-limit queries');
} else {
fail('Restriction: max_records allows within-limit');
}
}
// Enforce sandbox_only on SHELL_EXEC grant
if (shellGrant.granted && shellGrant.grantToken) {
const sandboxViolation = authGuardian.enforceRestrictions(shellGrant.grantToken, { type: 'execute', path: '/usr/bin/rm' });
if (sandboxViolation && sandboxViolation.includes('sandbox_only')) {
pass('Restriction: sandbox_only blocks non-sandbox paths');
} else {
fail('Restriction: sandbox_only enforcement');
}
}
// Test: Multiple grants and listing
log('\n [SEC] Test: Multiple grants...', 'blue');
const activeGrants = authGuardian.getActiveGrants();
if (activeGrants.length >= 3) {
pass(`Active grants tracking (${activeGrants.length} grants)`);
activeGrants.forEach(g => {
log(` - ${g.agentId}: ${g.resourceType} [${g.restrictions.join(', ')}]`, 'cyan');
});
} else {
fail('Active grants tracking');
}
// Test: Audit log
const auditLog = authGuardian.getAuditLog();
if (auditLog.length > 0) {
pass(`Audit logging (${auditLog.length} entries)`);
} else {
fail('Audit logging');
}
// Test: Resource profiles accessible
const profiles = authGuardian.getResourceProfiles();
if (Object.keys(profiles).length >= 14) {
pass(`Resource profiles loaded (${Object.keys(profiles).length} types including coding & infra)`);
} else {
fail(`Resource profiles (got ${Object.keys(profiles).length}, expected >= 14)`);
}
}
// ============================================================================
// TEST 3: INTEGRATION SCENARIO
// ============================================================================
async function testIntegrationScenario() {
header('TEST 3: Integration Scenario (v3 -- identity + scoping + restrictions)');
log('\n [#] Simulating a multi-agent financial analysis workflow...\n', 'blue');
const blackboard = new SharedBlackboard(process.cwd());
const authGuardian = new AuthGuardian();
blackboard.clear();
// Register agents with identity tokens and namespace ACLs
blackboard.registerAgent('orchestrator', 'orch-int-token', ['*']);
blackboard.registerAgent('DataAnalyst', 'da-int-token', ['analytics:', 'task:']);
blackboard.registerAgent('StrategyBot', 'sb-int-token', ['strategy:', 'task:']);
pass('Agents registered with identity tokens');
// Step 1: Check blackboard for cached work
log(' Step 1: Check blackboard for cached results...', 'cyan');
const cachedResult = blackboard.read('task:financial_analysis:q3');
if (!cachedResult) {
log(' No cached result found, proceeding with task', 'yellow');
pass('Cache miss detection');
}
// Step 2: Request permission for SAP API
log('\n Step 2: Request permission for SAP API...', 'cyan');
const sapGrant = await authGuardian.requestPermission(
'orchestrator',
'SAP_API',
'Orchestrator needs to delegate financial data retrieval task to DataAnalyst agent for Q3 quarterly report',
'read:financials:q3'
);
if (sapGrant.granted) {
pass('SAP API permission obtained');
log(` Restrictions bound: ${sapGrant.restrictions.join(', ')}`, 'cyan');
// Step 2b: Enforce restrictions before proceeding
if (sapGrant.grantToken) {
const violation = authGuardian.enforceRestrictions(sapGrant.grantToken, { type: 'read', count: 50 });
if (!violation) {
pass('Restriction enforcement passed (read, 50 records)');
} else {
fail('Restriction enforcement', violation);
}
}
// Step 3: Delegate task -- write to DataAnalyst's namespace with verified identity
log('\n Step 3: Delegate task to DataAnalyst...', 'cyan');
blackboard.write('task:DataAnalyst:pending', {
taskId: randomUUID(),
instruction: 'Analyze Q3 financial data',
grantToken: sapGrant.grantToken,
constraints: sapGrant.restrictions,
}, 'orchestrator', undefined, 'orch-int-token');
pass('Task delegation recorded (identity verified)');
// Step 4: DataAnalyst writes result to its own namespace
log('\n Step 4: DataAnalyst completes task...', 'cyan');
blackboard.write('analytics:q3:result', {
revenue: 15000000,
expenses: 8500000,
netIncome: 6500000,
growth: 12.5,
analyzedBy: 'DataAnalyst',
timestamp: new Date().toISOString(),
}, 'DataAnalyst', 3600, 'da-int-token');
pass('Task result recorded (analyst namespace)');
// Step 4b: DataAnalyst tries to write to a forbidden namespace
let forbidden = false;
try {
blackboard.write('strategy:forbidden', { hack: true }, 'DataAnalyst', undefined, 'da-int-token');
} catch { forbidden = true; }
if (forbidden) {
pass('DataAnalyst blocked from strategy: namespace');
} else {
fail('DataAnalyst should not write to strategy: namespace');
}
// Step 5: Orchestrator caches final result
log('\n Step 5: Cache final result...', 'cyan');
blackboard.write('task:financial_analysis:q3', {
summary: 'Q3 analysis complete',
metrics: { revenue: 15000000, growth: 12.5 },
completedAt: new Date().toISOString(),
}, 'orchestrator', 86400, 'orch-int-token');
pass('Result cached (24h TTL)');
} else {
fail('SAP API permission denied', sapGrant.reason);
}