File size: 50,560 Bytes
fdfe81a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
"""Non-live tests for ``agents.runner.run_audit``.

These tests mock ``Runner.run`` so no network calls are made. They cover:

* **Bounded concurrency** β€” at most ``MAX_CONCURRENT_SLIDES`` (5) Slide
  Reviewer calls are ever in flight at once.
* **Must-flag guarantee** β€” when every agent returns ZERO findings, the
  Python orchestrator still emits ``safety_net``-tagged findings for every
  Jacobs marker hit (slides 1, 6, 7, 23, 24).
* **Retry helper** β€” fails twice with ``RateLimitError``, succeeds on the
  third attempt; verifies 3 calls happened with backoff in between.
* **Boundary validation** β€” drops findings with empty ``evidence`` or
  unknown ``category``.
* **Lead Auditor must-flag firewall** β€” even with a Lead Auditor mock that
  returns an empty result, every Jacobs marker hit becomes a safety_net
  finding (proving must-flag enforcement is in ``runner.py``, NOT inside
  the Lead Auditor agent).
* **Partial audit** β€” a slide whose final retry fails records an entry in
  ``FinalAuditResult.errors`` and the audit still completes.
"""
from __future__ import annotations

import asyncio
import inspect
from pathlib import Path
from types import SimpleNamespace
from typing import Any

import httpx
import openai
import pytest

from agents.context import AuditContext
from agents.output_schemas import (
    DeckFindings,
    Finding,
    FindingExtended,
    FindingMeta,
    FinalAuditResult,
    SeverityCounts,
    SlideEnvelopeExtended,
    SlideFindings,
)
from agents.runner import (
    MAX_CONCURRENT_SLIDES,
    MAX_RETRY_ATTEMPTS,
    MUST_FLAG_TERMS,
    SlideBriefing,
    _build_safety_net_finding,
    _finalise,
    _is_retriable,
    _python_fallback_merge,
    _run_with_retry,
    run_audit,
)
from rubric.loader import load_rubric
from schemas.parsed import ParsedDeck, ParsedSlide, RunInfo, ShapeInfo
from services.markers import Hit, find_text_markers_pure
from services.parser import parse_deck
from services.renderer import RenderResult


_DOC_REF = Path(__file__).parents[3] / "Doc Reference"
JACOBS_PATH = _DOC_REF / (
    "20260429 Jacobs Assessment of Compensation Peers - DRAFT 20260327 (3).pptx"
)


# ===========================================================================
# Fixtures
# ===========================================================================


@pytest.fixture(scope="module")
def rubric():
    return load_rubric()


@pytest.fixture(scope="module")
def jacobs_deck() -> ParsedDeck:
    return parse_deck(JACOBS_PATH)


@pytest.fixture
def jacobs_ctx(jacobs_deck, rubric, tmp_path) -> AuditContext:
    return AuditContext(
        parsed_deck=jacobs_deck,
        render_result=RenderResult(skipped=True, reason="unit test"),
        rubric=rubric,
        out_dir=tmp_path,
    )


def _synthetic_deck(
    *, n_slides: int, text_per_slide: dict[int, str] | None = None,
) -> ParsedDeck:
    text_per_slide = text_per_slide or {}
    slides: list[ParsedSlide] = []
    for i in range(1, n_slides + 1):
        body = text_per_slide.get(i, f"Slide {i} content")
        shape = ShapeInfo(
            shape_id=f"s{i}.shape1",
            shape_type="TEXT_BOX",
            name="Body",
            left=0,
            top=0,
            width=1000,
            height=500,
            text=body,
            runs=[],
            table_cells=[],
        )
        slides.append(
            ParsedSlide(slide_number=i, shapes=[shape], extracted_text=body)
        )
    return ParsedDeck(
        slide_count=n_slides,
        slide_width_emu=12192000,
        slide_height_emu=6858000,
        slides=slides,
    )


# ===========================================================================
# Mock Runner machinery
# ===========================================================================


class _MockRunner:
    """A drop-in replacement for ``agents.Runner`` for tests.

    Wraps ``run`` with an in-flight counter so we can verify bounded
    concurrency. Records every call so we can assert call counts and inputs.
    """

    def __init__(self, side_effect):
        self._side_effect = side_effect
        self.calls: list[dict[str, Any]] = []
        self._inflight = 0
        self.peak_inflight = 0
        self._inflight_lock = asyncio.Lock()

    async def run(self, agent, *, input=None, context=None, max_turns=10, **kwargs):
        async with self._inflight_lock:
            self._inflight += 1
            self.peak_inflight = max(self.peak_inflight, self._inflight)
        try:
            self.calls.append(
                {
                    "agent_name": agent.name,
                    "input": input,
                    "max_turns": max_turns,
                }
            )
            # side_effect can be sync or async; return a RunResult-shaped obj.
            result = self._side_effect(agent, input, context)
            if inspect.isawaitable(result):
                result = await result
            return result
        finally:
            async with self._inflight_lock:
                self._inflight -= 1


def _wrap_as_run_result(final_output: Any) -> Any:
    """Mimic the SDK RunResult shape that the runner extracts ``final_output`` from."""
    return SimpleNamespace(final_output=final_output)


# ===========================================================================
# 1. Boundary validation β€” empty evidence + unknown category dropped
# ===========================================================================


def test_finalise_drops_empty_evidence_and_unknown_category(rubric, jacobs_deck, tmp_path):
    """Boundary validator must drop bad findings before they reach the result."""
    ctx = AuditContext(
        parsed_deck=jacobs_deck,
        render_result=RenderResult(skipped=True),
        rubric=rubric,
        out_dir=tmp_path,
    )
    bogus_extended = FindingExtended(
        category="title_slide",
        severity="high",
        confidence=0.9,
        title="Drop me β€” empty evidence",
        description="should be dropped",
        evidence="",  # empty β†’ must be dropped
        suggested_fix="n/a",
        guideline_reference="title_slide.no_draft",
        finding_meta=FindingMeta(source="agent_slide", must_flag=False),
    )
    bad_category = FindingExtended(
        category="totally_made_up_category",
        severity="medium",
        confidence=0.7,
        title="Drop me β€” unknown category",
        description="should be dropped",
        evidence="some text",
        suggested_fix="n/a",
        guideline_reference="bogus.rule",
        finding_meta=FindingMeta(source="agent_slide", must_flag=False),
    )
    keeper = FindingExtended(
        category="title_slide",
        severity="medium",
        confidence=0.85,
        title="Keep me",
        description="legit",
        evidence="real evidence quote",
        suggested_fix="fix it",
        guideline_reference="title_slide.no_draft",
        finding_meta=FindingMeta(source="agent_slide", must_flag=False),
    )
    envelope = SlideEnvelopeExtended(
        slide_number=2, image_url=None,
        findings=[bogus_extended, bad_category, keeper],
    )
    lead_result = FinalAuditResult(
        job_id="t",
        file_name="x.pptx",
        slide_count=jacobs_deck.slide_count,
        summary=SeverityCounts(),
        slides=[envelope],
        errors=[],
    )

    final = _finalise(
        job_id="t",
        file_name="x.pptx",
        slide_count=jacobs_deck.slide_count,
        lead_result=lead_result,
        marker_hits={n: [] for n in range(1, jacobs_deck.slide_count + 1)},
        ctx=ctx,
        errors=[],
    )

    s2 = final.slides[1]  # slide_number=2
    titles = [f.title for f in s2.findings]
    assert "Drop me β€” empty evidence" not in titles
    assert "Drop me β€” unknown category" not in titles
    assert "Keep me" in titles


# ===========================================================================
# 2. Retry helper β€” RateLimitError twice then success
# ===========================================================================


def _make_rate_limit_error() -> openai.RateLimitError:
    """Synthesise a RateLimitError without hitting the live API."""
    request = httpx.Request("POST", "https://api.openai.com/v1/responses")
    response = httpx.Response(429, request=request, json={"error": "rate"})
    return openai.RateLimitError(
        message="rate limited",
        response=response,
        body={"error": "rate"},
    )


def _make_500_error() -> openai.APIStatusError:
    request = httpx.Request("POST", "https://api.openai.com/v1/responses")
    response = httpx.Response(503, request=request, json={"error": "boom"})
    return openai.APIStatusError(
        message="server error", response=response, body={"error": "boom"},
    )


def _make_400_error() -> openai.BadRequestError:
    request = httpx.Request("POST", "https://api.openai.com/v1/responses")
    response = httpx.Response(400, request=request, json={"error": "bad"})
    return openai.BadRequestError(
        message="bad request", response=response, body={"error": "bad"},
    )


@pytest.mark.asyncio
async def test_run_with_retry_succeeds_after_two_rate_limits():
    """Two RateLimitError attempts then success β€” total of 3 invocations."""
    sleep_calls: list[float] = []

    async def no_sleep(seconds: float):
        sleep_calls.append(seconds)

    invocations = {"count": 0}

    async def factory():
        invocations["count"] += 1
        if invocations["count"] <= 2:
            raise _make_rate_limit_error()
        return "ok"

    result = await _run_with_retry(
        factory,
        label="test",
        sleep=no_sleep,
        rng=lambda: 0.0,
    )

    assert result == "ok"
    assert invocations["count"] == 3, "factory must have been called 3 times"
    # Two backoff sleeps before attempts 2 and 3 (2s and 4s base + 0 jitter).
    assert sleep_calls == [2.0, 4.0]


@pytest.mark.asyncio
async def test_run_with_retry_retries_on_5xx():
    """``APIStatusError(>=500)`` is retriable."""
    sleeps: list[float] = []

    async def no_sleep(s: float):
        sleeps.append(s)

    n = {"count": 0}

    async def factory():
        n["count"] += 1
        if n["count"] == 1:
            raise _make_500_error()
        return "ok"

    res = await _run_with_retry(factory, label="t", sleep=no_sleep, rng=lambda: 0.0)
    assert res == "ok"
    assert n["count"] == 2


@pytest.mark.asyncio
async def test_run_with_retry_does_not_retry_on_4xx():
    """A non-429 4xx is permanent β€” must propagate without retrying."""
    n = {"count": 0}

    async def factory():
        n["count"] += 1
        raise _make_400_error()

    with pytest.raises(openai.BadRequestError):
        await _run_with_retry(factory, label="t", sleep=_no_sleep, rng=lambda: 0.0)
    assert n["count"] == 1


@pytest.mark.asyncio
async def test_run_with_retry_gives_up_after_max_attempts():
    """All 4 attempts hit RateLimit β†’ propagate the last RateLimitError."""
    n = {"count": 0}

    async def factory():
        n["count"] += 1
        raise _make_rate_limit_error()

    with pytest.raises(openai.RateLimitError):
        await _run_with_retry(factory, label="t", sleep=_no_sleep, rng=lambda: 0.0)
    assert n["count"] == MAX_RETRY_ATTEMPTS


def test_is_retriable_classifies_correctly():
    assert _is_retriable(_make_rate_limit_error()) is True
    assert _is_retriable(_make_500_error()) is True
    assert _is_retriable(openai.APITimeoutError(httpx.Request("GET", "/"))) is True
    assert _is_retriable(_make_400_error()) is False
    assert _is_retriable(ValueError("bare exception")) is False


async def _no_sleep(_seconds: float) -> None:
    return None


# ===========================================================================
# 3. Bounded concurrency β€” semaphore caps in-flight Runner.run at 5
# ===========================================================================


@pytest.mark.asyncio
async def test_bounded_concurrency_caps_at_5(jacobs_ctx, monkeypatch):
    """A 33-slide deck with slow mocks must NEVER exceed 5 in flight."""

    async def slow_side_effect(agent, input_str, context):
        # Yield to the event loop so other coroutines can pile up β€” this
        # demonstrates the semaphore actually bounds concurrency.
        await asyncio.sleep(0.01)
        if agent.name == "Slide Reviewer":
            # Extract slide_number from the briefing JSON.
            import json
            try:
                payload = json.loads(input_str)
                slide_n = payload["slide_number"]
            except Exception:  # noqa: BLE001
                slide_n = 1
            return _wrap_as_run_result(SlideFindings(slide_number=slide_n, findings=[]))
        if agent.name == "Deck Consistency":
            return _wrap_as_run_result(DeckFindings(findings=[]))
        if agent.name == "Lead Auditor":
            return _wrap_as_run_result(
                FinalAuditResult(
                    job_id="job1",
                    file_name="jacobs.pptx",
                    slide_count=jacobs_ctx.parsed_deck.slide_count,
                    summary=SeverityCounts(),
                    slides=[],
                    errors=[],
                )
            )
        raise AssertionError(f"unexpected agent: {agent.name}")

    mock = _MockRunner(slow_side_effect)
    final = await run_audit(
        jacobs_ctx,
        job_id="job1",
        file_name="jacobs.pptx",
        runner=mock,
    )
    assert isinstance(final, FinalAuditResult)
    # Slide-reviewer calls = 33; plus 1 deck consistency + 1 lead auditor.
    slide_calls = [c for c in mock.calls if c["agent_name"] == "Slide Reviewer"]
    assert len(slide_calls) == jacobs_ctx.parsed_deck.slide_count
    # The peak in-flight count across ALL agents must be <= 5.
    # (Deck Consistency and Lead Auditor run after slides β€” they shouldn't
    # push the peak above 5 either.)
    assert mock.peak_inflight <= MAX_CONCURRENT_SLIDES, (
        f"peak in-flight {mock.peak_inflight} exceeded {MAX_CONCURRENT_SLIDES}"
    )


# ===========================================================================
# 4. Must-flag guarantee β€” agents return ZERO findings; safety_net still fires
# ===========================================================================


@pytest.mark.asyncio
async def test_must_flag_safety_net_fires_when_agents_return_nothing(jacobs_ctx):
    """The most important test: the Python guarantee must hold even if every
    LLM call returns no findings. Every marker hit on Jacobs slides
    1, 6, 7, 23, 24 must end up in the final result as a safety_net finding
    with finding_meta.source='safety_net' and finding_meta.must_flag=True.
    """

    async def empty_side_effect(agent, input_str, context):
        if agent.name == "Slide Reviewer":
            import json
            payload = json.loads(input_str)
            slide_n = payload["slide_number"]
            return _wrap_as_run_result(SlideFindings(slide_number=slide_n, findings=[]))
        if agent.name == "Deck Consistency":
            return _wrap_as_run_result(DeckFindings(findings=[]))
        if agent.name == "Lead Auditor":
            # Lead Auditor returns ZERO findings β€” proves must-flag enforcement
            # does NOT depend on the Lead Auditor adding them.
            return _wrap_as_run_result(
                FinalAuditResult(
                    job_id="job1",
                    file_name="jacobs.pptx",
                    slide_count=jacobs_ctx.parsed_deck.slide_count,
                    summary=SeverityCounts(),
                    slides=[
                        SlideEnvelopeExtended(slide_number=n, image_url=None, findings=[])
                        for n in range(1, jacobs_ctx.parsed_deck.slide_count + 1)
                    ],
                    errors=[],
                )
            )
        raise AssertionError(f"unexpected: {agent.name}")

    mock = _MockRunner(empty_side_effect)
    final = await run_audit(
        jacobs_ctx,
        job_id="job1",
        file_name="jacobs.pptx",
        runner=mock,
    )

    # The marker-related safety_net rule_ids in the rubric. Scope this
    # assertion to JUST marker findings β€” post-determinism-fix the runner
    # also injects safety_net findings for confidentiality / palette
    # violations on every slide of the Jacobs deck, but those are NOT
    # must_flag and have different rule_ids.
    marker_rule_ids = {
        "title_slide.no_draft", "writing_style.no_internal_comments",
    }
    expected_slides = {1, 6, 7, 23, 24}
    actual_slides = set()
    for env in final.slides:
        for f in env.findings:
            if f.finding_meta.source != "safety_net":
                continue
            if f.guideline_reference not in marker_rule_ids:
                continue  # confidentiality / palette safety_nets β€” different contract
            actual_slides.add(env.slide_number)
            # Acceptance: every marker safety_net has must_flag=True.
            assert f.finding_meta.must_flag is True
            # Severity must be high (DRAFT/TW question/Page to be updated).
            assert f.severity == "high"
            # Evidence must be non-empty.
            assert f.evidence.strip()

    assert actual_slides == expected_slides, (
        f"expected marker safety_net findings on {expected_slides}, "
        f"got {actual_slides}"
    )


@pytest.mark.asyncio
async def test_safety_net_always_injected_even_when_agent_covered_hit(jacobs_ctx):
    """Determinism contract (post-regression-fix): the safety_net for a marker
    hit is ALWAYS injected, regardless of whether the LLM already produced a
    finding quoting the same marker.

    Rationale: at temperature=1, the LLM's choice to surface the marker is
    stochastic. The previous "suppress when agent covers" logic let counts of
    marker-related findings drift across repeated runs of the same deck. The
    fix is to pin marker findings to a Python floor β€” one safety_net per hit,
    deterministically. The LLM finding (if any) is kept alongside and gets
    its finding_meta.must_flag promoted to True so the dashboard badges it.
    """

    async def smart_side(agent, input_str, context):
        if agent.name == "Slide Reviewer":
            import json
            payload = json.loads(input_str)
            slide_n = payload["slide_number"]
            findings = []
            if slide_n == 1:
                # Agent quotes DRAFT in its evidence. Old behaviour: safety_net
                # would be suppressed. New behaviour: safety_net still fires.
                findings = [
                    Finding(
                        category="title_slide",
                        severity="high",
                        confidence=0.95,
                        title="DRAFT designator on title slide",
                        description="Title slide carries DRAFT.",
                        evidence="April 29, 2026 – DRAFT 20260327",
                        suggested_fix="Remove DRAFT.",
                        guideline_reference="title_slide.no_draft",
                    )
                ]
            return _wrap_as_run_result(
                SlideFindings(slide_number=slide_n, findings=findings)
            )
        if agent.name == "Deck Consistency":
            return _wrap_as_run_result(DeckFindings(findings=[]))
        if agent.name == "Lead Auditor":
            # Echo the slide-1 finding into the merge result (extended shape).
            slides = []
            for n in range(1, jacobs_ctx.parsed_deck.slide_count + 1):
                if n == 1:
                    slides.append(
                        SlideEnvelopeExtended(
                            slide_number=1, image_url=None,
                            findings=[
                                FindingExtended(
                                    category="title_slide",
                                    severity="high",
                                    confidence=0.95,
                                    title="DRAFT designator on title slide",
                                    description="Title slide carries DRAFT.",
                                    evidence="April 29, 2026 – DRAFT 20260327",
                                    suggested_fix="Remove DRAFT.",
                                    guideline_reference="title_slide.no_draft",
                                    finding_meta=FindingMeta(
                                        source="agent_slide", must_flag=False
                                    ),
                                )
                            ],
                        )
                    )
                else:
                    slides.append(
                        SlideEnvelopeExtended(
                            slide_number=n, image_url=None, findings=[]
                        )
                    )
            return _wrap_as_run_result(
                FinalAuditResult(
                    job_id="job1",
                    file_name="jacobs.pptx",
                    slide_count=jacobs_ctx.parsed_deck.slide_count,
                    summary=SeverityCounts(),
                    slides=slides,
                    errors=[],
                )
            )
        raise AssertionError(agent.name)

    mock = _MockRunner(smart_side)
    final = await run_audit(jacobs_ctx, job_id="job1", file_name="jacobs.pptx", runner=mock)

    s1 = final.slides[0]
    # New contract: agent finding is kept AND a safety_net finding is appended.
    sources = [f.finding_meta.source for f in s1.findings]
    assert "agent_slide" in sources, "agent finding must be retained"
    assert "safety_net" in sources, (
        "safety_net must be injected even when agent covered the hit"
    )
    # The agent finding's must_flag is promoted to True due to overlap.
    agent_findings = [f for f in s1.findings if f.finding_meta.source == "agent_slide"]
    assert all(f.finding_meta.must_flag is True for f in agent_findings)

    # The OTHER must-flag slides (6, 7, 23, 24) all still get safety_net findings.
    for n in (6, 7, 23, 24):
        env = final.slides[n - 1]
        sn = [f for f in env.findings if f.finding_meta.source == "safety_net"]
        assert len(sn) >= 1, f"slide {n} missing safety_net finding"


# ===========================================================================
# 5. Lead Auditor source code MUST NOT contain safety_net injection logic
# ===========================================================================


def test_lead_auditor_module_does_not_inject_safety_net():
    """Static guard: must-flag enforcement lives in runner.py, not lead_auditor.py."""
    import agents.lead_auditor as la
    src_path = Path(la.__file__)
    src = src_path.read_text(encoding="utf-8")
    # The string 'safety_net' must not appear as injection logic in lead_auditor.
    # It may appear in the prompt prose ONLY via the Markdown file β€” not here.
    assert "safety_net" not in src, (
        "lead_auditor.py must not contain 'safety_net' β€” that logic belongs to runner.py"
    )
    # Also: no SDK handoffs.
    assert "handoffs=" not in src and "Handoff(" not in src


# ===========================================================================
# 6. Partial audit β€” a slide whose retry budget is exhausted records an error
# ===========================================================================


@pytest.mark.asyncio
async def test_partial_audit_when_one_slide_fails_permanently(jacobs_ctx, monkeypatch):
    """If slide 3's retries all fail, it ends up in errors[]; other slides succeed."""
    # Patch sleep so retries don't actually wait.
    import agents.runner as runner_module

    async def no_sleep(_):
        return None

    real_with_retry = runner_module._run_with_retry

    async def patched_with_retry(coro_factory, *, label, **kwargs):
        return await real_with_retry(
            coro_factory, label=label, sleep=no_sleep, rng=lambda: 0.0,
        )

    monkeypatch.setattr(runner_module, "_run_with_retry", patched_with_retry)

    async def side(agent, input_str, context):
        if agent.name == "Slide Reviewer":
            import json
            payload = json.loads(input_str)
            slide_n = payload["slide_number"]
            if slide_n == 3:
                # Permanent rate limit β€” exhausts retries.
                raise _make_rate_limit_error()
            return _wrap_as_run_result(SlideFindings(slide_number=slide_n, findings=[]))
        if agent.name == "Deck Consistency":
            return _wrap_as_run_result(DeckFindings(findings=[]))
        if agent.name == "Lead Auditor":
            return _wrap_as_run_result(
                FinalAuditResult(
                    job_id="job1",
                    file_name="jacobs.pptx",
                    slide_count=jacobs_ctx.parsed_deck.slide_count,
                    summary=SeverityCounts(),
                    slides=[
                        SlideEnvelopeExtended(slide_number=n, image_url=None, findings=[])
                        for n in range(1, jacobs_ctx.parsed_deck.slide_count + 1)
                    ],
                    errors=[],
                )
            )
        raise AssertionError(agent.name)

    mock = _MockRunner(side)
    final = await run_audit(jacobs_ctx, job_id="job1", file_name="jacobs.pptx", runner=mock)

    # The runner MUST NOT have aborted the whole audit.
    assert isinstance(final, FinalAuditResult)
    # Slide 3's failure must be recorded.
    assert any("slide 3" in e for e in final.errors), (
        f"expected slide 3 failure in errors, got {final.errors!r}"
    )
    # The other 32 slides must still appear in the result.
    assert len(final.slides) == jacobs_ctx.parsed_deck.slide_count


# ===========================================================================
# 7. _build_safety_net_finding β€” schema correctness on synthetic hit
# ===========================================================================


def test_build_safety_net_finding_uses_rubric_metadata(rubric):
    hit = Hit(
        term="DRAFT",
        offset=10,
        context_window="Some - DRAFT 20260327",
        source="shape",
        shape_id="s1.shape1",
    )
    f = _build_safety_net_finding(
        slide_n=1, hit=hit, must_flag_meta=rubric.metadata.must_flag_markers,
    )
    assert isinstance(f, FindingExtended)
    assert f.category == "title_slide"
    assert f.severity == "high"
    assert f.finding_meta.source == "safety_net"
    assert f.finding_meta.must_flag is True
    assert f.guideline_reference == "title_slide.no_draft"
    assert "DRAFT" in f.evidence
    assert "slide 1" in f.title.lower()
    assert f.confidence == 1.0


def test_build_safety_net_finding_for_internal_comment(rubric):
    hit = Hit(
        term="TW question",
        offset=0,
        context_window="TW question - Is Accenture US?",
        source="shape",
        shape_id="s7.shape1",
    )
    f = _build_safety_net_finding(
        slide_n=7, hit=hit, must_flag_meta=rubric.metadata.must_flag_markers,
    )
    assert f.category == "writing_style"
    assert f.severity == "high"
    assert f.guideline_reference == "writing_style.no_internal_comments"
    assert f.finding_meta.must_flag is True


# ===========================================================================
# 8. Strict PRD shape β€” Finding (no finding_meta) vs FindingExtended
# ===========================================================================


def test_finding_strict_shape_has_no_finding_meta_field():
    """The strict PRD shape MUST be Finding (no finding_meta) β€” verify the
    serialised JSON Schema does not contain a finding_meta property."""
    schema = Finding.model_json_schema()
    assert "finding_meta" not in schema.get("properties", {})
    expected = {
        "category", "severity", "confidence", "title", "description",
        "evidence", "suggested_fix", "guideline_reference",
    }
    assert set(schema["properties"].keys()) == expected


def test_finding_extended_shape_adds_only_finding_meta():
    schema = FindingExtended.model_json_schema()
    expected = {
        "category", "severity", "confidence", "title", "description",
        "evidence", "suggested_fix", "guideline_reference", "finding_meta",
    }
    assert set(schema["properties"].keys()) == expected


def test_strict_dump_drops_finding_meta_via_exclude():
    """When serialising a FindingExtended for export, exclude={'finding_meta'} must work."""
    fe = FindingExtended(
        category="title_slide", severity="high", confidence=0.9,
        title="t", description="d", evidence="e", suggested_fix="s",
        guideline_reference="title_slide.no_draft",
        finding_meta=FindingMeta(source="agent_slide", must_flag=False),
    )
    dumped = fe.model_dump(exclude={"finding_meta"})
    assert "finding_meta" not in dumped
    assert set(dumped.keys()) == {
        "category", "severity", "confidence", "title", "description",
        "evidence", "suggested_fix", "guideline_reference",
    }


# ===========================================================================
# 9. Python fallback merge β€” produces a usable result without an LLM
# ===========================================================================


def test_python_fallback_merge_assembles_envelopes():
    sf1 = SlideFindings(
        slide_number=1,
        findings=[
            Finding(
                category="title_slide", severity="high", confidence=0.9,
                title="t", description="d", evidence="ev",
                suggested_fix="s", guideline_reference="title_slide.no_draft",
            )
        ],
    )
    sf2 = SlideFindings(slide_number=2, findings=[])
    df = DeckFindings(
        findings=[
            Finding(
                category="terminology", severity="medium", confidence=0.8,
                title="drift", description="slides 1+2",
                evidence="quote A vs quote B",
                suggested_fix="align", guideline_reference="terminology.consistent",
            )
        ]
    )

    final = _python_fallback_merge(
        job_id="j", file_name="x.pptx", slide_count=2,
        slide_findings_by_n={1: sf1, 2: sf2}, deck_findings=df,
    )
    assert final.slide_count == 2
    s1 = final.slides[0]
    assert len(s1.findings) == 2  # 1 slide + 1 deck (parked on slide 1)
    sources = sorted({f.finding_meta.source for f in s1.findings})
    assert sources == ["agent_deck", "agent_slide"]


# ===========================================================================
# 10. End-to-end run_audit on synthetic deck β€” must-flag injection works
# ===========================================================================


@pytest.mark.asyncio
async def test_run_audit_synthetic_must_flag_injection(rubric, tmp_path):
    """A 3-slide synthetic deck where slide 2 has 'DRAFT' in its body."""
    deck = _synthetic_deck(
        n_slides=3,
        text_per_slide={
            1: "Title page",
            2: "Quarterly report β€” DRAFT for review only",
            3: "Conclusion",
        },
    )
    ctx = AuditContext(
        parsed_deck=deck,
        render_result=RenderResult(skipped=True),
        rubric=rubric,
        out_dir=tmp_path,
    )

    async def empty(agent, input_str, context):
        if agent.name == "Slide Reviewer":
            import json
            payload = json.loads(input_str)
            return _wrap_as_run_result(
                SlideFindings(slide_number=payload["slide_number"], findings=[])
            )
        if agent.name == "Deck Consistency":
            return _wrap_as_run_result(DeckFindings(findings=[]))
        if agent.name == "Lead Auditor":
            return _wrap_as_run_result(
                FinalAuditResult(
                    job_id="syn", file_name="syn.pptx", slide_count=3,
                    summary=SeverityCounts(),
                    slides=[
                        SlideEnvelopeExtended(slide_number=n, image_url=None, findings=[])
                        for n in (1, 2, 3)
                    ],
                    errors=[],
                )
            )
        raise AssertionError(agent.name)

    mock = _MockRunner(empty)
    final = await run_audit(ctx, job_id="syn", file_name="syn.pptx", runner=mock)

    # Slide 2 must have the safety_net DRAFT finding (writing_style category β€”
    # the rubric maps the 'DRAFT' marker via must_flag_markers; on a body
    # shape it routes to title_slide.no_draft if the term is exactly 'DRAFT').
    s2 = final.slides[1]
    draft_sn = [
        f for f in s2.findings
        if f.finding_meta.source == "safety_net"
        and f.guideline_reference == "title_slide.no_draft"
    ]
    assert len(draft_sn) == 1
    assert draft_sn[0].category == "title_slide"
    assert draft_sn[0].severity == "high"
    assert draft_sn[0].finding_meta.must_flag is True

    # NOTE (post-determinism-fix): the runner now also injects deterministic
    # safety_net findings for missing/mispositioned confidentiality
    # statements. The synthetic deck has no confidentiality footer on any
    # slide, so EVERY slide gets one such finding. We assert the expected
    # marker finding still exists and that confidentiality safety_net
    # findings appear on every slide.
    for n in (1, 2, 3):
        env = final.slides[n - 1]
        conf = [
            f for f in env.findings
            if f.finding_meta.source == "safety_net"
            and f.category == "confidentiality_statement"
        ]
        assert len(conf) == 1, (
            f"slide {n}: expected exactly one confidentiality safety_net "
            f"finding, got {[f.title for f in env.findings]}"
        )
    # Summary is recomputed: 1 DRAFT high + 3 confidentiality high = 4.
    assert final.summary.high == 4
    assert final.summary.medium == 0
    assert final.summary.low == 0


# ===========================================================================
# 11. on_slide_done callback fires once per slide + initial tick
# ===========================================================================


@pytest.mark.asyncio
async def test_progress_callback_fires_per_slide(rubric, tmp_path):
    """on_slide_done must be called: once with (0, 3) before the gather, then
    once per slide as each reviewer settles β€” 4 calls total ending at (3, 3).
    Intermediate values may arrive in any order due to concurrency.
    """
    deck = _synthetic_deck(n_slides=3)
    ctx = AuditContext(
        parsed_deck=deck,
        render_result=RenderResult(skipped=True),
        rubric=rubric,
        out_dir=tmp_path,
    )

    async def empty(agent, input_str, context):
        if agent.name == "Slide Reviewer":
            import json
            payload = json.loads(input_str)
            return _wrap_as_run_result(
                SlideFindings(slide_number=payload["slide_number"], findings=[])
            )
        if agent.name == "Deck Consistency":
            return _wrap_as_run_result(DeckFindings(findings=[]))
        if agent.name == "Lead Auditor":
            return _wrap_as_run_result(
                FinalAuditResult(
                    job_id="t", file_name="t.pptx", slide_count=3,
                    summary=SeverityCounts(),
                    slides=[
                        SlideEnvelopeExtended(slide_number=n, image_url=None, findings=[])
                        for n in (1, 2, 3)
                    ],
                    errors=[],
                )
            )
        raise AssertionError(agent.name)

    ticks: list[tuple[int, int]] = []

    def callback(completed: int, total: int) -> None:
        ticks.append((completed, total))

    mock = _MockRunner(empty)
    await run_audit(ctx, job_id="t", runner=mock, on_slide_done=callback)

    # 1 initial tick + 3 per-slide ticks = 4 total
    assert len(ticks) == 4, f"expected 4 ticks, got {len(ticks)}: {ticks}"
    # First tick is always the 0/N initialisation.
    assert ticks[0] == (0, 3), f"first tick must be (0, 3), got {ticks[0]}"
    # Final tick must show all slides complete.
    assert ticks[-1] == (3, 3), f"last tick must be (3, 3), got {ticks[-1]}"
    # All totals must be 3.
    assert all(t == 3 for _, t in ticks), f"all totals must be 3: {ticks}"


# ===========================================================================
# 12. Determinism regression β€” single-shot safety_net counts are bit-stable
# ===========================================================================
#
# These tests pin down the regression discovered when two consecutive audits
# of the same Jacobs deck produced 48 vs 14 findings. Root cause: the
# deterministic Python checks (text_markers, confidentiality, palette) were
# being passed as advisory data into the LLM prompt at temperature=1, and
# the model was stochastically choosing not to surface them. The fix in
# ``runner.py::_finalise`` promotes those checks to ALWAYS-fire safety_net
# findings post-LLM, independent of what the LLM emitted.


@pytest.mark.asyncio
async def test_single_shot_draft_safety_net_fires_with_empty_llm_output(jacobs_ctx, monkeypatch):
    """Determinism floor (text_markers): even when the (mocked) LLM returns
    EMPTY SlideFindings β€” the worst case at temp=1 β€” every Jacobs DRAFT/
    TW-question/Page-to-be-updated hit must surface as a safety_net finding.

    This is the regression test for the 48->14 finding drop: when the LLM
    skipped the marker-related findings, the prior code suppressed the
    safety_net too because it incorrectly considered the absent finding as
    "covered". The fix decouples safety_net injection from LLM output
    entirely.
    """
    monkeypatch.setenv("SLIDE_REVIEWER_MODE", "single_shot")

    async def empty(agent, input_str, context):
        if agent.name == "Slide Reviewer":
            # Single-shot input is a list[dict]; agentic input is a JSON
            # string. The runner accepts both shapes β€” we only need to
            # return an empty SlideFindings keyed to the right slide.
            slide_n: int
            if isinstance(input_str, list):
                # Multimodal content β€” find the input_text part.
                content = input_str[0].get("content", [])
                text_part = next(
                    (p for p in content if p.get("type") == "input_text"),
                    None,
                )
                import json as _json
                payload = _json.loads(text_part["text"]) if text_part else {}
                slide_n = payload.get("slide_number", 1)
            else:
                import json as _json
                slide_n = _json.loads(input_str)["slide_number"]
            return _wrap_as_run_result(
                SlideFindings(slide_number=slide_n, findings=[])
            )
        if agent.name == "Deck Consistency":
            return _wrap_as_run_result(DeckFindings(findings=[]))
        if agent.name == "Lead Auditor":
            return _wrap_as_run_result(
                FinalAuditResult(
                    job_id="d", file_name="jacobs.pptx",
                    slide_count=jacobs_ctx.parsed_deck.slide_count,
                    summary=SeverityCounts(),
                    slides=[
                        SlideEnvelopeExtended(slide_number=n, image_url=None, findings=[])
                        for n in range(1, jacobs_ctx.parsed_deck.slide_count + 1)
                    ],
                    errors=[],
                )
            )
        raise AssertionError(agent.name)

    mock = _MockRunner(empty)
    final = await run_audit(
        jacobs_ctx, job_id="d", file_name="jacobs.pptx", runner=mock,
    )

    # Every safety_net finding tied to an internal-marker rule must be high
    # severity and must_flag=True β€” regardless of LLM output.
    marker_rule_ids = {"title_slide.no_draft", "writing_style.no_internal_comments"}
    sn_marker_findings = [
        f
        for env in final.slides
        for f in env.findings
        if f.finding_meta.source == "safety_net"
        and f.guideline_reference in marker_rule_ids
    ]
    assert len(sn_marker_findings) >= 5, (
        "Jacobs deck has at least 5 known marker hits across slides "
        "1, 6, 7, 23, 24 β€” every one must produce a safety_net finding "
        "even when the LLM returned empty output."
    )
    for f in sn_marker_findings:
        assert f.severity == "high"
        assert f.finding_meta.must_flag is True
        assert f.finding_meta.source == "safety_net"


@pytest.mark.asyncio
async def test_single_shot_safety_net_counts_identical_across_5_runs(
    jacobs_ctx, monkeypatch
):
    """Run the same deck 5 times with a stochastic mock LLM (different findings
    each time) and verify the count of safety_net-source findings is identical
    across all runs. This is the headline determinism contract for the fix:
    LLM stochasticity must NOT change the count of deterministic safety_net
    findings.
    """
    monkeypatch.setenv("SLIDE_REVIEWER_MODE", "single_shot")
    import random as _r

    async def stochastic(agent, input_str, context):
        if agent.name == "Slide Reviewer":
            slide_n: int
            if isinstance(input_str, list):
                content = input_str[0].get("content", [])
                text_part = next(
                    (p for p in content if p.get("type") == "input_text"),
                    None,
                )
                import json as _json
                payload = _json.loads(text_part["text"]) if text_part else {}
                slide_n = payload.get("slide_number", 1)
            else:
                import json as _json
                slide_n = _json.loads(input_str)["slide_number"]
            # Stochastic: sometimes emit a finding mentioning DRAFT, sometimes
            # not. This simulates the real bug β€” the LLM at temp=1 picking
            # different subsets of issues to surface across runs.
            findings: list[Finding] = []
            if _r.random() < 0.5:
                findings.append(
                    Finding(
                        category="title_slide",
                        severity="high",
                        confidence=0.9,
                        title=f"Stochastic finding on slide {slide_n}",
                        description=f"Random emission for slide {slide_n}.",
                        evidence=f"DRAFT marker on slide {slide_n}",
                        suggested_fix="Remove DRAFT.",
                        guideline_reference="title_slide.no_draft",
                    )
                )
            return _wrap_as_run_result(
                SlideFindings(slide_number=slide_n, findings=findings)
            )
        if agent.name == "Deck Consistency":
            return _wrap_as_run_result(DeckFindings(findings=[]))
        if agent.name == "Lead Auditor":
            return _wrap_as_run_result(
                FinalAuditResult(
                    job_id="r", file_name="jacobs.pptx",
                    slide_count=jacobs_ctx.parsed_deck.slide_count,
                    summary=SeverityCounts(),
                    slides=[
                        SlideEnvelopeExtended(slide_number=n, image_url=None, findings=[])
                        for n in range(1, jacobs_ctx.parsed_deck.slide_count + 1)
                    ],
                    errors=[],
                )
            )
        raise AssertionError(agent.name)

    safety_net_counts: list[int] = []
    text_marker_counts: list[int] = []
    confidentiality_counts: list[int] = []
    for _ in range(5):
        # Re-seed each run differently to amplify stochasticity.
        _r.seed()
        mock = _MockRunner(stochastic)
        final = await run_audit(
            jacobs_ctx, job_id="r", file_name="jacobs.pptx", runner=mock,
        )
        sn_total = 0
        sn_marker = 0
        sn_conf_high = 0
        marker_rule_ids = {
            "title_slide.no_draft", "writing_style.no_internal_comments",
        }
        for env in final.slides:
            for f in env.findings:
                if f.finding_meta.source != "safety_net":
                    continue
                sn_total += 1
                if f.guideline_reference in marker_rule_ids:
                    sn_marker += 1
                if (
                    f.category == "confidentiality_statement"
                    and f.severity == "high"
                ):
                    sn_conf_high += 1
        safety_net_counts.append(sn_total)
        text_marker_counts.append(sn_marker)
        confidentiality_counts.append(sn_conf_high)

    assert len(set(safety_net_counts)) == 1, (
        f"safety_net total count drifted across runs: {safety_net_counts}"
    )
    assert len(set(text_marker_counts)) == 1, (
        f"text_marker safety_net count drifted: {text_marker_counts}"
    )
    assert len(set(confidentiality_counts)) == 1, (
        f"confidentiality_statement(high) safety_net count drifted: "
        f"{confidentiality_counts}"
    )


# ===========================================================================
# 13. Confidentiality + palette deterministic injectors β€” unit coverage
# ===========================================================================


def test_confidentiality_violates_logic():
    """``_confidentiality_violates`` must fire for absent OR mispositioned."""
    from agents.runner import _confidentiality_violates
    from services.confidentiality import ConfidentialityCheck

    # Absent β†’ violates.
    cc_absent = ConfidentialityCheck(
        present=False, exact_match=False, position_hint="absent",
        matched_excerpt=None, matching_shape_id=None,
    )
    assert _confidentiality_violates(cc_absent) is True

    # Header β†’ violates.
    cc_header = ConfidentialityCheck(
        present=True, exact_match=True, position_hint="header",
        matched_excerpt="Confidential", matching_shape_id="s1.shape1",
    )
    assert _confidentiality_violates(cc_header) is True

    # Body β†’ violates.
    cc_body = ConfidentialityCheck(
        present=True, exact_match=True, position_hint="body",
        matched_excerpt="Confidential", matching_shape_id="s1.shape1",
    )
    assert _confidentiality_violates(cc_body) is True

    # Footer β†’ satisfies.
    cc_footer = ConfidentialityCheck(
        present=True, exact_match=True, position_hint="footer",
        matched_excerpt="Confidential", matching_shape_id="s1.shape1",
    )
    assert _confidentiality_violates(cc_footer) is False


def test_offpalette_hexes_for_slide_filters_grayscale_and_allowed(rubric):
    """``_offpalette_hexes_for_slide`` keeps only non-grayscale, off-palette
    run colors β€” and de-dupes by first occurrence for stable ordering."""
    from agents.runner import _offpalette_hexes_for_slide

    # Build a tiny synthetic deck with three runs: one allowed-palette color,
    # one off-palette color, one grayscale (must be filtered out), and a
    # repeat of the off-palette color (must be de-duped).
    allowed = []
    for rule in rubric.rules:
        if rule.category == "color_palette" and rule.metadata and rule.metadata.allowed_hex:
            allowed = [h.lstrip("#").upper() for h in rule.metadata.allowed_hex]
            break
    assert allowed, "rubric must have a color_palette rule with allowed_hex"

    in_palette = allowed[0]
    off_palette = "112233" if "112233" not in {a.upper() for a in allowed} else "778899"

    runs = [
        RunInfo(text="a", font_size_pt=10.0, color_rgb=in_palette),
        RunInfo(text="b", font_size_pt=10.0, color_rgb=off_palette),
        RunInfo(text="c", font_size_pt=10.0, color_rgb="888888"),  # grayscale
        RunInfo(text="d", font_size_pt=10.0, color_rgb=off_palette),  # dupe
    ]
    shape = ShapeInfo(
        shape_id="s1.shape1", shape_type="TEXT_BOX", name="t",
        left=0, top=0, width=100, height=100, text="abcd",
        runs=runs, table_cells=[],
    )
    slide = ParsedSlide(slide_number=1, shapes=[shape], extracted_text="abcd")
    deck = ParsedDeck(
        slide_count=1, slide_width_emu=12192000, slide_height_emu=6858000,
        slides=[slide],
    )

    out = _offpalette_hexes_for_slide(deck, 1, allowed)
    assert out == [off_palette], f"expected [{off_palette!r}], got {out}"


def test_finalise_injects_confidentiality_and_palette_safety_nets(
    rubric, tmp_path
):
    """End-to-end on a synthetic deck with no confidentiality footer and an
    off-palette run color: ``_finalise`` must add a confidentiality safety_net
    AND a palette safety_net even when the LLM produced nothing."""
    from agents.runner import _finalise

    # Pick an off-palette color that isn't in the rubric's allowed list.
    allowed = []
    for rule in rubric.rules:
        if rule.category == "color_palette" and rule.metadata and rule.metadata.allowed_hex:
            allowed = [h.lstrip("#").upper() for h in rule.metadata.allowed_hex]
            break
    off_palette = "FF00FF" if "FF00FF" not in {a.upper() for a in allowed} else "00FFFF"

    runs = [RunInfo(text="x", font_size_pt=10.0, color_rgb=off_palette)]
    shape = ShapeInfo(
        shape_id="s1.shape1", shape_type="TEXT_BOX", name="body",
        left=0, top=0, width=100, height=100, text="x",
        runs=runs, table_cells=[],
    )
    slide = ParsedSlide(slide_number=1, shapes=[shape], extracted_text="x")
    deck = ParsedDeck(
        slide_count=1, slide_width_emu=12192000, slide_height_emu=6858000,
        slides=[slide],
    )
    ctx = AuditContext(
        parsed_deck=deck,
        render_result=RenderResult(skipped=True),
        rubric=rubric,
        out_dir=tmp_path,
    )
    lead_result = FinalAuditResult(
        job_id="t", file_name="t.pptx", slide_count=1,
        summary=SeverityCounts(),
        slides=[SlideEnvelopeExtended(slide_number=1, image_url=None, findings=[])],
        errors=[],
    )
    final = _finalise(
        job_id="t", file_name="t.pptx", slide_count=1,
        lead_result=lead_result,
        marker_hits={1: []},
        ctx=ctx,
        errors=[],
    )

    findings = final.slides[0].findings
    cats = {f.category for f in findings if f.finding_meta.source == "safety_net"}
    assert "confidentiality_statement" in cats, (
        f"expected confidentiality safety_net, got categories: {cats}"
    )
    assert "color_palette" in cats, (
        f"expected color_palette safety_net, got categories: {cats}"
    )