-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathtest-phase9.ts
More file actions
1882 lines (1683 loc) · 63.6 KB
/
test-phase9.ts
File metadata and controls
1882 lines (1683 loc) · 63.6 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
/**
* Phase 9: Agent Runtime & Console — Test Suite
*
* Tests for:
* 9a — SandboxPolicy: command matching, path scoping, risk assessment
* 9b — ShellExecutor: process spawning, timeout, concurrency
* 9c — FileAccessor: scoped read/write/list, traversal protection
* 9d — ApprovalGate: approval flow, auto-approve, history
* 9e — AgentRuntime: integrated exec/read/write with policy + approval
* 9f — ConsoleUI: commands, feed, status, command handlers
* 9g — Orchestrator Wiring: blackboard, budget, FSM, adapters via console
* 9h — StrategyAgent: pools, workload partitioning, adaptive strategy
* 9i — Pipe Mode: JSON stdin/stdout protocol
*
* Run with: npx ts-node test-phase9.ts
*/
import * as path from 'path';
import * as fs from 'fs';
import * as os from 'os';
import { EventEmitter } from 'events';
import {
SandboxPolicy,
ShellExecutor,
FileAccessor,
ApprovalGate,
AgentRuntime,
RuntimePolicyError,
RuntimeApprovalError,
} from './lib/agent-runtime';
import type {
SandboxPolicyConfig,
ShellResult,
ShellOptions,
FileResult,
ApprovalRequest,
ApprovalDecision,
RuntimeAuditEntry,
AgentRuntimeOptions,
} from './lib/agent-runtime';
import { ConsoleUI } from './lib/console-ui';
import type { ConsoleStatus, FeedEntry, ConsoleUIOptions } from './lib/console-ui';
import { LockedBlackboard } from './lib/locked-blackboard';
import { FederatedBudget } from './lib/federated-budget';
import { JourneyFSM } from './lib/fsm-journey';
import { AdapterRegistry } from './adapters/adapter-registry';
import {
StrategyAgent,
adaptiveStrategy,
} from './lib/strategy-agent';
import type {
AgentTemplate,
StrategyPlan,
SystemSnapshot,
PoolStatus,
} from './lib/strategy-agent';
// ============================================================================
// TEST UTILITIES
// ============================================================================
const colors = {
green: '\x1b[32m',
red: '\x1b[31m',
reset: '\x1b[0m',
bold: '\x1b[1m',
} as const;
let passed = 0;
let failed = 0;
function log(msg: string, color: keyof typeof colors = 'reset') {
console.log(`${colors[color]}${msg}${colors.reset}`);
}
function header(title: string) {
console.log('\n' + '='.repeat(64));
log(` ${title}`, 'bold');
console.log('='.repeat(64));
}
function pass(test: string) { log(` [PASS] ${test}`, 'green'); passed++; }
function fail(test: string, err?: string) {
log(` [FAIL] ${test}`, 'red');
if (err) log(` ${err}`, 'red');
failed++;
}
function assert(condition: boolean, test: string, detail?: string) {
if (condition) pass(test);
else fail(test, detail);
}
async function assertRejects(fn: () => Promise<unknown>, test: string) {
try { await fn(); fail(test, 'Expected to reject'); }
catch { pass(test); }
}
/** Create a temp directory for file tests */
function makeTempDir(): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nai-test-'));
return dir;
}
/** Clean up a temp directory */
function cleanTempDir(dir: string): void {
try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* ignore */ }
}
// ============================================================================
// 9a — SANDBOX POLICY
// ============================================================================
function testSandboxPolicy() {
header('Phase 9a — SandboxPolicy');
// 1. Constructor sets basePath
{
const policy = new SandboxPolicy({ basePath: '/test/project' });
assert(policy.basePath === path.resolve('/test/project'), 'Constructor resolves basePath');
}
// 2. Empty allowedCommands blocks all
{
const policy = new SandboxPolicy({ basePath: '/test', allowedCommands: [] });
assert(!policy.isCommandAllowed('npm test'), 'Empty allowlist blocks all commands');
}
// 3. Allowed command passes
{
const policy = new SandboxPolicy({ basePath: '/test', allowedCommands: ['npm *'] });
assert(policy.isCommandAllowed('npm test'), 'Matching allowed command passes');
}
// 4. Non-matching command blocked
{
const policy = new SandboxPolicy({ basePath: '/test', allowedCommands: ['npm *'] });
assert(!policy.isCommandAllowed('rm -rf /'), 'Non-matching command blocked');
}
// 5. Blocked commands override allowed
{
const policy = new SandboxPolicy({
basePath: '/test',
allowedCommands: ['*'],
blockedCommands: ['rm -rf /'],
});
assert(!policy.isCommandAllowed('rm -rf /'), 'Blocked overrides allowed');
}
// 6. Empty command blocked
{
const policy = new SandboxPolicy({ basePath: '/test', allowedCommands: ['*'] });
assert(!policy.isCommandAllowed(''), 'Empty command blocked');
assert(!policy.isCommandAllowed(' '), 'Whitespace-only command blocked');
}
// 7. Glob matching works with wildcards
{
const policy = new SandboxPolicy({ basePath: '/test', allowedCommands: ['git *'] });
assert(policy.isCommandAllowed('git status'), 'git status matches git *');
assert(policy.isCommandAllowed('git push origin main'), 'git push matches git *');
assert(!policy.isCommandAllowed('npm test'), 'npm test does not match git *');
}
// 8. requiresApproval detects patterns
{
const policy = new SandboxPolicy({
basePath: '/test',
allowedCommands: ['*'],
approvalRequired: ['rm *', 'git push*'],
});
assert(policy.requiresApproval('rm foo.txt'), 'rm requires approval');
assert(policy.requiresApproval('git push origin main'), 'git push requires approval');
assert(!policy.requiresApproval('npm test'), 'npm test does not require approval');
}
// 9. Risk assessment
{
const policy = new SandboxPolicy({ basePath: '/test' });
assert(policy.assessRisk('rm -rf node_modules') === 'high', 'rm is high risk');
assert(policy.assessRisk('git status') === 'medium', 'git is medium risk');
assert(policy.assessRisk('echo hello') === 'low', 'echo is low risk');
}
// 10. Path validation (within scope)
{
const base = path.resolve('/test/project');
const policy = new SandboxPolicy({ basePath: base, allowedPaths: ['.'] });
assert(policy.isPathAllowed('src/index.ts'), 'Relative path within scope allowed');
}
// 11. Path traversal blocked
{
const base = path.resolve('/test/project');
const policy = new SandboxPolicy({ basePath: base });
const result = policy.resolvePath('../../etc/passwd');
assert(result === null, 'Path traversal returns null');
}
// 12. Blocked paths override allowed
{
const base = path.resolve('/test/project');
const policy = new SandboxPolicy({
basePath: base,
allowedPaths: ['.'],
blockedPaths: ['secrets'],
});
assert(!policy.isPathAllowed('secrets/key.pem'), 'Blocked path rejected');
assert(policy.isPathAllowed('src/app.ts'), 'Non-blocked path allowed');
}
// 13. allowCommand dynamically adds pattern
{
const policy = new SandboxPolicy({ basePath: '/test', allowedCommands: [] });
assert(!policy.isCommandAllowed('python script.py'), 'Initially blocked');
policy.allowCommand('python *');
assert(policy.isCommandAllowed('python script.py'), 'Allowed after dynamic add');
}
// 14. disallowCommand removes pattern
{
const policy = new SandboxPolicy({ basePath: '/test', allowedCommands: ['npm *'] });
assert(policy.isCommandAllowed('npm test'), 'Initially allowed');
policy.disallowCommand('npm *');
assert(!policy.isCommandAllowed('npm test'), 'Blocked after disallow');
}
// 15. allowPath dynamically adds scope
{
const base = path.resolve('/test/project');
const policy = new SandboxPolicy({ basePath: base, allowedPaths: [] });
assert(!policy.isPathAllowed('src/index.ts'), 'Initially not allowed');
policy.allowPath('src');
assert(policy.isPathAllowed('src/index.ts'), 'Allowed after dynamic add');
}
// 16. blockPath dynamically blocks scope
{
const base = path.resolve('/test/project');
const policy = new SandboxPolicy({ basePath: base, allowedPaths: ['.'] });
assert(policy.isPathAllowed('.env'), 'Initially allowed');
policy.blockPath('.env');
// .env at root should now be blocked
assert(!policy.isPathAllowed('.env'), 'Blocked after dynamic block');
}
// 17. getConfig returns a copy
{
const policy = new SandboxPolicy({ basePath: '/test', allowedCommands: ['npm *'] });
const config = policy.getConfig();
assert(config.allowedCommands.includes('npm *'), 'Config includes allowed commands');
assert(typeof config.defaultTimeoutMs === 'number', 'Config has default timeout');
}
// 18. Default blocked commands include dangerous patterns
{
const policy = new SandboxPolicy({ basePath: '/test', allowedCommands: ['*'] });
assert(!policy.isCommandAllowed('rm -rf /'), 'rm -rf / blocked by default');
assert(!policy.isCommandAllowed('format C:'), 'format blocked by default');
}
// 19. Case-insensitive glob matching
{
const policy = new SandboxPolicy({ basePath: '/test', allowedCommands: ['NPM *'] });
assert(policy.isCommandAllowed('npm test'), 'Case-insensitive match works');
}
// 20. Default properties
{
const policy = new SandboxPolicy({ basePath: '/test' });
assert(policy.maxConcurrentProcesses === 5, 'Default maxConcurrentProcesses is 5');
assert(policy.defaultTimeoutMs === 30_000, 'Default timeout is 30s');
assert(policy.defaultMaxOutputBytes === 1_048_576, 'Default max output is 1MB');
assert(policy.autoApproveReads === true, 'Auto-approve reads by default');
}
}
// ============================================================================
// 9b — SHELL EXECUTOR
// ============================================================================
async function testShellExecutor() {
header('Phase 9b — ShellExecutor');
const isWindows = process.platform === 'win32';
// 1. Execute a simple command
{
const policy = new SandboxPolicy({ basePath: process.cwd(), allowedCommands: ['echo *'] });
const executor = new ShellExecutor(policy);
const result = await executor.execute('echo hello');
assert(result.stdout.trim() === 'hello', 'Simple echo produces correct output');
assert(result.exitCode === 0, 'Exit code is 0');
assert(!result.timedOut, 'Not timed out');
assert(!result.truncated, 'Not truncated');
}
// 2. Policy-blocked command throws
{
const policy = new SandboxPolicy({ basePath: process.cwd(), allowedCommands: ['echo *'] });
const executor = new ShellExecutor(policy);
await assertRejects(
() => executor.execute('rm somefile'),
'Blocked command throws RuntimePolicyError',
);
}
// 3. Command with non-zero exit
{
const cmd = isWindows ? 'cmd /c exit 1' : 'exit 1';
const policy = new SandboxPolicy({ basePath: process.cwd(), allowedCommands: ['*'] });
const executor = new ShellExecutor(policy);
const result = await executor.execute(cmd);
assert(result.exitCode !== 0, 'Non-zero exit code captured');
}
// 4. Duration tracking
{
const policy = new SandboxPolicy({ basePath: process.cwd(), allowedCommands: ['echo *'] });
const executor = new ShellExecutor(policy);
const result = await executor.execute('echo timing');
assert(result.durationMs >= 0, 'Duration is non-negative');
}
// 5. Running process count
{
const policy = new SandboxPolicy({ basePath: process.cwd(), allowedCommands: ['echo *'] });
const executor = new ShellExecutor(policy);
assert(executor.running === 0, 'No running processes initially');
}
// 6. Stderr captured
{
const cmd = isWindows ? 'echo error 1>&2' : 'echo error >&2';
const policy = new SandboxPolicy({ basePath: process.cwd(), allowedCommands: ['echo *'] });
const executor = new ShellExecutor(policy);
const result = await executor.execute(cmd);
assert(result.stderr.includes('error'), 'Stderr captured');
}
// 7. Timeout terminates command
{
const cmd = isWindows ? 'ping -n 10 127.0.0.1' : 'sleep 10';
const allowed = isWindows ? 'ping *' : 'sleep *';
const policy = new SandboxPolicy({ basePath: process.cwd(), allowedCommands: [allowed] });
const executor = new ShellExecutor(policy);
const result = await executor.execute(cmd, { timeoutMs: 500 });
assert(result.timedOut, 'Command timed out');
}
// 8. Concurrency limit
{
const policy = new SandboxPolicy({
basePath: process.cwd(),
allowedCommands: ['echo *'],
maxConcurrentProcesses: 1,
});
const executor = new ShellExecutor(policy);
// Start one process
const p1 = executor.execute('echo first');
// Try to start another while first is likely still active
// Since echo is so fast, we just verify the executor tracks count correctly
await p1;
assert(executor.running === 0, 'After completion, running count is 0');
}
}
// ============================================================================
// 9c — FILE ACCESSOR
// ============================================================================
async function testFileAccessor() {
header('Phase 9c — FileAccessor');
const tmpDir = makeTempDir();
try {
// Setup test files
fs.writeFileSync(path.join(tmpDir, 'test.txt'), 'hello world');
fs.mkdirSync(path.join(tmpDir, 'subdir'));
fs.writeFileSync(path.join(tmpDir, 'subdir', 'nested.txt'), 'nested content');
const policy = new SandboxPolicy({ basePath: tmpDir, allowedPaths: ['.'] });
const accessor = new FileAccessor(policy);
// 1. Read existing file
{
const result = await accessor.read('test.txt', 'agent-1');
assert(result.success, 'Read existing file succeeds');
assert(result.content === 'hello world', 'Read content matches');
}
// 2. Read nested file
{
const result = await accessor.read('subdir/nested.txt', 'agent-1');
assert(result.success, 'Read nested file succeeds');
assert(result.content === 'nested content', 'Nested content matches');
}
// 3. Read non-existent file
{
const result = await accessor.read('nonexistent.txt', 'agent-1');
assert(!result.success, 'Read non-existent file fails');
assert(!!result.error, 'Error message present');
}
// 4. Write new file
{
const result = await accessor.write('output.txt', 'written by agent', 'agent-1');
assert(result.success, 'Write file succeeds');
const content = fs.readFileSync(path.join(tmpDir, 'output.txt'), 'utf-8');
assert(content === 'written by agent', 'Written content matches');
}
// 5. Write creates parent directories
{
const result = await accessor.write('deep/nested/file.txt', 'deep write', 'agent-1');
assert(result.success, 'Write with nested dirs succeeds');
const content = fs.readFileSync(path.join(tmpDir, 'deep', 'nested', 'file.txt'), 'utf-8');
assert(content === 'deep write', 'Deep write content matches');
}
// 6. List directory
{
const result = await accessor.list('.', 'agent-1');
assert(result.success, 'List directory succeeds');
assert(Array.isArray(result.entries), 'Returns entries array');
assert(result.entries!.some(e => e === 'test.txt'), 'Lists test.txt');
assert(result.entries!.some(e => e === 'subdir/'), 'Lists subdir/ with trailing slash');
}
// 7. List subdirectory
{
const result = await accessor.list('subdir', 'agent-1');
assert(result.success, 'List subdirectory succeeds');
assert(result.entries!.includes('nested.txt'), 'Lists nested.txt');
}
// 8. Path traversal blocked
{
const result = await accessor.read('../../etc/passwd', 'agent-1');
assert(!result.success, 'Path traversal read blocked');
assert(result.error?.includes('traversal') === true, 'Error mentions traversal');
}
// 9. Write traversal blocked
{
const result = await accessor.write('../../tmp/evil.txt', 'bad', 'agent-1');
assert(!result.success, 'Path traversal write blocked');
}
// 10. Not-allowed path blocked
{
const strictPolicy = new SandboxPolicy({
basePath: tmpDir,
allowedPaths: ['subdir'],
});
const strictAccessor = new FileAccessor(strictPolicy);
const result = await strictAccessor.read('test.txt', 'agent-1');
assert(!result.success, 'File outside allowed paths blocked');
}
// 11. Duration tracking
{
const result = await accessor.read('test.txt', 'agent-1');
assert(result.durationMs >= 0, 'Duration is non-negative');
}
// 12. List non-existent directory
{
const result = await accessor.list('nonexistent', 'agent-1');
assert(!result.success, 'List non-existent dir fails');
}
} finally {
cleanTempDir(tmpDir);
}
}
// ============================================================================
// 9d — APPROVAL GATE
// ============================================================================
async function testApprovalGate() {
header('Phase 9d — ApprovalGate');
// 1. Auto-approve all
{
const gate = new ApprovalGate(undefined, true);
const decision = await gate.request({
type: 'shell', target: 'npm test', agentId: 'tester', risk: 'low', timestamp: Date.now(),
});
assert(decision.approved, 'Auto-approve grants all requests');
assert(decision.approvedBy === 'auto-approve-all', 'ApprovedBy is auto-approve-all');
}
// 2. No callback denies
{
const gate = new ApprovalGate();
const decision = await gate.request({
type: 'shell', target: 'rm -rf /', agentId: 'rogue', risk: 'high', timestamp: Date.now(),
});
assert(!decision.approved, 'No callback means denied');
assert(decision.reason?.includes('No approval callback') === true, 'Reason mentions no callback');
}
// 3. Custom callback approves
{
const gate = new ApprovalGate(async (req) => {
return { approved: true, approvedBy: 'human', reason: 'Looks safe' };
});
const decision = await gate.request({
type: 'shell', target: 'npm test', agentId: 'tester', risk: 'low', timestamp: Date.now(),
});
assert(decision.approved, 'Custom callback approves');
assert(decision.approvedBy === 'human', 'ApprovedBy from callback');
}
// 4. Custom callback denies
{
const gate = new ApprovalGate(async (req) => {
return { approved: false, reason: 'Too risky' };
});
const decision = await gate.request({
type: 'shell', target: 'rm -rf /', agentId: 'rogue', risk: 'high', timestamp: Date.now(),
});
assert(!decision.approved, 'Custom callback denies');
assert(decision.reason === 'Too risky', 'Denial reason preserved');
}
// 5. History tracking
{
const gate = new ApprovalGate(undefined, true);
await gate.request({ type: 'shell', target: 'cmd1', agentId: 'a', risk: 'low', timestamp: Date.now() });
await gate.request({ type: 'shell', target: 'cmd2', agentId: 'b', risk: 'low', timestamp: Date.now() });
const history = gate.getHistory();
assert(history.length === 2, 'History has 2 entries');
assert(history[0].request.target === 'cmd1', 'First entry is cmd1');
}
// 6. Stats tracking
{
const gate = new ApprovalGate(async (req) => {
return { approved: req.risk !== 'high' };
});
await gate.request({ type: 'shell', target: 'safe', agentId: 'a', risk: 'low', timestamp: Date.now() });
await gate.request({ type: 'shell', target: 'danger', agentId: 'b', risk: 'high', timestamp: Date.now() });
const stats = gate.getStats();
assert(stats.total === 2, 'Total is 2');
assert(stats.approved === 1, 'One approved');
assert(stats.denied === 1, 'One denied');
}
// 7. Events emitted
{
const gate = new ApprovalGate(undefined, true);
let requestedCount = 0;
let decidedCount = 0;
gate.on('requested', () => { requestedCount++; });
gate.on('decided', () => { decidedCount++; });
await gate.request({ type: 'shell', target: 'test', agentId: 'x', risk: 'low', timestamp: Date.now() });
assert(requestedCount === 1, 'Requested event emitted');
assert(decidedCount === 1, 'Decided event emitted');
}
// 8. Conditional approval based on risk
{
const gate = new ApprovalGate(async (req) => {
if (req.risk === 'high') return { approved: false, reason: 'High risk' };
return { approved: true, approvedBy: 'policy' };
});
const low = await gate.request({ type: 'shell', target: 'echo hi', agentId: 'a', risk: 'low', timestamp: Date.now() });
const high = await gate.request({ type: 'shell', target: 'rm -rf /', agentId: 'b', risk: 'high', timestamp: Date.now() });
assert(low.approved && !high.approved, 'Risk-based conditional approval works');
}
}
// ============================================================================
// 9e — AGENT RUNTIME (Integrated)
// ============================================================================
async function testAgentRuntime() {
header('Phase 9e — AgentRuntime (Integrated)');
const tmpDir = makeTempDir();
try {
fs.writeFileSync(path.join(tmpDir, 'readme.txt'), 'Hello from test');
// 1. Runtime constructor creates all components
{
const rt = new AgentRuntime({
policy: { basePath: tmpDir, allowedCommands: ['echo *'] },
autoApproveAll: true,
});
assert(rt.policy instanceof SandboxPolicy, 'Policy is SandboxPolicy');
assert(rt.shell instanceof ShellExecutor, 'Shell is ShellExecutor');
assert(rt.files instanceof FileAccessor, 'Files is FileAccessor');
assert(rt.gate instanceof ApprovalGate, 'Gate is ApprovalGate');
}
// 2. exec runs allowed command
{
const rt = new AgentRuntime({
policy: { basePath: tmpDir, allowedCommands: ['echo *'] },
autoApproveAll: true,
});
const result = await rt.exec('echo runtime test', 'agent-a');
assert(result.stdout.trim() === 'runtime test', 'Exec runs and captures output');
}
// 3. exec blocks disallowed command
{
const rt = new AgentRuntime({
policy: { basePath: tmpDir, allowedCommands: ['echo *'] },
autoApproveAll: true,
});
await assertRejects(
() => rt.exec('rm somefile', 'agent-a'),
'Exec rejects disallowed command',
);
}
// 4. exec with approval required — denied
{
const rt = new AgentRuntime({
policy: { basePath: tmpDir, allowedCommands: ['rm *'], approvalRequired: ['rm *'] },
onApproval: async () => ({ approved: false, reason: 'Nope' }),
});
await assertRejects(
() => rt.exec('rm temp.txt', 'agent-a'),
'Exec denied by approval gate',
);
}
// 5. exec with approval required — approved
{
const rt = new AgentRuntime({
policy: { basePath: tmpDir, allowedCommands: ['echo *'], approvalRequired: ['echo *'] },
onApproval: async () => ({ approved: true, approvedBy: 'test' }),
});
const result = await rt.exec('echo approved', 'agent-a');
assert(result.stdout.trim() === 'approved', 'Exec succeeds after approval');
}
// 6. readFile within scope
{
const rt = new AgentRuntime({
policy: { basePath: tmpDir, allowedCommands: [] },
autoApproveAll: true,
});
const result = await rt.readFile('readme.txt', 'agent-a');
assert(result.success, 'readFile succeeds');
assert(result.content === 'Hello from test', 'readFile content matches');
}
// 7. readFile outside scope
{
const rt = new AgentRuntime({
policy: { basePath: tmpDir, allowedPaths: ['subdir'] },
autoApproveAll: true,
});
const result = await rt.readFile('readme.txt', 'agent-a');
assert(!result.success, 'readFile outside allowed paths fails');
}
// 8. writeFile with approval
{
const rt = new AgentRuntime({
policy: { basePath: tmpDir },
onApproval: async () => ({ approved: true, approvedBy: 'test' }),
});
const result = await rt.writeFile('agent-output.txt', 'agent wrote this', 'agent-a');
assert(result.success, 'writeFile succeeds with approval');
const content = fs.readFileSync(path.join(tmpDir, 'agent-output.txt'), 'utf-8');
assert(content === 'agent wrote this', 'Written content matches');
}
// 9. writeFile denied without approval
{
const rt = new AgentRuntime({
policy: { basePath: tmpDir },
onApproval: async () => ({ approved: false, reason: 'No writes allowed' }),
});
const result = await rt.writeFile('blocked.txt', 'should not appear', 'agent-a');
assert(!result.success, 'writeFile denied without approval');
assert(!fs.existsSync(path.join(tmpDir, 'blocked.txt')), 'File was not created');
}
// 10. listDir
{
const rt = new AgentRuntime({
policy: { basePath: tmpDir },
autoApproveAll: true,
});
const result = await rt.listDir('.', 'agent-a');
assert(result.success, 'listDir succeeds');
assert(result.entries!.includes('readme.txt'), 'listDir includes readme.txt');
}
// 11. Audit log populated
{
const rt = new AgentRuntime({
policy: { basePath: tmpDir, allowedCommands: ['echo *'] },
autoApproveAll: true,
});
await rt.exec('echo audit test', 'auditor');
const log = rt.getAuditLog();
assert(log.length > 0, 'Audit log has entries');
assert(log.some(e => e.action === 'shell_execute'), 'Audit log has shell_execute entry');
}
// 12. Audit log cleared
{
const rt = new AgentRuntime({
policy: { basePath: tmpDir, allowedCommands: ['echo *'] },
autoApproveAll: true,
});
await rt.exec('echo audit', 'auditor');
assert(rt.getAuditLog().length > 0, 'Log has entries before clear');
rt.clearAuditLog();
assert(rt.getAuditLog().length === 0, 'Log empty after clear');
}
// 13. Events emitted on exec
{
const rt = new AgentRuntime({
policy: { basePath: tmpDir, allowedCommands: ['echo *'] },
autoApproveAll: true,
});
let started = false;
let completed = false;
rt.on('command:start', () => { started = true; });
rt.on('command:complete', () => { completed = true; });
await rt.exec('echo events', 'agent-a');
assert(started, 'command:start event emitted');
assert(completed, 'command:complete event emitted');
}
// 14. Policy violation event
{
const rt = new AgentRuntime({
policy: { basePath: tmpDir, allowedCommands: ['echo *'] },
autoApproveAll: true,
});
let violation = false;
rt.on('policy:violation', () => { violation = true; });
try { await rt.exec('rm badfile', 'agent-a'); } catch { /* expected */ }
assert(violation, 'policy:violation event emitted');
}
// 15. Approval events emitted
{
const rt = new AgentRuntime({
policy: { basePath: tmpDir, allowedCommands: ['echo *'], approvalRequired: ['echo *'] },
onApproval: async () => ({ approved: true }),
});
let approvalRequested = false;
let approvalDecided = false;
rt.on('approval:requested', () => { approvalRequested = true; });
rt.on('approval:decided', () => { approvalDecided = true; });
await rt.exec('echo approval-events', 'agent-a');
assert(approvalRequested, 'approval:requested event emitted');
assert(approvalDecided, 'approval:decided event emitted');
}
// 16. Audit entry has correct structure
{
const rt = new AgentRuntime({
policy: { basePath: tmpDir, allowedCommands: ['echo *'] },
autoApproveAll: true,
});
await rt.exec('echo structure', 'struct-agent');
const entry = rt.getAuditLog().find(e => e.action === 'shell_execute');
assert(!!entry, 'Shell execute audit entry exists');
assert(entry!.agentId === 'struct-agent', 'Audit entry agentId correct');
assert(entry!.target === 'echo structure', 'Audit entry target correct');
assert(!!entry!.timestamp, 'Audit entry has timestamp');
}
// 17. File access event emitted
{
const rt = new AgentRuntime({
policy: { basePath: tmpDir },
autoApproveAll: true,
});
let fileAccessMode = '';
rt.on('file:access', (_agentId: string, _path: string, mode: string) => { fileAccessMode = mode; });
await rt.readFile('readme.txt', 'reader');
assert(fileAccessMode === 'read', 'file:access emitted with read mode');
}
// 18. RuntimePolicyError has correct code
{
const err = new RuntimePolicyError('test');
assert(err.code === 'POLICY_VIOLATION', 'RuntimePolicyError code');
assert(err.name === 'RuntimePolicyError', 'RuntimePolicyError name');
}
// 19. RuntimeApprovalError has correct code
{
const err = new RuntimeApprovalError('test');
assert(err.code === 'APPROVAL_DENIED', 'RuntimeApprovalError code');
assert(err.name === 'RuntimeApprovalError', 'RuntimeApprovalError name');
}
// 20. listDir outside scope blocked
{
const rt = new AgentRuntime({
policy: { basePath: tmpDir, allowedPaths: ['subdir'] },
autoApproveAll: true,
});
const result = await rt.listDir('.', 'agent-a');
assert(!result.success, 'listDir outside allowed paths blocked');
}
} finally {
cleanTempDir(tmpDir);
}
}
// ============================================================================
// 9f — CONSOLE UI
// ============================================================================
// Mock writable stream for capturing console output
class MockWritable extends EventEmitter {
data = '';
write(chunk: string): boolean { this.data += chunk; return true; }
end(): void { /* noop */ }
}
async function testConsoleUI() {
header('Phase 9f — ConsoleUI');
// 1. Constructor defaults
{
const ui = new ConsoleUI();
assert(!ui.isRunning, 'Not running initially');
const status = ui.getStatus();
assert(status.agents.active === 0, 'Default agents active is 0');
assert(status.budget.usedPercent === 0, 'Default budget is 0%');
assert(status.fsm.state === 'idle', 'Default FSM state is idle');
}
// 2. Custom options
{
const ui = new ConsoleUI({
title: 'TestUI',
version: '1.2.3',
prompt: '$ ',
});
const status = ui.getStatus();
assert(status.version === '1.2.3', 'Custom version set');
}
// 3. Register and retrieve command
{
const ui = new ConsoleUI();
let called = false;
ui.command('test-cmd', () => { called = true; });
// Verify it's registered (help won't throw)
ui.showHelp();
assert(true, 'Command registered without error');
}
// 4. Log adds to feed
{
const ui = new ConsoleUI();
ui.log('Test message', 'info');
ui.log('Warning msg', 'warn');
ui.log('Error msg', 'error');
const feed = ui.getFeed();
assert(feed.length === 3, 'Feed has 3 entries');
assert(feed[0].level === 'info', 'First entry is info');
assert(feed[1].level === 'warn', 'Second entry is warn');
assert(feed[2].level === 'error', 'Third entry is error');
}
// 5. Feed max limit
{
const ui = new ConsoleUI({ maxFeedEntries: 5 });
for (let i = 0; i < 10; i++) {
ui.log(`msg ${i}`);
}
assert(ui.getFeed().length === 5, 'Feed capped at maxFeedEntries');
assert(ui.getFeed()[0].message.includes('msg 5'), 'Oldest entries evicted');
}
// 6. Clear feed
{
const ui = new ConsoleUI();
ui.log('to be cleared');
assert(ui.getFeed().length === 1, 'Feed has entry');
ui.clearFeed();
assert(ui.getFeed().length === 0, 'Feed cleared');
}
// 7. Update status
{
const ui = new ConsoleUI();
ui.updateStatus({
agents: { active: 3, total: 5 },
budget: { usedPercent: 42 },
fsm: { state: 'executing' },
pendingApprovals: 2,
});
const s = ui.getStatus();
assert(s.agents.active === 3, 'Agents active updated');
assert(s.budget.usedPercent === 42, 'Budget updated');
assert(s.fsm.state === 'executing', 'FSM state updated');
assert(s.pendingApprovals === 2, 'Pending approvals updated');
}
// 8. Feed emits event
{
const ui = new ConsoleUI();
let emittedEntry: FeedEntry | null = null;
ui.on('feed', (entry: FeedEntry) => { emittedEntry = entry; });
ui.log('event test', 'success');
assert(emittedEntry !== null, 'Feed event emitted');
assert(emittedEntry!.level === 'success', 'Feed event has correct level');
}
// 9. Success level icon
{
const ui = new ConsoleUI();
ui.log('success msg', 'success');
const entry = ui.getFeed()[0];
assert(entry.icon.includes('✓'), 'Success icon is checkmark');
}
// 10. Approval level icon
{
const ui = new ConsoleUI();
ui.log('approval msg', 'approval');
const entry = ui.getFeed()[0];
assert(entry.icon.includes('⏳'), 'Approval icon is hourglass');
}
// 11. renderHeader produces output
{
const output = new MockWritable();
const ui = new ConsoleUI({
output: output as unknown as NodeJS.WritableStream,
version: '4.13.1',
});
ui.renderHeader();
assert(output.data.includes('Network-AI'), 'Header contains title');
assert(output.data.includes('4.13.1'), 'Header contains version');
}
// 12. Built-in help command exists
{
const output = new MockWritable();
const ui = new ConsoleUI({
output: output as unknown as NodeJS.WritableStream,
});
ui.showHelp();
assert(output.data.includes('help'), 'Help lists help command');
assert(output.data.includes('exit'), 'Help lists exit command');
assert(output.data.includes('clear'), 'Help lists clear command');
}
// 13. Feed entry has timestamp
{
const ui = new ConsoleUI();
ui.log('timestamp test');
const entry = ui.getFeed()[0];
assert(entry.time.includes(':'), 'Time has colon separator');
}
// 14. Partial status update preserves other fields
{
const ui = new ConsoleUI();
ui.updateStatus({ agents: { active: 5, total: 10 } });
ui.updateStatus({ budget: { usedPercent: 75 } });
const s = ui.getStatus();
assert(s.agents.active === 5, 'Agents preserved after budget update');
assert(s.budget.usedPercent === 75, 'Budget updated');
}
// 15. Multiple commands can be registered
{
const ui = new ConsoleUI();
ui.command('cmd1', () => { });
ui.command('cmd2', () => { });
ui.command('cmd3', () => { });
// Built-ins: help, clear, exit, quit = 4 + 3 custom = 7
// Just verify no error
assert(true, 'Multiple commands registered');
}
// 16. Stop sets isRunning to false
{
const output = new MockWritable();