File size: 31,317 Bytes
81e3673
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Agent Maturity Authorization Security Tests (SECU-02.1).

Comprehensive tests for agent maturity level permissions:
- STUDENT: Read-only (search, list, get, summarize, present_chart)
- INTERN: Level 1-2 actions (draft, analyze, suggest, generate)
- SUPERVISED: Level 1-3 actions (update, submit_form, send_email)
- AUTONOMOUS: Level 1-4 actions (delete, execute, deploy, payment)

These are CRITICAL security tests ensuring governance enforcement.
Failure indicates a security vulnerability where agents can exceed permissions.
"""
import pytest
from fastapi.testclient import TestClient
from sqlalchemy.orm import Session
from tests.factories.agent_factory import (
    StudentAgentFactory,
    InternAgentFactory,
    SupervisedAgentFactory,
    AutonomousAgentFactory
)
from tests.factories.user_factory import UserFactory, AdminUserFactory
from core.models import AgentStatus, AgentRegistry
from core.agent_governance_service import AgentGovernanceService
from core.governance_cache import get_governance_cache


# ============================================================================
# STUDENT Agent Tests - Read-Only Only
# ============================================================================


class TestStudentAgentPermissions:
    """Test STUDENT agents can only perform read-only actions."""

    def test_student_can_search(self, db_session: Session):
        """STUDENT agents can search (complexity 1, read-only)."""
        student = StudentAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(student.id, "search")

        assert result["allowed"] is True
        assert result["action_complexity"] == 1
        assert result["agent_status"] == AgentStatus.STUDENT.value

    def test_student_can_read(self, db_session: Session):
        """STUDENT agents can read (complexity 1, read-only)."""
        student = StudentAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(student.id, "read")

        assert result["allowed"] is True
        assert result["action_complexity"] == 1

    def test_student_can_list(self, db_session: Session):
        """STUDENT agents can list (complexity 1, read-only)."""
        student = StudentAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(student.id, "list")

        assert result["allowed"] is True
        assert result["action_complexity"] == 1

    def test_student_can_summarize(self, db_session: Session):
        """STUDENT agents can summarize (complexity 1, read-only)."""
        student = StudentAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(student.id, "summarize")

        assert result["allowed"] is True
        assert result["action_complexity"] == 1

    def test_student_can_present_chart(self, db_session: Session):
        """STUDENT agents can present charts (complexity 1, read-only)."""
        student = StudentAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(student.id, "present_chart")

        assert result["allowed"] is True
        assert result["action_complexity"] == 1

    def test_student_blocked_from_stream(self, db_session: Session):
        """STUDENT agents CANNOT stream (complexity 2)."""
        student = StudentAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(student.id, "stream")

        assert result["allowed"] is False
        assert "lacks maturity" in result["reason"].lower() or "blocked" in result["reason"].lower()
        assert result["action_complexity"] == 2

    def test_student_blocked_from_analyze(self, db_session: Session):
        """STUDENT agents CANNOT analyze (complexity 2)."""
        student = StudentAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(student.id, "analyze")

        assert result["allowed"] is False
        assert result["action_complexity"] == 2

    def test_student_blocked_from_draft(self, db_session: Session):
        """STUDENT agents CANNOT draft (complexity 2)."""
        student = StudentAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(student.id, "draft")

        assert result["allowed"] is False
        assert result["action_complexity"] == 2

    def test_student_blocked_from_update(self, db_session: Session):
        """STUDENT agents CANNOT update state (complexity 3)."""
        student = StudentAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(student.id, "update")

        assert result["allowed"] is False
        assert result["action_complexity"] == 3

    def test_student_blocked_from_submit_form(self, db_session: Session):
        """STUDENT agents CANNOT submit forms (complexity 3)."""
        student = StudentAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(student.id, "submit_form")

        assert result["allowed"] is False
        assert result["action_complexity"] == 3

    def test_student_blocked_from_send_email(self, db_session: Session):
        """STUDENT agents CANNOT send email (complexity 3)."""
        student = StudentAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(student.id, "send_email")

        assert result["allowed"] is False
        assert result["action_complexity"] == 3

    def test_student_blocked_from_delete(self, db_session: Session):
        """STUDENT agents CANNOT delete (complexity 4 - CRITICAL)."""
        student = StudentAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(student.id, "delete")

        assert result["allowed"] is False
        assert result["action_complexity"] == 4

    def test_student_blocked_from_execute(self, db_session: Session):
        """STUDENT agents CANNOT execute commands (complexity 4 - CRITICAL)."""
        student = StudentAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(student.id, "execute")

        assert result["allowed"] is False
        assert result["action_complexity"] == 4

    def test_student_blocked_from_deploy(self, db_session: Session):
        """STUDENT agents CANNOT deploy (complexity 4 - CRITICAL)."""
        student = StudentAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(student.id, "deploy")

        assert result["allowed"] is False
        assert result["action_complexity"] == 4

    def test_student_blocked_from_payment(self, db_session: Session):
        """STUDENT agents CANNOT process payments (complexity 4 - CRITICAL)."""
        student = StudentAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(student.id, "payment")

        assert result["allowed"] is False
        assert result["action_complexity"] == 4

    def test_student_confidence_score_range(self, db_session: Session):
        """STUDENT agents have confidence score < 0.5."""
        student = StudentAgentFactory(_session=db_session)

        assert 0.0 <= student.confidence_score < 0.5

    def test_student_cannot_bypass_governance_via_cache(self, db_session: Session):
        """Test STUDENT cannot bypass governance by poisoning cache.

        Note: Current governance cache implementation returns cached values
        without database verification. This test documents the behavior.
        In production, cache poisoning should be prevented via:
        1. Cache signing/encryption
        2. TTL expiration
        3. Database verification for critical actions
        """
        student = StudentAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)
        cache = get_governance_cache()

        # First check - cache miss, checks database
        result1 = governance.can_perform_action(student.id, "delete")
        assert result1["allowed"] is False

        # Verify it was cached
        cached = cache.get(student.id, "delete")
        assert cached is not None
        assert cached["allowed"] is False

        # Even if we could poison the cache, the cache implementation
        # uses in-memory dict with no access control. This is a known
        # limitation mitigated by:
        # - Process isolation (separate worker processes)
        # - Cache TTL (automatic expiration)
        # - No external cache API (cache not exposed via endpoints)

        # Document: Cache poisoning requires code execution access
        # At that point, attacker has higher privileges anyway


# ============================================================================
# INTERN Agent Tests - Level 1-2 Actions
# ============================================================================


class TestInternAgentPermissions:
    """Test INTERN agents can perform level 1-2 actions."""

    def test_intern_can_search(self, db_session: Session):
        """INTERN agents can search (complexity 1)."""
        intern = InternAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(intern.id, "search")

        assert result["allowed"] is True
        assert result["action_complexity"] == 1

    def test_intern_can_analyze(self, db_session: Session):
        """INTERN agents can analyze (complexity 2)."""
        intern = InternAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(intern.id, "analyze")

        assert result["allowed"] is True
        assert result["action_complexity"] == 2

    def test_intern_can_suggest(self, db_session: Session):
        """INTERN agents can suggest (complexity 2)."""
        intern = InternAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(intern.id, "suggest")

        assert result["allowed"] is True
        assert result["action_complexity"] == 2

    def test_intern_can_draft(self, db_session: Session):
        """INTERN agents can draft (complexity 2)."""
        intern = InternAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(intern.id, "draft")

        assert result["allowed"] is True
        assert result["action_complexity"] == 2

    def test_intern_can_generate(self, db_session: Session):
        """INTERN agents can generate (complexity 2)."""
        intern = InternAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(intern.id, "generate")

        assert result["allowed"] is True
        assert result["action_complexity"] == 2

    def test_intern_can_stream(self, db_session: Session):
        """INTERN agents can stream (complexity 2)."""
        intern = InternAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(intern.id, "stream")

        assert result["allowed"] is True
        assert result["action_complexity"] == 2

    def test_intern_can_submit(self, db_session: Session):
        """INTERN agents can submit (complexity 2 - NOT submit_form)."""
        intern = InternAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(intern.id, "submit")

        assert result["allowed"] is True
        assert result["action_complexity"] == 2

    def test_intern_blocked_from_update(self, db_session: Session):
        """INTERN agents CANNOT update state (complexity 3)."""
        intern = InternAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(intern.id, "update")

        assert result["allowed"] is False
        assert result["action_complexity"] == 3

    def test_intern_blocked_from_submit_form(self, db_session: Session):
        """INTERN agents CANNOT submit forms (complexity 3)."""
        intern = InternAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(intern.id, "submit_form")

        assert result["allowed"] is False
        assert result["action_complexity"] == 3

    def test_intern_blocked_from_send_email(self, db_session: Session):
        """INTERN agents CANNOT send email (complexity 3)."""
        intern = InternAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(intern.id, "send_email")

        assert result["allowed"] is False
        assert result["action_complexity"] == 3

    def test_intern_blocked_from_delete(self, db_session: Session):
        """INTERN agents CANNOT delete (complexity 4 - CRITICAL)."""
        intern = InternAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(intern.id, "delete")

        assert result["allowed"] is False
        assert result["action_complexity"] == 4

    def test_intern_blocked_from_execute(self, db_session: Session):
        """INTERN agents CANNOT execute (complexity 4 - CRITICAL)."""
        intern = InternAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(intern.id, "execute")

        assert result["allowed"] is False
        assert result["action_complexity"] == 4

    def test_intern_confidence_score_range(self, db_session: Session):
        """INTERN agents have confidence score 0.5-0.7."""
        intern = InternAgentFactory(_session=db_session)

        assert 0.5 <= intern.confidence_score < 0.7


# ============================================================================
# SUPERVISED Agent Tests - Level 1-3 Actions
# ============================================================================


class TestSupervisedAgentPermissions:
    """Test SUPERVISED agents can perform level 1-3 actions."""

    def test_supervised_can_search(self, db_session: Session):
        """SUPERVISED agents can search (complexity 1)."""
        supervised = SupervisedAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(supervised.id, "search")

        assert result["allowed"] is True
        assert result["action_complexity"] == 1

    def test_supervised_can_stream(self, db_session: Session):
        """SUPERVISED agents can stream (complexity 2)."""
        supervised = SupervisedAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(supervised.id, "stream")

        assert result["allowed"] is True
        assert result["action_complexity"] == 2

    def test_supervised_can_analyze(self, db_session: Session):
        """SUPERVISED agents can analyze (complexity 2)."""
        supervised = SupervisedAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(supervised.id, "analyze")

        assert result["allowed"] is True
        assert result["action_complexity"] == 2

    def test_supervised_can_update(self, db_session: Session):
        """SUPERVISED agents can update state (complexity 3)."""
        supervised = SupervisedAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(supervised.id, "update")

        assert result["allowed"] is True
        assert result["action_complexity"] == 3

    def test_supervised_can_submit_form(self, db_session: Session):
        """SUPERVISED agents can submit forms (complexity 3)."""
        supervised = SupervisedAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(supervised.id, "submit_form")

        assert result["allowed"] is True
        assert result["action_complexity"] == 3

    def test_supervised_can_send_email(self, db_session: Session):
        """SUPERVISED agents can send email (complexity 3)."""
        supervised = SupervisedAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(supervised.id, "send_email")

        assert result["allowed"] is True
        assert result["action_complexity"] == 3

    def test_supervised_can_create(self, db_session: Session):
        """SUPERVISED agents can create (complexity 3)."""
        supervised = SupervisedAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(supervised.id, "create")

        assert result["allowed"] is True
        assert result["action_complexity"] == 3

    def test_supervised_can_post_message(self, db_session: Session):
        """SUPERVISED agents can post messages (complexity 3)."""
        supervised = SupervisedAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(supervised.id, "post_message")

        assert result["allowed"] is True
        assert result["action_complexity"] == 3

    def test_supervised_blocked_from_delete(self, db_session: Session):
        """SUPERVISED agents CANNOT delete (complexity 4 - CRITICAL)."""
        supervised = SupervisedAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(supervised.id, "delete")

        assert result["allowed"] is False
        assert result["action_complexity"] == 4

    def test_supervised_blocked_from_execute(self, db_session: Session):
        """SUPERVISED agents CANNOT execute (complexity 4 - CRITICAL)."""
        supervised = SupervisedAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(supervised.id, "execute")

        assert result["allowed"] is False
        assert result["action_complexity"] == 4

    def test_supervised_blocked_from_deploy(self, db_session: Session):
        """SUPERVISED agents CANNOT deploy (complexity 4 - CRITICAL)."""
        supervised = SupervisedAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(supervised.id, "deploy")

        assert result["allowed"] is False
        assert result["action_complexity"] == 4

    def test_supervised_blocked_from_payment(self, db_session: Session):
        """SUPERVISED agents CANNOT process payments (complexity 4 - CRITICAL)."""
        supervised = SupervisedAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(supervised.id, "payment")

        assert result["allowed"] is False
        assert result["action_complexity"] == 4

    def test_supervised_confidence_score_range(self, db_session: Session):
        """SUPERVISED agents have confidence score 0.7-0.9."""
        supervised = SupervisedAgentFactory(_session=db_session)

        assert 0.7 <= supervised.confidence_score < 0.9


# ============================================================================
# AUTONOMOUS Agent Tests - Full Execution (Level 1-4)
# ============================================================================


class TestAutonomousAgentPermissions:
    """Test AUTONOMOUS agents have full execution权限."""

    def test_autonomous_can_search(self, db_session: Session):
        """AUTONOMOUS agents can search (complexity 1)."""
        autonomous = AutonomousAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(autonomous.id, "search")

        assert result["allowed"] is True
        assert result["action_complexity"] == 1

    def test_autonomous_can_stream(self, db_session: Session):
        """AUTONOMOUS agents can stream (complexity 2)."""
        autonomous = AutonomousAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(autonomous.id, "stream")

        assert result["allowed"] is True
        assert result["action_complexity"] == 2

    def test_autonomous_can_analyze(self, db_session: Session):
        """AUTONOMOUS agents can analyze (complexity 2)."""
        autonomous = AutonomousAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(autonomous.id, "analyze")

        assert result["allowed"] is True
        assert result["action_complexity"] == 2

    def test_autonomous_can_update(self, db_session: Session):
        """AUTONOMOUS agents can update (complexity 3)."""
        autonomous = AutonomousAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(autonomous.id, "update")

        assert result["allowed"] is True
        assert result["action_complexity"] == 3

    def test_autonomous_can_delete(self, db_session: Session):
        """AUTONOMOUS agents can delete (complexity 4 - CRITICAL)."""
        autonomous = AutonomousAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(autonomous.id, "delete")

        assert result["allowed"] is True
        assert result["action_complexity"] == 4

    def test_autonomous_can_execute(self, db_session: Session):
        """AUTONOMOUS agents can execute (complexity 4 - CRITICAL)."""
        autonomous = AutonomousAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(autonomous.id, "execute")

        assert result["allowed"] is True
        assert result["action_complexity"] == 4

    def test_autonomous_can_deploy(self, db_session: Session):
        """AUTONOMOUS agents can deploy (complexity 4 - CRITICAL)."""
        autonomous = AutonomousAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(autonomous.id, "deploy")

        assert result["allowed"] is True
        assert result["action_complexity"] == 4

    def test_autonomous_can_payment(self, db_session: Session):
        """AUTONOMOUS agents can process payments (complexity 4 - CRITICAL)."""
        autonomous = AutonomousAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(autonomous.id, "payment")

        assert result["allowed"] is True
        assert result["action_complexity"] == 4

    def test_autonomous_can_send_email(self, db_session: Session):
        """AUTONOMOUS agents can send email (complexity 3)."""
        autonomous = AutonomousAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(autonomous.id, "send_email")

        assert result["allowed"] is True
        assert result["action_complexity"] == 3

    def test_autonomous_confidence_score_range(self, db_session: Session):
        """AUTONOMOUS agents have confidence score >= 0.9."""
        autonomous = AutonomousAgentFactory(_session=db_session)

        assert 0.9 <= autonomous.confidence_score <= 1.0


# ============================================================================
# Maturity Promotion/Regression Tests
# ============================================================================


class TestMaturityTransitions:
    """Test maturity level changes invalidate cache."""

    def test_promotion_student_to_intern(self, db_session: Session):
        """Test promoting STUDENT to INTERN grants new permissions."""
        student = StudentAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)
        cache = get_governance_cache()

        # Initially blocked from streaming
        result1 = governance.can_perform_action(student.id, "stream")
        assert result1["allowed"] is False

        # Promote to INTERN
        student.status = AgentStatus.INTERN.value
        student.confidence_score = 0.6
        db_session.commit()

        # Invalidate cache
        cache.invalidate(student.id)

        # Now allowed to stream
        result2 = governance.can_perform_action(student.id, "stream")
        assert result2["allowed"] is True

    def test_regression_autonomous_to_supervised(self, db_session: Session):
        """Test demoting AUTONOMOUS to SUPERVISED revokes critical permissions."""
        autonomous = AutonomousAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)
        cache = get_governance_cache()

        # Initially allowed to delete
        result1 = governance.can_perform_action(autonomous.id, "delete")
        assert result1["allowed"] is True

        # Demote to SUPERVISED
        autonomous.status = AgentStatus.SUPERVISED.value
        autonomous.confidence_score = 0.8
        db_session.commit()

        # Invalidate cache
        cache.invalidate(autonomous.id)

        # Now blocked from delete
        result2 = governance.can_perform_action(autonomous.id, "delete")
        assert result2["allowed"] is False

    def test_multiple_maturity_changes(self, db_session: Session):
        """Test multiple maturity transitions maintain correct permissions."""
        agent = StudentAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)
        cache = get_governance_cache()

        # STUDENT: blocked from analyze
        result = governance.can_perform_action(agent.id, "analyze")
        assert result["allowed"] is False

        # Promote to INTERN
        agent.status = AgentStatus.INTERN.value
        agent.confidence_score = 0.6
        db_session.commit()
        cache.invalidate(agent.id)

        # INTERN: allowed to analyze
        result = governance.can_perform_action(agent.id, "analyze")
        assert result["allowed"] is True

        # Promote to SUPERVISED
        agent.status = AgentStatus.SUPERVISED.value
        agent.confidence_score = 0.8
        db_session.commit()
        cache.invalidate(agent.id)

        # SUPERVISED: still allowed to analyze
        result = governance.can_perform_action(agent.id, "analyze")
        assert result["allowed"] is True

        # Promote to AUTONOMOUS
        agent.status = AgentStatus.AUTONOMOUS.value
        agent.confidence_score = 0.95
        db_session.commit()
        cache.invalidate(agent.id)

        # AUTONOMOUS: still allowed to analyze
        result = governance.can_perform_action(agent.id, "analyze")
        assert result["allowed"] is True


# ============================================================================
# Edge Cases and Boundary Tests
# ============================================================================


class TestMaturityEdgeCases:
    """Test edge cases and boundary conditions."""

    def test_nonexistent_agent(self, db_session: Session):
        """Test governance check for non-existent agent."""
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action("nonexistent-agent-id", "delete")

        assert result["allowed"] is False
        assert "not found" in result["reason"].lower()

    def test_invalid_action_type(self, db_session: Session):
        """Test governance check for unknown action type."""
        autonomous = AutonomousAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(autonomous.id, "unknown_action_xyz")

        # Should handle gracefully (default to blocking or assume safe)
        assert "allowed" in result

    def test_confidence_score_boundaries(self, db_session: Session):
        """Test confidence score boundaries match maturity levels."""
        from tests.factories.agent_factory import AgentFactory

        # Test boundary at 0.5 (STUDENT/INTERN)
        agent1 = AgentFactory.create(
            confidence_score=0.49,
            status=AgentStatus.STUDENT.value,
            _session=db_session
        )
        assert agent1.confidence_score < 0.5

        agent2 = AgentFactory.create(
            confidence_score=0.50,
            status=AgentStatus.INTERN.value,
            _session=db_session
        )
        assert agent2.confidence_score >= 0.5

        # Test boundary at 0.7 (INTERN/SUPERVISED)
        agent3 = AgentFactory.create(
            confidence_score=0.69,
            status=AgentStatus.INTERN.value,
            _session=db_session
        )
        assert agent3.confidence_score < 0.7

        agent4 = AgentFactory.create(
            confidence_score=0.70,
            status=AgentStatus.SUPERVISED.value,
            _session=db_session
        )
        assert agent4.confidence_score >= 0.7

        # Test boundary at 0.9 (SUPERVISED/AUTONOMOUS)
        agent5 = AgentFactory.create(
            confidence_score=0.89,
            status=AgentStatus.SUPERVISED.value,
            _session=db_session
        )
        assert agent5.confidence_score < 0.9

        agent6 = AgentFactory.create(
            confidence_score=0.90,
            status=AgentStatus.AUTONOMOUS.value,
            _session=db_session
        )
        assert agent6.confidence_score >= 0.9

    def test_governance_reason_provided(self, db_session: Session):
        """Test governance checks provide reason for denial."""
        student = StudentAgentFactory(_session=db_session)
        governance = AgentGovernanceService(db_session)

        result = governance.can_perform_action(student.id, "delete")

        assert "reason" in result
        assert len(result["reason"]) > 0
        # Reason should mention maturity or permissions
        reason_lower = result["reason"].lower()
        assert any(term in reason_lower for term in ["maturity", "permission", "blocked", "lacks"])