File size: 60,834 Bytes
fb62a97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55ac80e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb62a97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Unit tests for triage/classifier.py and reports/generate_report.py.

All inputs are SYNTHETIC FIXTURES in triage/tests/fixtures/ (files prefixed FIXTURE_).
They mimic the Playwright JSON reporter shape; they are not real runs and contain no Fusion data.
Run:  python3 -m unittest discover -s triage/tests -v
"""
import json
import sys
import tempfile
import unittest
from pathlib import Path

HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[1]
FX = HERE / "fixtures"
sys.path.insert(0, str(ROOT / "triage"))
sys.path.insert(0, str(ROOT / "reports"))
import classifier as clf  # noqa: E402
import generate_report as gr  # noqa: E402


def classify(msg, snippet="", status="failed"):
    return clf.classify_errors([{"message": msg, "snippet": snippet, "status": status}])


class TestRules(unittest.TestCase):
    def test_strict_mode_is_ui_change(self):
        c = classify("Error: locator.click: Error: strict mode violation: getByRole('button') resolved to 2 elements")
        self.assertEqual(c.category, "ui_change")
        self.assertGreaterEqual(c.confidence, 0.8)
        self.assertTrue(any("Strict mode" in e for e in c.evidence))

    def test_locator_not_found_is_ui_change(self):
        c = classify("Error: expect(locator).toHaveText(expected) failed\n\nLocator: getByTestId('invoice-amount')\n"
                     "Expected string: \"100\"\nReceived: <element(s) not found>")
        self.assertEqual(c.category, "ui_change")  # business word must NOT turn this into a defect
        self.assertEqual(c.scores["real_defect"], 0.0)

    def test_navigation_timeout_is_timing(self):
        c = classify("TimeoutError: page.goto: Timeout 30000ms exceeded.\nCall log:\n  - navigating to \"http://localhost:3000/\"")
        self.assertEqual(c.category, "timing")
        self.assertGreaterEqual(c.confidence, 0.8)

    def test_waitfor_timeout_is_timing(self):
        c = classify("TimeoutError: page.waitForResponse: Timeout 10000ms exceeded while waiting for event \"response\"")
        self.assertEqual(c.category, "timing")

    def test_test_timeout_is_timing(self):
        c = classify("Test timeout of 30000ms exceeded.", status="timedOut")
        self.assertEqual(c.category, "timing")

    def test_http_4xx_is_data_not_defect(self):
        c = classify("Error: expect(received).toBe(expected)\n\nExpected: 201\nReceived: 422",
                     snippet="> 12 |   expect(response.status()).toBe(201);")
        self.assertEqual(c.category, "data")
        self.assertEqual(c.scores["real_defect"], 0.0)

    def test_duplicate_and_missing_record_are_data(self):
        self.assertEqual(classify("Error: Invoice number FX-1 already exists").category, "data")
        self.assertEqual(classify("Error: Purchase order FX-PO-9 does not exist").category, "data")
        self.assertEqual(classify("Error: Validation failed: Supplier Site is required").category, "data")

    def test_business_assertion_is_real_defect(self):
        c = classify("Error: Timed out 5000ms waiting for expect(locator).toHaveText(expected)\n\n"
                     "Locator: getByTestId('hold-reason')\nExpected string: \"Qty Rec\"\nReceived string: \"None\"")
        self.assertEqual(c.category, "real_defect")
        self.assertGreaterEqual(c.confidence, 0.6)

    def test_camelcase_business_value_in_snippet(self):
        c = classify("Error: expect(received).toBe(expected)\n\nExpected: 1000\nReceived: 900",
                     snippet="  54 | const x = 1;\n> 55 |   expect(invoiceTotal).toBe(1000);")
        self.assertEqual(c.category, "real_defect")
        self.assertTrue(any("total" in e for e in c.evidence))

    def test_matcher_name_is_not_business_word(self):
        c = classify("Error: expect(received).toMatch(expected)\n\nExpected pattern: /abc/\nReceived string: \"xyz\"",
                     snippet="> 3 | expect(label).toMatch(/abc/);")
        self.assertEqual(c.category, "real_defect")
        self.assertLess(c.confidence, 0.6)  # generic assertion only -> low confidence

    def test_http_5xx_is_the_environment_not_a_defect(self):
        c = classify("Error: expect(received).toBe(expected)\n\nExpected: 200\nReceived: 500",
                     snippet="> 9 | expect(resp.status()).toBe(200);")
        self.assertEqual(c.category, "environment")
        self.assertEqual(c.scores["real_defect"], 0.0)
        self.assertEqual(classify("Error: GET invoices failed: HTTP 503 Service Unavailable").category, "environment")

    def test_the_pod_or_network_is_environment_not_timing(self):
        cases = {
            "sign-in refused": ("page.waitForURL: Timeout 120000ms exceeded.\n=== logs ===\n"
                                "waiting for navigation to \"/AtkHomePageWelcome|FuseWelcome/\" until \"commit\"", "failed"),
            "sign-in page missing": ("TimeoutError: locator.fill: Timeout 60000ms exceeded.\nCall log:\n"
                                     "  - waiting for locator('[id=\"idcs-signin-basic-signin-form-username|input\"]')", "failed"),
            "edge": ("Error: Fusion showed page \"Access Denied\": You don't have permission to access \"http://x/\" on this "
                     "server. Reference #18.6a3d1402.1700000000.1a2b3c", "failed"),
            "crash": ("Error: page.click: Target crashed", "failed"),
            "network": ("Error: page.goto: net::ERR_CONNECTION_RESET at https://pod.example/", "failed"),
            "pass lost": ("The remote browser runner did not finish the attempt in time. This pass (4 scenarios) stopped "
                          "before it reported, so they have no result of their own; the retry runs them again.", "timedOut"),
        }
        for name, (msg, status) in cases.items():
            c = classify(msg, status=status)
            self.assertEqual((name, c.category), (name, "environment"))
            self.assertFalse(c.needs_review, name)   # nothing else competes: confident
            self.assertEqual(c.scores["timing"], 0.0, name)

    def test_a_slow_page_stays_timing(self):
        c = classify("TimeoutError: page.goto: Timeout 30000ms exceeded.\nCall log:\n  - navigating to \"http://x/\"")
        self.assertEqual(c.category, "timing")
        self.assertEqual(c.scores["environment"], 0.0)
        self.assertEqual(classify("Test timeout of 30000ms exceeded.", status="timedOut").category, "timing")

    def test_conflicting_signals_lower_confidence(self):
        c = classify("Error: Timed out 5000ms waiting for expect(locator).toHaveText(expected)\n\n"
                     "Locator: getByTestId('req-status')\nExpected string: \"Approved\"\nReceived string: \"Pending Approval\"")
        self.assertTrue(c.conflict)
        self.assertLess(c.confidence, 0.6)
        self.assertTrue(c.needs_review)

    def test_ambiguous_locator_wait_is_low_confidence(self):
        c = classify("TimeoutError: locator.fill: Timeout 10000ms exceeded.\nCall log:\n  - waiting for getByLabel('Supplier Site')")
        self.assertIn(c.category, ("timing", "ui_change"))
        self.assertLess(c.confidence, 0.6)

    def test_unknown_is_unclassified(self):
        c = classify("Error: something odd")
        self.assertEqual(c.category, "unclassified")
        self.assertEqual(c.confidence, 0.0)
        self.assertTrue(c.needs_review)

    def test_ansi_is_stripped(self):
        c = classify("\x1b[31mError: strict mode violation\x1b[39m: locator resolved to 3 elements")
        self.assertEqual(c.category, "ui_change")


class TestReportParsing(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.tri = clf.triage(FX / "FIXTURE_mixed_results.json", FX / "cases")
        cls.by_id = {r["case_id"]: r for r in cls.tri["records"]}

    def test_counts(self):
        outcomes = [r["outcome"] for r in self.tri["records"]]
        self.assertEqual(len(outcomes), 14)
        self.assertEqual(outcomes.count("passed"), 2)
        self.assertEqual(outcomes.count("failed"), 10)
        self.assertEqual(outcomes.count("skipped"), 1)
        self.assertEqual(outcomes.count("flaky"), 1)

    def test_expected_classes(self):
        exp = {"FX-UI-001": "ui_change", "FX-UI-002": "ui_change", "FX-TIME-001": "timing",
               "FX-TIME-002": "timing", "FX-DATA-001": "data", "FX-DATA-002": "data",
               "FX-DEF-001": "real_defect", "FX-DEF-002": "real_defect", "FX-UNK-001": "unclassified"}
        for cid, cls in exp.items():
            self.assertEqual(self.by_id[cid]["classification"]["category"], cls, cid)

    def test_flaky_flagged_and_classified(self):
        r = self.by_id["FX-FLAKY-001"]
        self.assertEqual(r["outcome"], "flaky")
        self.assertEqual(r["attempts"], 2)
        self.assertEqual(r["classification"]["category"], "timing")

    def test_case_id_from_tags_only(self):
        self.assertIn("FX-UI-001", self.by_id)   # Playwright JSON tag without '@'
        self.assertIn("FX-UI-002", self.by_id)   # '@'-prefixed tag

    def test_artifacts_collected(self):
        names = {a["name"] for a in self.by_id["FX-UI-001"]["artifacts"]}
        self.assertEqual(names, {"screenshot", "trace"})

    def test_risk_from_minimal_yaml(self):
        self.assertEqual(self.by_id["FX-PASS-001"]["risk"], "high")
        self.assertEqual(self.by_id["FX-PASS-002"]["risk"], "medium")  # nested risk: {level: medium}
        self.assertTrue(clf.is_high_risk("High"))     # P2
        self.assertFalse(clf.is_high_risk("4"))       # P4 (low) under QA's mapping
        self.assertFalse(clf.is_high_risk("medium"))

    def test_rejects_non_playwright_json(self):
        with tempfile.TemporaryDirectory() as d:
            p = Path(d) / "x.json"
            p.write_text('{"foo": 1}')
            with self.assertRaises(ValueError):
                clf.load_report(p)


def results_with_standin(src: Path, case_id: str, tmp: str) -> Path:
    """Copy of a SYNTHETIC results fixture where the spec tagged with case_id also carries the runtime 'stand-in' tag."""
    data = json.loads(Path(src).read_text())
    def walk(suite):
        for sp in suite.get("specs", []):
            if any(str(t).lstrip("@") == case_id for t in sp.get("tags", [])):
                sp["tags"] = list(sp["tags"]) + ["stand-in"]
        for x in suite.get("suites", []):
            walk(x)
    for su in data["suites"]:
        walk(su)
    out = Path(tmp) / f"standin-{case_id}.json"
    out.write_text(json.dumps(data))
    return out


def make_root(project: str, tmp: str) -> Path:
    """Temp project root = synthetic fixture project + the REAL qa/audit.py (QA's rule helpers)."""
    import shutil
    root = Path(tmp) / "root"
    shutil.copytree(FX / project, root)
    (root / "qa").mkdir()
    shutil.copy(ROOT / "qa" / "audit.py", root / "qa" / "audit.py")
    (root / "triage").mkdir(exist_ok=True)
    for f in ("ids.py", "risk.py"):  # qa/audit.py loads the shared parser/tiers from <root>/triage/
        shutil.copy(ROOT / "triage" / f, root / "triage" / f)
    return root


@unittest.skipUnless((ROOT / "qa" / "audit.py").is_file(), "qa/audit.py (QA rule helpers) not present")
class TestQaGoNoGoRule(unittest.TestCase):
    """Decision = QA exit criteria (qa/test-strategy.md section 5). Synthetic fixtures only."""

    def run_rule(self, project, results, review=None, mutate=None):
        with tempfile.TemporaryDirectory() as d:
            root = make_root(project, d)
            tri = clf.triage(FX / results, root / "tests" / "cases")
            if mutate:
                mutate(tri)
            return gr.summarize(tri, root, review or {}, module="FX")

    def test_mixed_is_no_go_for_p1_and_flaky(self):
        s = self.run_rule("project_mixed", "FIXTURE_mixed_results.json")
        self.assertEqual(s["decision"], "NO-GO")
        crit = s["criteria"]
        self.assertTrue(crit["C1"][0], crit["C1"][1])           # every case scripted and run
        self.assertFalse(crit["C2"][0])                         # P1 FX-DEF-001 failed; P2 FX-UNK-001 untriaged
        self.assertIn("FX-DEF-001 (fail)", crit["C2"][1])
        self.assertIn("without a triage verdict: 1 of", crit["C2"][1])
        self.assertFalse(crit["C3"][0])                         # 1/13 = 7.7% > 5%, no owner
        self.assertTrue(crit["C5"][0], crit["C5"][1])           # counts equal qa/audit.py recomputation
        self.assertEqual(s["counts"], {"pass": 2, "fail": 10, "flaky": 1, "skipped": 1, "total": 14, "executed": 13})

    def test_go_when_all_qa_criteria_hold(self):
        # P1 + P2 pass, P4 skipped, P3 failure (data): QA's rule does not block on P3.
        s = self.run_rule("project_go", "FIXTURE_go_results.json")
        self.assertEqual(s["decision"], "GO", s["criteria"])
        self.assertTrue(any("P3/P4" in g for g in s["gaps"]))

    def test_old_invented_conditions_are_gone(self):
        # A non-P1/P2 high-confidence real defect no longer blocks (my old ">=0.6 defect" rule is dropped).
        def mutate(tri):
            for r in tri["records"]:
                if r["case_id"] == "FX-DATA-002":
                    r["classification"]["category"] = "real_defect"
                    r["classification"]["confidence"] = 0.9
        s = self.run_rule("project_go", "FIXTURE_go_results.json", mutate=mutate)
        self.assertEqual(s["decision"], "GO")

    def test_p1_flaky_is_not_a_pass(self):
        def mutate(tri):
            for r in tri["records"]:
                if r["case_id"] == "FX-PASS-001":
                    r["outcome"] = "flaky"
        s = self.run_rule("project_go", "FIXTURE_go_results.json", mutate=mutate)
        self.assertFalse(s["criteria"]["C2"][0])
        self.assertIn("FX-PASS-001 (flaky)", s["criteria"]["C2"][1])

    def test_p2_defect_blocks_unless_waived_or_reclassified(self):
        # Fixture: P2 case FX-PASS-002 fails with a business-value assertion (classifier: real defect).
        run = lambda review, m=None: self.run_rule("project_go", "FIXTURE_p2_defect_results.json", review, m)
        base = run({})
        self.assertTrue(base["criteria"]["C5"][0], base["criteria"]["C5"][1])
        # Unconfirmed P2 defect -> NO-GO
        self.assertEqual(base["decision"], "NO-GO")
        self.assertIn("FX-PASS-002", base["criteria"]["C2"][1])
        # ...at any confidence
        def lowconf(tri):
            for r in tri["records"]:
                if r["case_id"] == "FX-PASS-002":
                    r["classification"].update(confidence=0.3, needs_review=True)
        self.assertEqual(run({}, lowconf)["decision"], "NO-GO")
        # Human-confirmed but not waived -> NO-GO
        self.assertEqual(run({"FX-PASS-002": {"confirmed": "real_defect"}})["decision"], "NO-GO")
        # Waived -> GO
        self.assertEqual(run({"FX-PASS-002": {"confirmed": "real_defect", "waiver": "FIXTURE waiver"}})["decision"], "GO")
        self.assertEqual(run({"FX-PASS-002": {"waiver": "FIXTURE waiver"}})["decision"], "GO")
        # Human reclassified as not a defect -> GO
        self.assertEqual(run({"FX-PASS-002": {"confirmed": "not_defect"}})["decision"], "GO")

    def test_an_environment_failure_is_never_a_product_defect(self):
        # The same P2 failure, but the pod answered HTTP 503: not a defect for C2, a non-defect for C4, and qa/audit agrees.
        def env(tri):
            for r in tri["records"]:
                if r["case_id"] == "FX-PASS-002":
                    r["classification"] = clf.asdict(clf.classify_errors([{"message": "GET invoices failed: HTTP 503 Service Unavailable"}]))
        s = self.run_rule("project_go", "FIXTURE_p2_defect_results.json", mutate=env)
        self.assertEqual(s["decision"], "GO", s["criteria"])
        self.assertIn("real-defect failures not waived or human-reclassified: 0", s["criteria"]["C2"][1])
        self.assertIn("non-defect 2 / triaged gating failures 2;", s["criteria"]["C4"][1])   # with the fixture's data failure
        self.assertIn("0 defect verdict(s)", s["criteria"]["C4"][1])
        self.assertEqual(s["by_class"].get("environment"), 1)
        self.assertEqual(gr.load_qa_audit(ROOT).classify("environment"), "non_defect")

    def test_p1_failure_blocks_even_if_waived(self):
        def mutate(tri):
            for r in tri["records"]:
                if r["case_id"] == "FX-PASS-001":
                    r["outcome"] = "failed"
                    r["classification"] = {"category": "real_defect", "confidence": 0.9, "needs_review": False,
                                           "evidence": ["fixture"], "scores": {}, "conflict": False}
        s = self.run_rule("project_go", "FIXTURE_go_results.json",
                          {"FX-PASS-001": {"waiver": "FIXTURE waiver", "confirmed": "not_defect"}}, mutate)
        self.assertFalse(s["criteria"]["C2"][0])
        self.assertIn("FX-PASS-001 (fail)", s["criteria"]["C2"][1])
        self.assertEqual(s["decision"], "NO-GO")

    def test_flaky_owner_required(self):
        s = self.run_rule("project_mixed", "FIXTURE_mixed_results.json", {"FX-FLAKY-001": {"owner": "fixture-owner"}})
        self.assertIn("without an owner: 0", s["criteria"]["C3"][1])

    def test_count_mismatch_with_audit_blocks(self):
        def mutate(tri):
            tri["records"][0]["outcome"] = "failed"
        s = self.run_rule("project_go", "FIXTURE_go_results.json", mutate=mutate)
        self.assertFalse(s["criteria"]["C5"][0])

    def test_no_designed_cases_fails_coverage(self):
        with tempfile.TemporaryDirectory() as d:
            root = make_root("project_go", d)
            for f in (root / "tests" / "cases").iterdir():
                f.unlink()
            s = gr.summarize(clf.triage(FX / "FIXTURE_go_results.json", root / "tests" / "cases"), root, {}, module="FX")
            self.assertFalse(s["criteria"]["C1"][0])
            self.assertEqual(s["decision"], "NO-GO")

    def test_script_not_run_fails_coverage(self):
        with tempfile.TemporaryDirectory() as d:
            root = make_root("project_go", d)
            (root / "automation" / "tests" / "p2p" / "extra.spec.ts").write_text("test('FX-PASS-001 again', { tag: ['@FX-PASS-001'] }, async () => {});")
            s = gr.summarize(clf.triage(FX / "FIXTURE_go_results.json", root / "tests" / "cases"), root, {}, module="FX")
            self.assertFalse(s["criteria"]["C1"][0])

    def test_reports_readable_by_qa_audit(self):
        with tempfile.TemporaryDirectory() as d:
            root = make_root("project_mixed", d)
            tri = clf.triage(FX / "FIXTURE_mixed_results.json", root / "tests" / "cases")
            out = Path(d) / "out"
            gr.write_reports(tri, out, root=root, review={}, module="FX")
            qa = gr.load_qa_audit(root)
            for name in ("go-no-go.md", "go-no-go.html"):
                counts, mock_note, fusion_claim = qa.extract_report_counts(str(out / name))
                self.assertTrue(mock_note, name)
                self.assertFalse(fusion_claim, name)
                got = {k: sorted(set(v)) for k, v in counts.items()}
                self.assertEqual(got, {"total": [14], "executed": [13], "pass": [2], "fail": [10], "flaky": [1],
                                       "skipped": [1], "cases": [14], "scripts": [1]}, name)
            md = (out / "go-no-go.md").read_text()
            self.assertIn("NOT Oracle Fusion", md)
            self.assertIn("qa/test-strategy.md section 5", md)
            json.loads((out / "triage.json").read_text())

    def test_empty_run_is_no_go(self):
        with tempfile.TemporaryDirectory() as d:
            root = make_root("project_go", d)
            tri = {"source": str(FX / "FIXTURE_go_results.json"), "records": [], "run_errors": [], "case_risks": {}}
            self.assertEqual(gr.summarize(tri, root, {}, module="FX")["decision"], "NO-GO")

    # ---- tiered C1 (QA patch) + stand-ins
    def _go_root_with_extra_case(self, d, cid, priority):
        root = make_root("project_go", d)
        with open(root / "tests" / "cases" / "FIXTURE_cases.yaml", "a") as f:
            f.write(f"- id: {cid}\n  title: {cid} unscripted (fixture)\n  priority: {priority}\n")
        return root

    def test_c1_p1_scope_go_with_unscripted_p2(self):
        with tempfile.TemporaryDirectory() as d:
            root = self._go_root_with_extra_case(d, "FX-NOSCRIPT-P2", "P2")
            tri = clf.triage(FX / "FIXTURE_go_results.json", root / "tests" / "cases")
            s = gr.summarize(tri, root, {}, module="FX")
            self.assertTrue(s["criteria"]["C1"][0], s["criteria"]["C1"][1])
            self.assertEqual(s["decision"], "GO", s["criteria"])
            self.assertTrue(any("FX-NOSCRIPT-P2" in g and "not blocking" in g for g in s["gaps"]))

    def test_c1_include_p2_no_go_with_unscripted_p2(self):
        with tempfile.TemporaryDirectory() as d:
            root = self._go_root_with_extra_case(d, "FX-NOSCRIPT-P2", "P2")
            tri = clf.triage(FX / "FIXTURE_go_results.json", root / "tests" / "cases")
            s = gr.summarize(tri, root, {}, include_p2=True, module="FX")
            self.assertFalse(s["criteria"]["C1"][0])
            self.assertEqual(s["decision"], "NO-GO")
            self.assertTrue(any("FX-NOSCRIPT-P2" in g for g in s["gaps"]))

    def test_c1_unscripted_p1_and_untiered_block(self):
        for prio in ("P1", "''"):
            with tempfile.TemporaryDirectory() as d:
                root = self._go_root_with_extra_case(d, "FX-NOSCRIPT-X", prio)
                tri = clf.triage(FX / "FIXTURE_go_results.json", root / "tests" / "cases")
                self.assertFalse(gr.summarize(tri, root, {}, module="FX")["criteria"]["C1"][0], prio)

    def test_c1_unrun_script_for_deferred_case_does_not_block(self):
        with tempfile.TemporaryDirectory() as d:
            root = self._go_root_with_extra_case(d, "FX-DEFER-003", "P3")
            (root / "automation" / "tests" / "p2p" / "deferred.spec.ts").write_text(
                "// SYNTHETIC FIXTURE\ntest('FX-DEFER-003 fixture', { tag: ['@FX-DEFER-003'] }, async () => {});\n")
            tri = clf.triage(FX / "FIXTURE_go_results.json", root / "tests" / "cases")
            s = gr.summarize(tri, root, {}, include_p2=True, module="FX")
            self.assertTrue(s["criteria"]["C1"][0], s["criteria"]["C1"][1])
            self.assertTrue(any("deferred.spec.ts" in g and "not blocking" in g for g in s["gaps"]))

    def test_standin_listed_separately_not_real_coverage(self):
        with tempfile.TemporaryDirectory() as d:
            root = make_root("project_go", d)
            spec = root / "automation" / "tests" / "p2p" / "fixture.spec.ts"
            spec.write_text(spec.read_text().replace(
                "test('FX-PASS-002 fixture', { tag: ['@FX-PASS-002'] }, async () => {});",
                "test('FX-PASS-002 REST import stand-in', { tag: ['@FX-PASS-002', '@stand-in'] }, async () => {});"))
            tri = clf.triage(results_with_standin(FX / "FIXTURE_go_results.json", "FX-PASS-002", d), root / "tests" / "cases")
            out = Path(d) / "out"
            s = gr.write_reports(tri, out, root=root, review={}, include_p2=True, module="FX")
            self.assertEqual([x["case"] for x in s["standins"]], ["FX-PASS-002"])
            self.assertTrue(s["criteria"]["C1"][0])               # stand-in satisfies C1 (QA 2a)
            self.assertEqual((s["n_fully"], s["n_in_scope"]), (1, 2))  # but is not fully covered
            self.assertEqual(s["counts"]["pass"], 2)              # its result still counts (C5 parity)
            self.assertTrue(s["criteria"]["C5"][0])
            md = (out / "go-no-go.md").read_text()
            sec = md[md.index("## Stand-in (substitute) coverage: NOT real coverage"):md.index("## Per-case results")]
            self.assertIn("| FX-PASS-002 | P2 | yes |", sec)
            self.assertIn("NOT real coverage", sec)
            self.assertIn("ARE included in the Total", sec)
            self.assertIn("FX-PASS-002 (STAND-IN)", (out / "go-no-go.html").read_text())
            counts, _, _ = gr.load_qa_audit(root).extract_report_counts(str(out / "go-no-go.md"))
            self.assertEqual(sorted(set(counts["pass"])), [2])

    def test_standin_detected_from_result_tags_only(self):
        # Script text has no @stand-in literal (tags added at runtime); results carry the tag -> still a stand-in.
        with tempfile.TemporaryDirectory() as d:
            root = make_root("project_go", d)
            tri = clf.triage(results_with_standin(FX / "FIXTURE_go_results.json", "FX-PASS-002", d), root / "tests" / "cases")
            s = gr.summarize(tri, root, {}, include_p2=True, module="FX")
            self.assertEqual([x["case"] for x in s["standins"]], ["FX-PASS-002"])
            self.assertEqual(s["n_fully"], 1)

    def test_c1_skipped_fixme_in_scope_case_is_not_run(self):
        # FX-SKIP-001 is skipped in the fixture. As P4 it is deferred (GO); retiered to P2 it blocks only with --include-p2.
        with tempfile.TemporaryDirectory() as d:
            root = make_root("project_go", d)
            y = root / "tests" / "cases" / "FIXTURE_cases.yaml"
            y.write_text(y.read_text().replace("- id: FX-SKIP-001\n  title: FX-SKIP-001 (fixture)\n  priority: P4",
                                               "- id: FX-SKIP-001\n  title: FX-SKIP-001 (fixture)\n  priority: P2"))
            tri = clf.triage(FX / "FIXTURE_go_results.json", root / "tests" / "cases")
            self.assertEqual(gr.summarize(tri, root, {}, module="FX")["decision"], "GO")
            s = gr.summarize(tri, root, {}, include_p2=True, module="FX")
            self.assertFalse(s["criteria"]["C1"][0], s["criteria"]["C1"][1])
            self.assertTrue(any("FX-SKIP-001" in g and "not executed" in g for g in s["gaps"]))

    def test_c1_a_case_not_applicable_on_the_pod_is_accounted_for(self):
        # The automation skips a scenario the pod's setup does not allow (a type it lacks, approval it does not use) with a
        # 'not-applicable' note on the result: it is no longer "not executed", and the report says why.
        with tempfile.TemporaryDirectory() as d:
            root = make_root("project_go", d)
            y = root / "tests" / "cases" / "FIXTURE_cases.yaml"
            y.write_text(y.read_text().replace("- id: FX-SKIP-001\n  title: FX-SKIP-001 (fixture)\n  priority: P4",
                                               "- id: FX-SKIP-001\n  title: FX-SKIP-001 (fixture)\n  priority: P2"))
            data = json.loads((FX / "FIXTURE_go_results.json").read_text(encoding="utf-8"))
            why = "Not applicable on this pod: invoice approval is not required for this business unit"

            def mark(suites):
                for su in suites or []:
                    for sp in su.get("specs") or []:
                        if "FX-SKIP-001" in json.dumps(sp.get("tags")) or "FX-SKIP-001" in sp.get("title", ""):
                            for t in sp.get("tests") or []:
                                t["results"][-1].setdefault("annotations", []).append({"type": "not-applicable", "description": why})
                    mark(su.get("suites"))
            mark(data.get("suites"))
            res = Path(d) / "results.json"
            res.write_text(json.dumps(data), encoding="utf-8")
            tri = clf.triage(res, root / "tests" / "cases")
            rec = next(r for r in tri["records"] if "FX-SKIP-001" in (r.get("tag_ids") or []) or r.get("case_id") == "FX-SKIP-001")
            self.assertEqual(rec["not_applicable"], why)
            s = gr.summarize(tri, root, {}, include_p2=True, module="FX")
            self.assertTrue(s["criteria"]["C1"][0], s["criteria"]["C1"][1])
            self.assertTrue(any("not applicable on this pod" in g and "FX-SKIP-001" in g for g in s["gaps"]))

    def test_tier_mapping(self):
        self.assertEqual(gr.tier("P1"), "P1")
        self.assertEqual(gr.tier("critical"), "P1")
        self.assertEqual(gr.tier("High"), "P2")
        self.assertEqual(gr.tier("p3 (medium)"), "P3")
        self.assertIsNone(gr.tier(""))

    def test_tier_and_high_risk_share_one_mapping(self):
        import risk
        self.assertIs(gr.tier, risk.tier)
        self.assertIs(clf.tier, risk.tier)
        self.assertIs(clf.is_high_risk, risk.is_high_risk)
        self.assertIs(gr.is_high_risk, risk.is_high_risk)
        values = ["P1", "p1", "P 2", "P3", "P4", "1", "2", "3", "4", "critical", "Critical", "high", "High",
                  "HIGH", "high-risk", "medium", "p3 (medium)", "low", "Low", "", None, "unknown", "5", "0.9",
                  "very high", "severe", "h"]
        expected = {"P1": True, "P2": True, "P3": False, "P4": False, None: False}
        for v in values:
            t = gr.tier(v)
            self.assertEqual(clf.tier(v), t, v)
            self.assertEqual(clf.is_high_risk(v), expected[t], v)
            self.assertEqual(gr.is_high_risk(v), clf.is_high_risk(v), v)
        self.assertEqual(gr.tier("high"), "P2")
        self.assertEqual(gr.tier("critical"), "P1")


@unittest.skipUnless((ROOT / "qa" / "audit.py").is_file(), "qa/audit.py not present")
class TestRunTriageEndToEnd(unittest.TestCase):
    """Regression: run the real CLI (triage/run_triage.py) end to end in a subprocess on a synthetic fixture project.
    Guards against the KeyError: 'passed' crash (count-key mismatch between run_triage.py and generate_report.py)."""

    def _run(self, root, *args):
        import subprocess
        return subprocess.run([sys.executable, str(ROOT / "triage" / "run_triage.py"), "--root", str(root), "--module", "FX", *args],
                              capture_output=True, text=True, timeout=60)

    def test_full_pipeline_discovery_go_and_include_p2(self):
        import shutil
        with tempfile.TemporaryDirectory() as d:
            root = make_root("project_go", d)
            res = root / "automation" / "results"
            res.mkdir(parents=True)
            shutil.copy(FX / "FIXTURE_go_results.json", res / "results.json")  # discovered, not passed explicitly
            p = self._run(root)
            self.assertNotIn("Traceback", p.stderr, p.stderr)
            self.assertEqual(p.returncode, 0, p.stdout + p.stderr)            # GO
            self.assertIn("[FX] GO (mock run, not Fusion; C1 scope P1)", p.stdout)
            self.assertIn("total=4 executed=3 pass=2 fail=1 flaky=0 skipped=1", p.stdout)
            for f in ("go-no-go.md", "go-no-go.html", "triage.json"):  # non-P2P module -> reports/<module>/
                self.assertTrue((root / "reports" / "fx" / f).is_file(), f)
            # same run, P2 in scope, plus an unscripted P2 case -> NO-GO, exit 1, C1 named
            with open(root / "tests" / "cases" / "FIXTURE_cases.yaml", "a") as fh:
                fh.write("- id: FX-NOSCRIPT-P2\n  title: unscripted (fixture)\n  priority: P2\n")
            self.assertEqual(self._run(root).returncode, 0)
            p2 = self._run(root, "--include-p2")
            self.assertNotIn("Traceback", p2.stderr, p2.stderr)
            self.assertEqual(p2.returncode, 1, p2.stdout + p2.stderr)
            self.assertIn("NOT MET C1", p2.stdout)

    def test_full_pipeline_no_go_explicit_file(self):
        with tempfile.TemporaryDirectory() as d:
            root = make_root("project_mixed", d)
            p = self._run(root, str(FX / "FIXTURE_mixed_results.json"), "--out-dir", str(Path(d) / "out"))
            self.assertNotIn("Traceback", p.stderr, p.stderr)
            self.assertEqual(p.returncode, 1)
            self.assertIn("total=14 executed=13 pass=2 fail=10 flaky=1 skipped=1", p.stdout)
            self.assertTrue((Path(d) / "out" / "fx" / "go-no-go.md").is_file())

    def test_no_results_exit_2(self):
        with tempfile.TemporaryDirectory() as d:
            root = make_root("project_go", d)
            p = self._run(root)
            self.assertEqual(p.returncode, 2)
            self.assertIn("WAITING", p.stdout)
            self.assertFalse((root / "reports" / "go-no-go.md").exists())

    def test_counts_keys_are_canonical(self):
        tri = clf.triage(FX / "FIXTURE_go_results.json")
        with tempfile.TemporaryDirectory() as d:
            s = gr.summarize(tri, make_root("project_go", d), {}, module="FX")
        self.assertEqual(set(s["counts"]), set(gr.COUNT_KEYS))
        gr.counts_line(s)  # must not raise


class TestDefaultResultsPath(unittest.TestCase):
    """run_triage.py reads <root>/automation/results/results.json only; no auto-discovery."""

    def _run(self, root, *args):
        import subprocess
        return subprocess.run([sys.executable, str(ROOT / "triage" / "run_triage.py"), "--root", str(root), "--module", "FX", *args],
                              capture_output=True, text=True, timeout=60)

    def _stray(self, root):
        # Newer, valid Playwright JSON files in places the old discovery would have picked up.
        import os
        import shutil
        import time
        paths = [root / "automation" / "test-results" / "results.json", root / "playwright-report" / "report.json",
                 root / "test-results" / "results.json", root / "automation" / "results" / "newer.json"]
        for p in paths:
            p.parent.mkdir(parents=True, exist_ok=True)
            shutil.copy(FX / "FIXTURE_mixed_results.json", p)
            future = time.time() + 3600
            os.utime(p, (future, future))
        return paths

    @unittest.skipUnless((ROOT / "qa" / "audit.py").is_file(), "qa/audit.py not present")
    def test_newer_stray_json_is_ignored(self):
        import shutil
        with tempfile.TemporaryDirectory() as d:
            root = make_root("project_go", d)
            (root / "automation" / "results").mkdir(parents=True)
            shutil.copy(FX / "FIXTURE_go_results.json", root / "automation" / "results" / "results.json")
            self._stray(root)
            p = self._run(root)
            self.assertEqual(p.returncode, 0, p.stdout + p.stderr)
            self.assertIn("total=4 executed=3 pass=2 fail=1", p.stdout)      # default file, not the 14-test stray
            self.assertIn(str(root / "automation" / "results" / "results.json"), p.stdout)
            self.assertNotIn("newer.json", p.stdout)

    def test_missing_default_waits_even_with_stray_json(self):
        with tempfile.TemporaryDirectory() as d:
            root = make_root("project_go", d)
            self._stray(root)
            p = self._run(root)
            self.assertEqual(p.returncode, 2)
            self.assertIn("WAITING", p.stdout)
            self.assertFalse((root / "reports" / "go-no-go.md").exists())

    @unittest.skipUnless((ROOT / "qa" / "audit.py").is_file(), "qa/audit.py not present")
    def test_explicit_path_overrides_default(self):
        import shutil
        with tempfile.TemporaryDirectory() as d:
            root = make_root("project_mixed", d)
            (root / "automation" / "results").mkdir(parents=True)
            shutil.copy(FX / "FIXTURE_go_results.json", root / "automation" / "results" / "results.json")
            p = self._run(root, str(FX / "FIXTURE_mixed_results.json"))
            self.assertIn("total=14", p.stdout)
            p2 = self._run(root, str(Path(d) / "nope.json"))
            self.assertEqual(p2.returncode, 2)

    def test_no_discovery_function_left(self):
        self.assertFalse(hasattr(clf, "find_result_files"))


class TestMultiModuleIds(unittest.TestCase):
    def test_shared_pattern(self):
        import ids
        good = ["P2P-INV-006", "O2C-ORD-012", "R2R-JE-3", "P2P-E2E-001", "P2P-SMOKE-001", "TC-001", "TC_01",
                "FX-UI-001", "HCM1-PAY-07", "P2P-PO-3WAY-001"]
        for g in good:
            self.assertEqual(ids.find_case_ids(f"x {g} y"), [g], g)
            self.assertEqual(ids.tag_case_id("@" + g), g)
        for bad in ["P2P-INV", "p2p-inv-001", "xP2P-INV-001", "_P2P-INV-001", "P2P-INV-001X", "TOOLONG1-A-1", "INV-006", "@smoke"]:
            self.assertEqual(ids.find_case_ids(bad), [], bad)
        self.assertEqual(ids.modules(["O2C-ORD-1", "R2R-JE-2", "P2P-INV-3", "TC-9"]), ["O2C", "P2P", "R2R"])
        self.assertTrue(ids.is_standin("@stand-in") and ids.is_standin("REST import stand-in"))

    def test_classifier_and_report_share_pattern(self):
        import ids
        self.assertIs(clf.CASE_ID_RE, ids.CASE_ID_RE)
        self.assertIs(gr.case_ids, ids)

    def test_classifier_reads_o2c_r2r_ids(self):
        def rec(title, tags):
            spec = {"title": title, "tags": tags, "id": "x", "file": "m.spec.ts", "line": 1,
                    "tests": [{"projectName": "chromium", "status": "expected", "annotations": [],
                               "results": [{"status": "passed", "retry": 0, "duration": 1}]}]}
            return clf.parse_report({"suites": [{"title": "m.spec.ts", "specs": [spec]}]})[0]
        self.assertIsNone(rec("O2C-ORD-012 create order", []).case_id)  # titles are never read for IDs
        self.assertEqual(rec("journal entry", ["@R2R-JE-3"]).case_id, "R2R-JE-3")
        self.assertEqual(rec("journal entry", ["R2R-JE-3", "P1"]).case_id, "R2R-JE-3")

    @unittest.skipUnless((ROOT / "qa" / "audit.py").is_file(), "qa/audit.py not present")
    def test_report_multi_module_end_to_end(self):
        # project_go with IDs renamed to O2C-/R2R- (synthetic): same decision, IDs mapped, module-neutral wording.
        ren = {"FX-PASS-001": "O2C-ORD-001", "FX-PASS-002": "R2R-JE-002", "FX-SKIP-001": "O2C-ORD-003",
               "FX-DATA-002": "R2R-JE-004"}
        def sub(t):
            for k, v in ren.items():
                t = t.replace(k, v)
            return t
        with tempfile.TemporaryDirectory() as d:
            root = make_root("project_go", d)
            for f in [root / "tests" / "cases" / "FIXTURE_cases.yaml", root / "automation" / "tests" / "p2p" / "fixture.spec.ts"]:
                f.write_text(sub(f.read_text()))
            res = Path(d) / "results.json"
            data = json.loads(sub((FX / "FIXTURE_go_results.json").read_text()))
            for sp in data["suites"][0]["specs"]:
                if sp["title"].startswith("R2R-JE-002"):
                    sp["tags"] = ["@R2R-JE-002", "@stand-in"]
            res.write_text(json.dumps(data))
            tri = clf.triage(res, root / "tests" / "cases")
            out = Path(d) / "out"
            res_all = gr.write_all_modules(tri, out, root=root, review={}, include_p2=True)
            self.assertEqual(sorted(res_all), ["O2C", "R2R"])
            o, r_ = res_all["O2C"], res_all["R2R"]
            self.assertEqual((o["decision"], r_["decision"]), ("GO", "GO"), (o["criteria"], r_["criteria"]))
            self.assertEqual((o["module_label"], r_["module_label"]), ("O2C", "R2R"))
            self.assertEqual({x for rr in o["tri"]["records"] for x in rr["case_ids"]}, {"O2C-ORD-001", "O2C-ORD-003"})
            self.assertEqual({x for rr in r_["tri"]["records"] for x in rr["case_ids"]}, {"R2R-JE-002", "R2R-JE-004"})
            self.assertEqual([x["case"] for x in r_["standins"]], ["R2R-JE-002"])
            self.assertEqual(o["standins"], [])
            md = (out / "r2r" / "go-no-go.md").read_text()
            self.assertTrue(md.startswith("# R2R patch test: go/no-go report"))
            self.assertTrue((out / "o2c" / "go-no-go.md").read_text().startswith("# O2C patch test: go/no-go report"))
            for f in [out / "o2c" / "go-no-go.md", out / "r2r" / "go-no-go.md", out / "r2r" / "go-no-go.html", out / "go-no-go-all.md"]:
                self.assertNotIn("P2P", f.read_text(), f)
            self.assertFalse((out / "go-no-go.md").exists())  # no P2P report when there is no P2P module


@unittest.skipUnless((ROOT / "qa" / "audit.py").is_file(), "qa/audit.py not present")
class TestPerModuleReports(unittest.TestCase):
    """Synthetic project_multi: P2P (P1 pass, P2 fail 409), O2C (P1 pass, P1 skipped/fixme), one ID-less test."""

    def tri_for(self, root, results="FIXTURE_multi_results.json"):
        return clf.triage(FX / results, root / "tests" / "cases")

    def audit_counts(self, root, results, module):
        import subprocess
        p = subprocess.run([sys.executable, str(root / "qa" / "audit.py"), "--root", str(root), "--results", str(results),
                            "--module", module, "--out", str(root / f"audit-{module}.md")],
                           capture_output=True, text=True, timeout=60)
        import re as _re
        m = _re.search(r"results: pass (\d+) fail (\d+) flaky (\d+) skipped (\d+)", p.stdout)
        self.assertIsNotNone(m, p.stdout + p.stderr)
        return dict(zip(("pass", "fail", "flaky", "skipped"), map(int, m.groups())))

    def test_mixed_results_separate_counts(self):
        with tempfile.TemporaryDirectory() as d:
            root = make_root("project_multi", d)
            tri = self.tri_for(root)
            p2p = gr.summarize(tri, root, {}, module="P2P")
            o2c = gr.summarize(tri, root, {}, module="O2C")
            # ID-less 'mock health check' is counted in both modules (qa.in_module rule) and listed as unassigned
            self.assertEqual(p2p["counts"], {"total": 3, "executed": 3, "pass": 2, "fail": 1, "flaky": 0, "skipped": 0})
            self.assertEqual(o2c["counts"], {"total": 3, "executed": 2, "pass": 2, "fail": 0, "flaky": 0, "skipped": 1})
            for s_ in (p2p, o2c):
                self.assertEqual([r["title"] for r in s_["unassigned"]], ["mock health check"])
            self.assertEqual(p2p["n_cases"], 2)
            self.assertEqual(o2c["n_cases"], 2)
            # per-module triage verdicts: the P2P failure is classified in P2P only
            self.assertEqual(p2p["by_class"], {"data": 1})
            self.assertEqual(o2c["by_class"], {})
            # decisions: P2P GO (P1 passed; P2 failure is data, not a defect). O2C NO-GO (P1 O2C-ORD-002 fixme = not run)
            self.assertEqual(p2p["decision"], "GO", p2p["criteria"])
            self.assertEqual(o2c["decision"], "NO-GO")
            self.assertFalse(o2c["criteria"]["C1"][0])
            self.assertFalse(o2c["criteria"]["C2"][0])
            self.assertIn("O2C-ORD-002 (skipped)", o2c["criteria"]["C2"][1])
            self.assertIn("1/1 in-scope", p2p["criteria"]["C1"][1])
            self.assertIn("2/2 in-scope", o2c["criteria"]["C1"][1])

    def test_c5_matches_audit_per_module(self):
        with tempfile.TemporaryDirectory() as d:
            root = make_root("project_multi", d)
            res = FX / "FIXTURE_multi_results.json"
            tri = self.tri_for(root)
            for m in ("P2P", "O2C"):
                s_ = gr.summarize(tri, root, {}, module=m)
                self.assertTrue(s_["criteria"]["C5"][0], s_["criteria"]["C5"][1])
                a = self.audit_counts(root, res, m)
                self.assertEqual(a, {k: s_["counts"][k] for k in ("pass", "fail", "flaky", "skipped")}, m)

    def test_o2c_only_report(self):
        with tempfile.TemporaryDirectory() as d:
            root = make_root("project_multi", d)
            res = FX / "FIXTURE_o2c_only_results.json"
            tri = self.tri_for(root, "FIXTURE_o2c_only_results.json")
            out = Path(d) / "reports"
            s_ = gr.write_reports(tri, gr.module_out_dir(out, "O2C"), root=root, review={}, module="O2C")
            self.assertEqual(s_["counts"], {"total": 2, "executed": 1, "pass": 1, "fail": 0, "flaky": 0, "skipped": 1})
            self.assertTrue(s_["criteria"]["C5"][0], s_["criteria"]["C5"][1])
            self.assertEqual(self.audit_counts(root, res, "O2C"), {"pass": 1, "fail": 0, "flaky": 0, "skipped": 1})
            md = (out / "o2c" / "go-no-go.md").read_text()
            self.assertTrue(md.startswith("# O2C patch test"))
            self.assertNotIn("P2P", md)
            t = json.loads((out / "o2c" / "triage.json").read_text())
            self.assertEqual({r["case_id"] for r in t["records"]}, {"O2C-ORD-001", "O2C-ORD-002"})
            counts, _, _ = gr.load_qa_audit(root).extract_report_counts(str(out / "o2c" / "go-no-go.md"))
            self.assertEqual(sorted(set(counts["total"])), [2])
            # P2P on O2C-only results: no P2P tests, no P2P coverage evidence -> NO-GO, not a crash
            p = gr.summarize(tri, root, {}, module="P2P")
            self.assertEqual(p["counts"]["total"], 0)
            self.assertEqual(p["decision"], "NO-GO")

    def test_run_triage_module_all_cli(self):
        import shutil
        import subprocess
        with tempfile.TemporaryDirectory() as d:
            root = make_root("project_multi", d)
            (root / "automation" / "results").mkdir(parents=True)
            shutil.copy(FX / "FIXTURE_multi_results.json", root / "automation" / "results" / "results.json")
            p = subprocess.run([sys.executable, str(ROOT / "triage" / "run_triage.py"), "--root", str(root), "--module", "all"],
                               capture_output=True, text=True, timeout=60)
            self.assertNotIn("Traceback", p.stderr, p.stderr)
            self.assertEqual(p.returncode, 1)  # O2C NO-GO
            self.assertIn("[P2P] GO", p.stdout)
            self.assertIn("[O2C] NO-GO", p.stdout)
            self.assertTrue((root / "reports" / "go-no-go.md").is_file())       # P2P keeps legacy path
            self.assertTrue((root / "reports" / "o2c" / "go-no-go.md").is_file())
            self.assertTrue((root / "reports" / "go-no-go-all.md").is_file())
            idx = (root / "reports" / "go-no-go-all.md").read_text()
            self.assertIn("| O2C | NO-GO |", idx)
            self.assertIn("| P2P | GO |", idx)
            # default module is P2P
            p2 = subprocess.run([sys.executable, str(ROOT / "triage" / "run_triage.py"), "--root", str(root)],
                                capture_output=True, text=True, timeout=60)
            self.assertEqual(p2.returncode, 0, p2.stdout + p2.stderr)
            self.assertIn("[P2P] GO", p2.stdout)
            self.assertNotIn("[O2C]", p2.stdout)


@unittest.skipUnless((ROOT / "qa" / "audit.py").is_file(), "qa/audit.py not present")
class TestLifecycle(unittest.TestCase):
    """Synthetic project_lifecycle: LC = 1 active P1 (pass), tolerant P1 (real-defect fail), tolerant P2 (flaky),
    2 retired (one with a missing successor), event-driven P3 (no script), P3 fixme whose reason names DR-O2C-INT-003.
    HX = 2 cases, all on execution_hold, no scripts, no results."""
    RES = "FIXTURE_lifecycle_results.json"

    def setUp(self):
        self._d = tempfile.TemporaryDirectory()
        self.root = make_root("project_lifecycle", self._d.name)
        self.tri = clf.triage(FX / self.RES, self.root / "tests" / "cases")

    def tearDown(self):
        self._d.cleanup()

    def run_cli(self, *args):
        import shutil
        import subprocess
        (self.root / "automation" / "results").mkdir(parents=True, exist_ok=True)
        shutil.copy(FX / self.RES, self.root / "automation" / "results" / "results.json")
        return subprocess.run([sys.executable, str(ROOT / "triage" / "run_triage.py"), "--root", str(self.root), *args],
                              capture_output=True, text=True, timeout=60)

    def test_tolerant_does_not_gate(self):
        s_ = gr.summarize(self.tri, self.root, {}, module="LC")
        # tolerant LC-AI-001 (P1, real-defect failure) and LC-TF-001 (flaky) would each block if gating
        self.assertEqual(s_["decision"], "GO", s_["criteria"])
        self.assertEqual(s_["counts"], {"total": 4, "executed": 3, "pass": 1, "fail": 1, "flaky": 1, "skipped": 1})  # = audit
        self.assertEqual(s_["gating_counts"], {"total": 2, "executed": 1, "pass": 1, "fail": 0, "flaky": 0, "skipped": 1})
        self.assertIn("0/1 gating executed", s_["criteria"]["C3"][1])
        self.assertIn("1 of 1", s_["criteria"]["C2"][1])
        tol = {x["case"]: x["result"] for x in s_["lifecycle"]["tolerant"]}
        self.assertEqual(tol, {"LC-AI-001": "fail", "LC-TF-001": "flaky"})
        self.assertEqual(s_["lifecycle"]["tolerant_counts"], {"pass": 0, "fail": 1, "flaky": 1, "skipped": 0})

    def test_retired_out_of_scope_with_successor_check(self):
        s_ = gr.summarize(self.tri, self.root, {}, module="LC")
        ret = {x["case"]: x["superseded_by"] for x in s_["lifecycle"]["retired"]}
        self.assertEqual(ret, {"LC-OLD-001": "LC-A-001", "LC-OLD-002": "LC-NOPE-009"})
        self.assertEqual(s_["lifecycle"]["warnings"], ["LC-OLD-002: successor LC-NOPE-009 not found in tests/cases"])
        self.assertIn("1/1 in-scope", s_["criteria"]["C1"][1])  # retired P1 cases without scripts do not block
        self.assertEqual(s_["n_cases"], 7)          # same base as qa/audit.py 'cases' (C5)
        self.assertEqual(s_["n_active_cases"], 5)   # retired excluded

    def test_event_due(self):
        off = gr.summarize(self.tri, self.root, {}, module="LC", event_due=False)
        on = gr.summarize(self.tri, self.root, {}, module="LC", event_due=True)
        self.assertEqual(off["decision"], "GO")
        self.assertEqual(on["decision"], "NO-GO")  # event-driven P3 LC-EVT-001 now in scope, has no script
        self.assertIn("1/2 in-scope", on["criteria"]["C1"][1])
        self.assertEqual({x["case"]: x["scope"] for x in on["lifecycle"]["event_driven"]}, {"LC-EVT-001": "blocking"})

    def test_held_module(self):
        s_ = gr.summarize(self.tri, self.root, {}, module="HX")
        self.assertEqual(s_["decision"], "HELD")
        self.assertIn("fixture-hold (2 case(s)): Fixture hold until masking is confirmed", s_["hold_reason"])
        self.assertEqual(s_["n_scripts"], 0)

    def test_ids_from_tags_only_no_fake_module(self):
        # Regression: 'DR-O2C-INT-003' in a fixme reason must not become a case ID / a 'DR' module.
        rec = next(r for r in self.tri["records"] if r["title"] == "integration via recipe")
        self.assertEqual(rec["case_id"], "LC-FX-003")
        self.assertEqual(rec["tag_ids"], ["LC-FX-003"])
        self.assertIn("DR-O2C-INT-003", " ".join(rec["fixme_reasons"]))
        self.assertEqual(gr.modules_in(self.tri, self.root), ["HX", "LC"])
        qa = gr.load_qa_audit(self.root)
        for q in (qa, None):  # via qa.case_ids_from_tags, and the no-audit fallback: same answer
            self.assertEqual(gr.record_ids({"title": "P2P-INV-001 x", "tags": ["smoke"], "fixme_reasons": ["O2C-ORD-001"]}, q), [])
            self.assertEqual(gr.record_ids({"tags": ["@P2P-INV-001", "O2C-ORD-002", "P1"]}, q), ["O2C-ORD-002", "P2P-INV-001"])

    def test_scripts_row_every_module_and_c5_vs_audit(self):
        import subprocess
        out = self.root / "reports"
        gr.write_all_modules(self.tri, out, root=self.root, review={})
        qa = gr.load_qa_audit(self.root)
        for m, n_scripts, n_cases in (("LC", 1, 7), ("HX", 0, 2)):
            md = out / m.lower() / "go-no-go.md"
            self.assertIn(f"| Scripts | {n_scripts} |", md.read_text())
            counts, _, _ = qa.extract_report_counts(str(md))
            self.assertEqual(counts["scripts"], [n_scripts], m)
            self.assertEqual(counts["cases"], [n_cases], m)
            html_counts, _, _ = qa.extract_report_counts(str(out / m.lower() / "go-no-go.html"))
            self.assertEqual(html_counts["scripts"], [n_scripts], m)
            p = subprocess.run([sys.executable, str(self.root / "qa" / "audit.py"), "--root", str(self.root), "--results",
                                str(FX / self.RES), "--module", m, "--out", str(self.root / f"audit-{m}.md")],
                               capture_output=True, text=True, timeout=60)
            audit_md = (self.root / f"audit-{m}.md").read_text()
            rows = [ln for ln in audit_md.splitlines() if ln.startswith("| ") and ln.rstrip().endswith(("| yes |", "| NO |"))]
            self.assertTrue(rows, p.stdout + p.stderr)
            self.assertFalse([ln for ln in rows if ln.rstrip().endswith("| NO |")], "\n".join(rows))
        idx = (out / "go-no-go-all.md").read_text()
        self.assertIn("| HX | HELD |", idx)
        self.assertIn("| LC | GO |", idx)
        self.assertIn("3 no NO-GO but some HELD", idx)

    def test_exit_codes(self):
        self.assertEqual(self.run_cli("--module", "HX").returncode, 3)
        p = self.run_cli("--module", "all")
        self.assertEqual(p.returncode, 3, p.stdout + p.stderr)   # LC GO + HX HELD
        self.assertIn("[HX] HELD", p.stdout)
        self.assertEqual(self.run_cli("--module", "LC").returncode, 0)
        self.assertEqual(self.run_cli("--module", "all", "--event-due").returncode, 1)  # LC NO-GO wins over HELD
        self.assertEqual(gr.exit_code(["GO", "HELD", "NO-GO"]), 1)
        self.assertEqual(gr.exit_code(["GO", "GO"]), 0)


@unittest.skipUnless((ROOT / "qa" / "audit.py").is_file(), "qa/audit.py not present")
class TestSideSuitesCoverageBreach(unittest.TestCase):
    """Tolerant suite file, held-suite file (hold breach), coverage split, qa.case_ids_from_tags reuse.
    Uses project_lifecycle, which ships SYNTHETIC automation/results/{tolerant,held}/*.pwjson fixtures."""
    RES = "FIXTURE_lifecycle_results.json"

    def setUp(self):
        self._d = tempfile.TemporaryDirectory()
        self.root = make_root("project_lifecycle", self._d.name)
        self.tri = clf.triage(FX / self.RES, self.root / "tests" / "cases")

    def tearDown(self):
        self._d.cleanup()

    def audit(self, module, *extra, results=None):
        import subprocess
        out = self.root / f"audit-{module}.md"
        p = subprocess.run([sys.executable, str(self.root / "qa" / "audit.py"), "--root", str(self.root), "--results",
                            str(results or FX / self.RES), "--module", module, "--out", str(out), *extra],
                           capture_output=True, text=True, timeout=60)
        return p.stdout, out.read_text()

    def test_tolerant_suite_separate_and_never_gating(self):
        s_ = gr.summarize(self.tri, self.root, {}, module="LC")
        ts = s_["lifecycle"]["tolerant_suite"]
        self.assertTrue(ts["found"])
        self.assertEqual(ts["entries"], 3)
        self.assertEqual(ts["counts"], {"pass": 1, "fail": 2, "flaky": 0, "skipped": 0})
        self.assertEqual({x["case"]: x["suite_result"] for x in s_["lifecycle"]["tolerant"]}, {"LC-AI-001": "pass", "LC-TF-001": "fail"})
        # main totals / gating / decision unchanged by the tolerant-suite failures
        self.assertEqual(s_["counts"], {"total": 4, "executed": 3, "pass": 1, "fail": 1, "flaky": 1, "skipped": 1})
        self.assertEqual(s_["decision"], "GO")
        self.assertEqual(s_["by_class"], {})
        out = Path(self._d.name) / "out"
        gr.write_reports(self.tri, out, root=self.root, review={}, module="LC")
        md = (out / "go-no-go.md").read_text()
        self.assertIn("### Tolerant suite (does not affect GO/NO-GO)", md)
        self.assertIn("P/F/Fl/S 1/2/0/0", md)
        # same numbers as qa/audit.py's Tolerant suite section, and its count extractor still sees the main totals only
        stdout, _ = self.audit("LC")
        self.assertIn("results p/f/fl/s 1/2/0/0", stdout)
        counts, _, _ = gr.load_qa_audit(self.root).extract_report_counts(str(out / "go-no-go.md"))
        self.assertEqual(counts["fail"], [1])
        self.assertEqual(counts["total"], [4])

    def test_held_suite_runs_are_mock_only_not_breach(self):
        s_ = gr.summarize(self.tri, self.root, {}, module="HX")
        self.assertEqual(s_["decision"], "HELD")  # stays HELD
        self.assertIsNone(s_["hold_breach"])       # held-suite runs are allowed (Chief of Staff 9 Oct 18:30 IST)
        self.assertIsNone(gr.breach_text(s_))
        h = s_["held_mock"]
        self.assertEqual((h["runs"], h["ids"], h["file"]), (3, ["HX-A-001", "HX-A-002"], "automation/results/held/results.held.pwjson"))
        self.assertEqual(h["counts"], {"pass": 2, "fail": 0, "flaky": 0, "skipped": 1})
        self.assertEqual(s_["counts"]["total"], 0)  # never in totals
        out = self.root / "reports"
        gr.write_all_modules(self.tri, out, root=self.root, review={})
        md = (out / "hx" / "go-no-go.md").read_text()
        self.assertIn("Held cases run on mock only (synthetic data, allowed by Chief of Staff 9 Oct 18:30 IST; not counted): "
                      "3 run(s) in `automation/results/held/results.held.pwjson`", md)
        self.assertIn("HX-A-001, HX-A-002", md)
        idx = (out / "go-no-go-all.md").read_text()
        for txt in (md, (out / "hx" / "go-no-go.html").read_text(), idx):
            self.assertNotIn("HOLD BREACH", txt)
        self.assertIn("## Held cases run on mock only (allowed, not counted)", idx)
        self.assertIn("| HX | HELD |", idx)
        self.assertIn("3 run(s) on mock only, 2 case(s) (allowed, not counted)", idx)
        self.assertIsNone(gr.summarize(self.tri, self.root, {}, module="LC")["held_mock"])
        # qa/audit.py sees the same held-suite entries and the counts still match (0 mismatches)
        stdout, amd = self.audit("HX")
        self.assertIn("3 entr(y/ies) for this module", amd)
        self.assertFalse([ln for ln in amd.splitlines() if ln.startswith("| ") and ln.rstrip().endswith("| NO |")])

    def test_hold_breach_from_gate_results(self):
        data = json.loads((FX / self.RES).read_text())
        sp = json.loads(json.dumps(data["suites"][0]["specs"][0]))
        sp["title"], sp["tags"], sp["file"] = "held in gate", ["HX-A-002"], "hx/hx.spec.ts"
        data["suites"][0]["specs"].append(sp)
        res = Path(self._d.name) / "gate.json"
        res.write_text(json.dumps(data))
        tri = clf.triage(res, self.root / "tests" / "cases")
        s_ = gr.summarize(tri, self.root, {}, module="HX")
        self.assertEqual(s_["decision"], "HELD")
        self.assertEqual(s_["hold_breach"]["gate_ids"], ["HX-A-002"])
        self.assertEqual(s_["counts"]["total"], 1)  # a gate entry stays in totals (C5 parity with the audit)
        self.assertTrue(s_["criteria"]["C5"][0], s_["criteria"]["C5"][1])
        self.assertTrue(gr.breach_text(s_).startswith("HOLD BREACH: 1 entr(y/ies) for held case(s) in the main results"))
        self.assertIsNotNone(s_["held_mock"])  # the held-suite note is still shown alongside, not as a breach
        out = Path(self._d.name) / "rep"
        gr.write_all_modules(tri, out, root=self.root, review={})
        idx = (out / "go-no-go-all.md").read_text()
        self.assertIn("## HOLD BREACH (held cases in the main results)", idx)
        self.assertIn("**HOLD BREACH**: 1 in main results (HX-A-002)", idx)
        self.assertIn("HOLD BREACH", (out / "hx" / "go-no-go.md").read_text())

    def test_coverage_split_matches_audit(self):
        s_ = gr.summarize(self.tri, self.root, {}, module="LC")
        self.assertEqual(gr.coverage_short(s_), "1 fully / 0 stand-in only (of 1)")
        stdout, _ = self.audit("LC")
        self.assertIn("fully covered excl. stand-ins: 1", stdout)
        with tempfile.TemporaryDirectory() as d:  # P1 stand-in only, decided from result tags (like the audit)
            root = make_root("project_go", d)
            res = results_with_standin(FX / "FIXTURE_go_results.json", "FX-PASS-001", d)
            tri = clf.triage(res, root / "tests" / "cases")
            s2 = gr.summarize(tri, root, {}, module="FX")
            p1 = s2["coverage"]["p1"]
            self.assertEqual((p1["fully"], p1["standin"], p1["not_covered"]), ([], ["FX-PASS-001"], []))
            self.assertIn("P1 in scope: 1 case(s); 0 fully covered, 1 stand-in only", gr.render_markdown(tri, s2))
            import subprocess
            p = subprocess.run([sys.executable, str(root / "qa" / "audit.py"), "--root", str(root), "--results", str(res),
                                "--module", "FX", "--out", str(Path(d) / "a.md")], capture_output=True, text=True, timeout=60)
            self.assertIn("fully covered excl. stand-ins: 0", p.stdout)
            self.assertIn("covered-by-substitute: 1", p.stdout)

    def test_ids_via_qa_case_ids_from_tags(self):
        qa = gr.load_qa_audit(self.root)
        calls = []
        orig = qa.case_ids_from_tags
        def spy(tags, id_re=None):
            calls.append(list(tags))
            return orig(tags, id_re)
        qa.case_ids_from_tags = spy
        try:
            gr_load = gr.load_qa_audit
            gr.load_qa_audit = lambda root: qa
            s_ = gr.summarize(self.tri, self.root, {}, module="LC")
        finally:
            gr.load_qa_audit = gr_load
            qa.case_ids_from_tags = orig
        self.assertTrue(calls)
        self.assertTrue(s_["criteria"]["C5"][0])
        # spec-level tags only (what the audit reads); annotation text is never passed
        self.assertFalse(any("DR-O2C-INT-003" in " ".join(map(str, c)) for c in calls))


if __name__ == "__main__":
    unittest.main()