File size: 73,200 Bytes
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1293
1294
1295
#!/usr/bin/env python3
"""QA traceability + results audit, per Fusion module pack (P2P, O2C, R2R, ...; mock-only).



Module selection (--module, default P2P): a case belongs to the module of its ID prefix (triage/ids.py

module_of: 'O2C-ORD-001' -> O2C), else to its folder under tests/cases/<module>/; TC-style ids at the top

level are 'UNASSIGNED'. Scripts/results are kept for a module if any case ID in them has that module, or if

they carry no module ID at all (scope unknown, so they stay visible in every module). --module all writes one

report per module plus qa/audit-report-all.md. Library defaults (load_cases/load_scripts module='P2P') keep

reports/generate_report.py on P2P.



Maps: tests/cases/*.yaml case IDs -> Playwright scripts in automation/ -> run results

(default: automation/results/results.json, Playwright JSON reporter) -> triage output

-> counts quoted in the go/no-go report under reports/.



Team decisions (9 Oct 2026) applied here:

  * Playwright runs with retries=0; the LangGraph graph owns the single retry and merges attempts

    into a Playwright-shaped report (status "flaky" = failed then passed). Explicit reruns can be

    passed with --rerun; a fail in the main results that passes in a rerun is reported as flaky-on-rerun.

  * Tiered coverage (priority read from each case YAML). In-scope tiers count toward the coverage

    criterion: P1 by default, P1+P2 with --include-p2 (same flag name as architecture/p2p_graph.py).

    P2 without the flag = best effort (gaps reported, never blocking). P3/P4 = deferred: excluded from

    coverage gaps, listed, and never a blocker. Cases with no recognisable priority are treated as

    in scope (unknown risk) and listed.

  * Stand-in scripts: a test tagged @stand-in (or @standin/@substitute, or "stand-in" in its title)

    covers its case "by substitute" (e.g. P2P-INV-006 spreadsheet upload -> REST import stand-in).

    Such cases count as covered for the coverage criterion but are listed separately, not as fully covered.

  * The GO/NO-GO decision itself is made by reports/generate_report.py (criteria C1-C6), which imports

    this module. This audit reports QA metrics and cross-checks counts; it does not decide GO.



Writes qa/audit-report.md. Stdlib only; uses PyYAML if installed, else a regex fallback.

Missing inputs are reported as 'not yet available', never guessed.

"""
import argparse
import csv
import datetime
import html
import json
import os
import re
import sys
import xml.etree.ElementTree as ET

try:
    import yaml  # type: ignore
except Exception:  # pragma: no cover
    yaml = None

NA = "not yet available"
SKIP_DIRS = {"node_modules", ".venv", "venv", ".git", "__pycache__", ".cache", "playwright-report-data"}
SCRIPT_RE = re.compile(r"\.(spec|test)\.(ts|js|mjs|cjs|tsx|jsx)$")
def _load_shared_ids():
    """triage/ids.py is the team's single case-ID parser (any module prefix + TC-). Fallback = same patterns."""
    try:
        import importlib.util
        p = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "triage", "ids.py")
        if os.path.isfile(p):
            spec = importlib.util.spec_from_file_location("_qa_shared_ids", p)
            m = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(m)
            return m.CASE_ID_PATTERN, m.STANDIN_RE, m.module_of, "triage/ids.py"
    except Exception:
        pass
    pat = (r"(?<![A-Za-z0-9_-])(?:[A-Z][A-Z0-9]{1,5}(?:-[A-Z0-9]+)+-\d+|TC[-_][A-Za-z0-9]+(?:[-_][A-Za-z0-9]+)*)"
           r"(?![A-Za-z0-9_])")
    def module_of(cid):
        if not cid or re.match(r"TC[-_]", cid):
            return None
        return cid.split("-", 1)[0]
    return pat, re.compile(r"@?(?:stand[-_ ]?in|substitute)\b", re.I), module_of, "qa/audit.py fallback (same patterns)"


CASE_ID_PATTERN, STANDIN_RE, module_of, IDS_SOURCE = _load_shared_ids()
DEFAULT_MODULE = "P2P"
# Chief of Staff decision, 9 Oct 2026 18:34 IST: these partly substituted P1 cases ARE stand-ins (not full coverage).
# Automation is adding @stand-in tags; until a result entry carries the tag, the audit applies the decision itself.
DECIDED_STANDINS = {
    "SCP-INT-001": "duration/SLA asserts cannot fail on the mock (synchronous processes)",
    "SCP-SUP-001": "plan compared with a mock-captured baseline",
    "SCP-SUP-002": "transfer orders held by the mock SCP pack",
    "P2M-WO-004": "backflush variant not modelled; manual issue only",
    "SCM-CST-001": "uncostable fix via mock API",
    "EXP-RMB-001": "payment request held by the mock EXP pack, no Payables payment",
    "O2C-SEC-005": "SoD from the mock role model (ASSUMED)",
    "PPM-CST-001": "synthetic payroll cost file instead of HCM costing output",
}
DECIDED_STANDINS_NOTE = "Chief of Staff decision 9 Oct 2026 18:34 IST"
DEFAULT_RESULTS = os.path.join("automation", "results", "results.json")
DEFAULT_ID_RE = CASE_ID_PATTERN
TEST_TITLE_RE = re.compile(r"""\btest(?:\.(?:only|skip|fixme|fail|slow))?\(\s*(['"`])(.+?)\1""", re.S)
DEFECT_WORDS = ("defect", "bug", "regression", "product")
NON_DEFECT_WORDS = ("ui", "locator", "data", "timing", "environment", "env", "flaky", "test_issue", "script", "infra", "non_defect")
CLASS_KEYS = ("classification", "category", "verdict", "label", "failure_class", "class", "type")


def walk_files(root, exts):
    if not os.path.isdir(root):
        return []
    out = []
    for d, dirs, files in os.walk(root):
        dirs[:] = [x for x in dirs if x not in SKIP_DIRS]
        for f in files:
            if f.lower().endswith(exts):
                out.append(os.path.join(d, f))
    return sorted(out)


def rel(p, base):
    try:
        return os.path.relpath(p, base).replace(os.sep, "/")
    except ValueError:
        return p


# ---------------------------------------------------------------- cases
SPECIAL_FIELDS = ("status", "superseded_by", "retired_reason", "suite", "suite_reason", "go_no_go",
                  "execution_hold", "execution_hold_reason", "schedule", "condition")


def _top_scalar(text, key):
    """Top-level (column 0) YAML scalar `key:` without PyYAML: plain, single- or double-quoted, incl. multi-line

    double-quoted values with escaped line breaks (`\\` at line end) and indented plain continuation lines."""
    m = re.search(r"^" + re.escape(key) + r"[ \t]*:[ \t]*(.*)$", text, re.M)
    if not m:
        return None
    first = m.group(1).rstrip()
    rest = text[m.end():].split("\n")[1:]
    if first.startswith('"'):
        buf = first[1:]
        i = 0
        while not re.search(r'(?<!\\)"\s*(#.*)?$', buf) and i < len(rest):
            buf += "\n" + rest[i]; i += 1
        buf = re.sub(r'(?<!\\)"\s*(#.*)?$', "", buf)
        buf = re.sub(r"\\\n\s*", "", buf)            # escaped line break: join, drop indentation
        buf = re.sub(r"\s*\n\s*", " ", buf)            # plain line folding
        return buf.replace("\\ ", " ").replace('\\"', '"').strip()
    if first.startswith("'"):
        buf = first[1:]
        i = 0
        while not re.search(r"(?<!')'\s*$", buf) and i < len(rest):
            buf += " " + rest[i].strip(); i += 1
        return re.sub(r"'\s*$", "", buf).replace("''", "'").strip()
    val = re.sub(r"\s+#.*$", "", first).strip()
    for ln in rest:  # plain scalar continuation lines (indented, not a new key / list item)
        if ln.startswith((" ", "\t")) and ln.strip() and not re.match(r"\s*(-\s|[\w.-]+\s*:)", ln):
            val += " " + ln.strip()
        else:
            break
    return val


def _norm_field(v):
    if v is None:
        return ""
    if isinstance(v, bool):
        return "true" if v else "false"
    return str(v).strip()


def case_flags(c):
    """Classify a case by the tests/README.md lifecycle fields. Exclusion precedence: retired > held > tolerant.

    conditional / event_driven are informational flags (they do not by themselves change scope; see scope logic)."""
    status = c.get("status", "").lower()
    suite = c.get("suite", "").lower()
    gng = c.get("go_no_go", "").lower()
    return {
        "retired": status == "retired",
        "held": bool(c.get("execution_hold", "")),
        "tolerant": suite == "tolerant" or gng in ("false", "no", "0"),
        "conditional": bool(c.get("condition", "")),
        "event_driven": c.get("schedule", "").lower().replace("_", "-") == "event-driven",
    }


def case_class(c):
    f = case_flags(c)
    return "retired" if f["retired"] else "held" if f["held"] else "tolerant" if f["tolerant"] else None


def _collect_cases(obj, src, out):
    if isinstance(obj, list):
        for x in obj:
            _collect_cases(x, src, out)
    elif isinstance(obj, dict):
        cid = None
        for k in ("id", "case_id", "test_id", "caseId", "ID"):
            if k in obj and isinstance(obj[k], (str, int)):
                cid = str(obj[k]).strip()
                break
        if cid and any(k in obj for k in ("title", "name", "steps", "process", "expected", "priority", "description")):
            out.append({"id": cid, "file": src, "title": str(obj.get("title") or obj.get("name") or ""),
                        "priority": str(obj.get("priority") or obj.get("risk") or ""),
                        "process": str(obj.get("process") or obj.get("module") or ""),
                        **{k: _norm_field(obj.get(k)) for k in SPECIAL_FIELDS}})
            return
        for k in ("cases", "tests", "test_cases", "scenarios"):
            if k in obj:
                _collect_cases(obj[k], src, out)
                return
        if cid:  # bare dict with id only
            out.append({"id": cid, "file": src, "title": "", "priority": "", "process": "",
                        **{k: _norm_field(obj.get(k)) for k in SPECIAL_FIELDS}})


def case_module(case):
    """Module of a case: ID prefix, else tests/cases/<folder>/, else UNASSIGNED."""
    m = module_of(case["id"])
    if m:
        return m
    parts = case["file"].replace("\\", "/").split("/")
    if len(parts) > 3 and parts[0] == "tests" and parts[1] == "cases":
        return parts[2].upper()
    return "UNASSIGNED"


def _want(module):
    return None if module in (None, "", "all", "ALL") else str(module).upper()


def load_cases(root, warnings, module=DEFAULT_MODULE):
    """Cases from tests/cases/**/*.yaml, filtered to `module` (default P2P; None/'all' = every module)."""
    files, cases = _load_all_cases(root, warnings)
    want = _want(module)
    if want:
        cases = [c for c in cases if case_module(c) == want]
        files = sorted({os.path.join(root, c["file"]) for c in cases})
    return files, cases


def _load_all_cases(root, warnings):
    files = walk_files(os.path.join(root, "tests", "cases"), (".yaml", ".yml"))
    cases = []
    for f in files:
        src = rel(f, root)
        try:
            text = open(f, encoding="utf-8").read()
        except Exception as e:
            warnings.append(f"could not read {src}: {e}")
            continue
        got = []
        if yaml is not None:
            try:
                for doc in yaml.safe_load_all(text):
                    _collect_cases(doc, src, got)
            except Exception as e:
                warnings.append(f"YAML parse error in {src}: {e}; used regex fallback")
                got = []
        if not got:  # regex fallback: one block per id line, pick simple scalar fields inside the block
            idre = re.compile(r"""^\s*-?\s*(?:id|case_id|test_id)\s*:\s*["']?([A-Za-z0-9_.\-]+)""", re.M)
            ms = list(idre.finditer(text))
            for j, m in enumerate(ms):
                block = text[m.start(): ms[j + 1].start() if j + 1 < len(ms) else len(text)]
                def fld(*names):
                    for n in names:
                        mm = re.search(r"^\s*-?\s*" + n + r"""\s*:\s*["']?([^"'\n#]+)""", block, re.M)
                        if mm:
                            return mm.group(1).strip()
                    return ""
                got.append({"id": m.group(1), "file": src, "title": fld("title", "name"),
                            "priority": fld("priority", "risk"), "process": fld("process", "module")})
            if len(got) == 1:  # one case per file (tests/README.md): lifecycle fields are top-level scalars
                for k in SPECIAL_FIELDS:
                    got[0][k] = _norm_field(_top_scalar(text, k))
            else:
                for g in got:
                    for k in SPECIAL_FIELDS:
                        g.setdefault(k, "")
        cases.extend(got)
    return files, cases


def _local_tier(priority):
    """Fallback P1..P4 mapping; identical to triage/risk.py tier() (used when that module is absent)."""
    t = str(priority or "").strip().lower()
    if not t:
        return None
    m = re.match(r"p\s*([1-4])\b", t) or re.match(r"([1-4])$", t)
    if m:
        return "P" + m.group(1)
    for word, v in (("critical", "P1"), ("high", "P2"), ("medium", "P3"), ("low", "P4")):
        if t.startswith(word):
            return v
    return None


def _load_shared_tier():
    """Use the team's single shared mapping (triage/risk.py, also used by reports/generate_report.py) if present."""
    try:
        import importlib.util
        p = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "triage", "risk.py")
        if os.path.isfile(p):
            spec = importlib.util.spec_from_file_location("_qa_shared_risk", p)
            m = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(m)
            return m.tier, "triage/risk.py"
    except Exception:
        pass
    return _local_tier, "qa/audit.py fallback"


tier, TIER_SOURCE = _load_shared_tier()


def scope_of(priority, include_p2=False):
    """blocking (in scope) | best_effort | deferred (team decision 2; --include-p2 puts P2 in scope)."""
    t = tier(priority)
    if t == "P2":
        return "blocking" if include_p2 else "best_effort"
    if t in ("P3", "P4"):
        return "deferred"
    return "blocking"  # P1 or untiered


# ---------------------------------------------------------------- scripts
TAG_LITERAL_RE = re.compile(r"""['"`]@([A-Za-z0-9_.\-]+)['"`]""")


def case_ids_from_tags(tags, id_re=None):
    """Case IDs from Playwright tags ONLY ('@P2P-INV-006' in source, 'P2P-INV-006' in JSON), as triage/ids.py

    tag_case_id(): the whole tag must be an ID. Titles, file names and annotation text are never read (they carry

    data-recipe IDs such as DR-INV-001, which produced a fake DR module)."""
    rx = re.compile(id_re) if isinstance(id_re, str) else (id_re or re.compile(CASE_ID_PATTERN))
    out = set()
    for t in tags or ():
        t = str(t or "").strip().lstrip("@")
        m = rx.fullmatch(t)
        if m:
            out.add(m.group(0))
    return out


def script_tag_ids(text, id_re=None):
    """Case IDs from literal '@<CASE-ID>' tag strings in script source (tags built at runtime are not visible)."""
    return case_ids_from_tags(TAG_LITERAL_RE.findall(text), id_re)


def find_ids(text, known, id_re):
    """Legacy free-text ID search (kept for callers such as reports/generate_report.py C5). qa/audit.py itself

    now uses case_ids_from_tags / script_tag_ids only."""
    ids = set()
    for k in known:
        if re.search(r"(?<![A-Za-z0-9])" + re.escape(k) + r"(?![A-Za-z0-9])", text):
            ids.add(k)
    for m in id_re.finditer(text):
        ids.add(m.group(0))
    # drop generic matches that are strict prefixes of a known id found (e.g. P2P-REQ vs P2P-REQ-001)
    return {i for i in ids if i in known or not any(k != i and k.startswith(i) for k in ids)}


def in_module(ids, module):
    """Keep an item for `module` if any id has that module, or if no id carries a module (scope unknown)."""
    want = _want(module)
    if not want:
        return True
    mods = {module_of(i) for i in ids} - {None}
    return not mods or want in mods


def load_scripts(root, known, id_re, module=DEFAULT_MODULE):
    files = [f for f in walk_files(os.path.join(root, "automation"), (".ts", ".js", ".mjs", ".cjs", ".tsx", ".jsx"))
             if SCRIPT_RE.search(f)]
    scripts = []
    for f in files:
        text = open(f, encoding="utf-8", errors="replace").read()
        titles = [m.group(2) for m in TEST_TITLE_RE.finditer(text)]
        ids = script_tag_ids(text, id_re)
        # per-test segments: ids covered by a full test vs by a stand-in test
        full_ids, standin_ids = set(), set()
        starts = [m.start() for m in TEST_TITLE_RE.finditer(text)]
        for j, st in enumerate(starts):
            seg = text[st: starts[j + 1] if j + 1 < len(starts) else len(text)]
            head = seg[: seg.find("async") if "async" in seg else 400]  # title + options (tags) only
            seg_ids = script_tag_ids(head, id_re)
            if not seg_ids:  # tag only on test.describe(...): file-level tag IDs
                seg_ids = set(ids)
            is_standin = STANDIN_RE.search(head) or re.search(r"""type\s*:\s*['"`](?:stand[-_ ]?in|substitute)['"`]""", seg)
            (standin_ids if is_standin else full_ids).update(seg_ids)
        if not starts:
            full_ids = set(ids)
        scripts.append({"path": f, "rel": rel(f, root), "titles": titles, "ids": ids, "text": text,
                        "full_ids": full_ids, "standin_ids": standin_ids - full_ids})
    return [s_ for s_ in scripts if in_module(s_["ids"], module)]


# ---------------------------------------------------------------- results
def _pw_specs(suite, file_hint, out):
    f = suite.get("file") or file_hint
    for spec in suite.get("specs", []) or []:
        for t in spec.get("tests", []) or [{}]:
            st = t.get("status")
            results = t.get("results", []) or []
            if st == "flaky":
                status = "flaky"
            elif st == "skipped":
                status = "skipped"
            elif st == "unexpected":
                status = "fail"
            elif st == "expected":
                status = "pass"
            else:  # derive from results
                rs = [r.get("status") for r in results]
                if not rs:
                    status = "unknown"
                elif rs[-1] == "passed":
                    status = "flaky" if any(r in ("failed", "timedOut") for r in rs[:-1]) else "pass"
                elif rs[-1] == "skipped":
                    status = "skipped"
                else:
                    status = "fail"
            tags = list(spec.get("tags", []) or []) + [a.get("type", "") + ":" + str(a.get("description", ""))
                                                       for a in (t.get("annotations") or [])]
            sf = spec.get("file") or f
            if f and sf != f and not re.search(r"\.(spec|test)\.[cm]?[jt]sx?$", sf):
                sf = f  # test() called from a shared helper (Fusion step runner): credit the spec file that was run
            out.append({"title": spec.get("title", ""), "file": sf, "tags": tags,
                        "spec_tags": list(spec.get("tags", []) or []),
                        "project": t.get("projectName", ""), "status": status,
                        "fixme": any(a.get("type") in ("fixme", "fixme()") for a in (t.get("annotations") or []))})
    for s in suite.get("suites", []) or []:
        _pw_specs(s, f, out)


def parse_playwright_json(path):
    try:
        data = json.load(open(path, encoding="utf-8"))
    except Exception:
        return None
    if not isinstance(data, dict) or "suites" not in data or not ("config" in data or "stats" in data):
        return None
    out = []
    for s in data.get("suites", []):
        _pw_specs(s, s.get("file", ""), out)
    return {"format": "playwright-json", "tests": out, "stats": data.get("stats", {})}


def parse_junit(path):
    try:
        tree = ET.parse(path)
    except Exception:
        return None
    r = tree.getroot()
    if r.tag not in ("testsuites", "testsuite"):
        return None
    out = []
    for tc in r.iter("testcase"):
        tags = [p.get("value", "") for p in tc.iter("property")]
        kids = {c.tag for c in tc}
        if kids & {"failure", "error"}:
            status = "fail"
        elif kids & {"flakyFailure", "flakyError", "rerunFailure", "rerunError"}:
            status = "flaky"
        elif "skipped" in kids:
            status = "skipped"
        else:
            status = "pass"
        out.append({"title": tc.get("name", ""), "file": tc.get("file") or tc.get("classname", ""),
                    "tags": tags, "spec_tags": [x for x in tags if ":" not in x], "project": "", "status": status})
    return {"format": "junit", "tests": out, "stats": {}}


def find_results(root, explicit, discover=False):
    if explicit:
        cands = [p if os.path.isabs(p) else os.path.join(root, p) for p in explicit]
    elif discover:
        cands = (walk_files(os.path.join(root, "automation"), (".json", ".xml")) +
                 walk_files(os.path.join(root, "reports"), (".json", ".xml")))
    else:
        cands = [os.path.join(root, DEFAULT_RESULTS)]
    cands = [p for p in cands if os.path.isfile(p)]
    found = []
    for p in cands:
        if os.path.getsize(p) > 200 * 1024 * 1024:
            continue
        res = parse_junit(p) if p.lower().endswith(".xml") else (parse_playwright_json(p) or parse_junit(p))  # .json/.pwjson/…
        if res is not None:
            res["path"] = p
            res["mtime"] = os.path.getmtime(p)
            found.append(res)
    return found


# ---------------------------------------------------------------- triage
def _norm(v):
    return re.sub(r"[\s\-/]+", "_", str(v).strip().lower())


def classify(v):
    n = _norm(v)
    if not n:
        return "unclassified"
    if n.startswith("non") or n.startswith("not_"):
        return "non_defect"
    if any(w in n for w in DEFECT_WORDS):
        return "defect"
    if any(w in n for w in NON_DEFECT_WORDS):
        return "non_defect"
    return "unclassified"


def _triage_records(obj, out):
    if isinstance(obj, list):
        for x in obj:
            _triage_records(x, out)
    elif isinstance(obj, dict):
        for k in CLASS_KEYS:
            if k in obj and isinstance(obj[k], str) and classify(obj[k]) != "unclassified":
                out.append(obj)
                return
        for v in obj.values():
            if isinstance(v, (list, dict)):
                _triage_records(v, out)


def load_triage(root, result_paths):
    files = walk_files(os.path.join(root, "triage"), (".json", ".jsonl", ".csv", ".yaml", ".yml")) + \
        [f for f in walk_files(os.path.join(root, "reports"), (".json", ".jsonl", ".csv", ".yaml", ".yml"))]
    files = [f for f in files if f not in result_paths and "/fixtures/" not in f and "/samples/" not in f]
    recs, used = [], []
    for f in files:
        got = []
        try:
            if f.endswith(".csv"):
                got = [r for r in csv.DictReader(open(f, encoding="utf-8"))
                       if any(classify(r.get(k, "")) != "unclassified" for k in CLASS_KEYS)]
            elif f.endswith(".jsonl"):
                for line in open(f, encoding="utf-8"):
                    if line.strip():
                        _triage_records(json.loads(line), got)
            elif f.endswith(".json"):
                _triage_records(json.load(open(f, encoding="utf-8")), got)
            elif yaml is not None:
                for d in yaml.safe_load_all(open(f, encoding="utf-8")):
                    _triage_records(d, got)
        except Exception:
            continue
        if got:
            used.append(f)
            for r in got:
                r["_src"] = f
            recs.extend(got)
    return used, recs


def triage_class(r):
    for k in CLASS_KEYS:
        if k in r and classify(r[k]) != "unclassified":
            return classify(r[k]), str(r[k])
    return "unclassified", ""


# ---------------------------------------------------------------- go/no-go report
COUNT_WORDS = {"passed": "pass", "pass": "pass", "failed": "fail", "fail": "fail", "failures": "fail",
               "flaky": "flaky", "skipped": "skipped", "total": "total", "executed": "executed",
               "cases": "cases", "scripts": "scripts"}


def find_gonogo(root, module=DEFAULT_MODULE):
    """Module's go/no-go report.

    P2P:    reports/go-no-go.{md,html}.

    Others: reports/<module lower>/go-no-go.{md,html}.

    Fallback (old layout): a top-level reports/ file naming the module (e.g. go-no-go-o2c.md); for P2P any

    un-suffixed top-level report. Never another module's report, never reports/include-p2/ or go-no-go-all.*.

    .md is preferred over .html (deterministic parse)."""
    want = (_want(module) or DEFAULT_MODULE).lower()
    rd = os.path.join(root, "reports")
    exts = (".md", ".html", ".htm")
    primary_dir = rd if want == DEFAULT_MODULE.lower() else os.path.join(rd, want)
    for ext in exts:
        f = os.path.join(primary_dir, "go-no-go" + ext)
        if os.path.isfile(f):
            return f
    # fallback: old top-level naming
    files = sorted(os.path.join(rd, f) for f in (os.listdir(rd) if os.path.isdir(rd) else [])
                   if f.lower().endswith(exts) and os.path.isfile(os.path.join(rd, f)))
    named = [f for f in files if re.search(r"(?<![a-z0-9])" + re.escape(want) + r"(?![a-z0-9])", os.path.basename(f).lower())]
    if named:
        files = named
    elif want != DEFAULT_MODULE.lower():
        return None
    else:  # P2P legacy: drop reports that name another module or 'all'
        files = [f for f in files if not re.search(r"[-_](?!p2p\.)[a-z][a-z0-9]{1,5}\.(md|html?)$", os.path.basename(f).lower())]
    pref = [f for f in files if re.search(r"go[-_ ]?no[-_ ]?go|gonogo|report|summary", os.path.basename(f), re.I)]
    pick = pref or files
    if not pick:
        return None
    md = [f for f in pick if f.lower().endswith(".md")]
    return max(md or pick, key=os.path.getmtime)


def extract_report_counts(path):
    text = open(path, encoding="utf-8", errors="replace").read()
    if path.endswith((".html", ".htm")):
        text = re.sub(r"<(script|style)[^>]*>.*?</\1>", " ", text, flags=re.S | re.I)
        text = re.sub(r"</t[dh]>\s*<t[dh][^>]*>", " | ", text, flags=re.I)
        text = html.unescape(re.sub(r"<[^>]+>", " ", text))
    counts = {}
    w = "|".join(sorted(COUNT_WORDS, key=len, reverse=True))
    pats = [re.compile(r"\b(" + w + r")\b[^\d\n|]{0,15}[:=|]\s*\**\s*(\d+)\b", re.I),  # Passed: 12 / | Passed | 12 |
            re.compile(r"\b(\d+)\s+(?:tests?\s+|cases?\s+)?(" + w + r")\b", re.I)]       # 12 passed
    for m in pats[0].finditer(text):
        counts.setdefault(COUNT_WORDS[m.group(1).lower()], []).append(int(m.group(2)))
    for m in pats[1].finditer(text):
        counts.setdefault(COUNT_WORDS[m.group(2).lower()], []).append(int(m.group(1)))
    mock_note = bool(re.search(r"\bmock\b", text, re.I))
    fusion_claim = bool(re.search(r"(ran|run|executed|tested)\s+(?:\w+\s+){0,3}(?:against|on)\s+(?:the\s+|a\s+)?"
                                  r"(?:real\s+|oracle\s+)?fusion\s+(?:test\s+)?pod", text, re.I))
    return counts, mock_note, fusion_claim


# ---------------------------------------------------------------- stability scan
SCAN_RULES = [
    ("S2", "fixed sleep: waitForTimeout", re.compile(r"\.waitForTimeout\s*\(")),
    ("S2", "sleep via setTimeout promise", re.compile(r"new\s+Promise\s*\([^)]*setTimeout")),
    ("S1", "xpath locator", re.compile(r"""(['"`])\s*(?:xpath=|//)[^'"`]*\1""")),
    ("S1", "CSS locator via page.locator/$/$$", re.compile(r"""(?:\.locator|\.\$\$?|\.\$eval)\(\s*(['"`])[.#\[][^'"`]*\1""")),
    ("S1", "raw selector string in page.click/fill/type/check", re.compile(r"""page\.(?:click|dblclick|fill|type|press|check|uncheck|hover|selectOption|textContent|innerText|isVisible)\(\s*['"`]""")),
    ("S1", "nth-child / positional selector", re.compile(r":nth-child|:nth-of-type|>>\s*nth=|\.nth\(\d+\)")),
    ("S3", "force click/fill bypasses actionability", re.compile(r"force\s*:\s*true")),
    ("S3", "non-retrying assertion on await isVisible/textContent", re.compile(r"expect\(\s*await\s+[^)]*\.(?:isVisible|isEnabled|textContent|innerText|count)\(")),
    ("S3", "waitForLoadState('networkidle')", re.compile(r"networkidle")),
    ("S4", "hardcoded business id (PO/INV/REQ/SUP + digits)", re.compile(r"""['"`](?:PO|INV|REQ|SUP|RCPT|PAY)[-_]?\d{3,}['"`]""")),
    ("S4", "serial mode (order dependence)", re.compile(r"describe\.serial|mode:\s*['\"]serial")),
    ("S6", "possible literal secret", re.compile(r"""(?i)(password|passwd|secret|token|api[_-]?key)\s*[:=]\s*['"`][^'"`${}]{4,}['"`]""")),
    ("S8", "focused test (test.only)", re.compile(r"\b(?:test|describe)\.only\(")),
    ("S8", "skip/fixme left in", re.compile(r"\btest\.(?:skip|fixme)\(")),
]
GOOD_LOCATORS = re.compile(r"getBy(Role|Label|Text|Placeholder|TestId|AltText|Title)\(")


def scan_script(text):
    findings = []
    for i, line in enumerate(text.splitlines(), 1):
        s = line.strip()
        if s.startswith("//") and "xpath" not in s:
            continue
        for rule, desc, rx in SCAN_RULES:
            if rx.search(line):
                findings.append((rule, desc, i, s[:120]))
    return findings, len(GOOD_LOCATORS.findall(text))


def scan_config(root):
    cfgs = [f for f in walk_files(os.path.join(root, "automation"), (".ts", ".js", ".mjs", ".cjs"))
            if re.search(r"playwright\.config\.", os.path.basename(f))]
    out = []
    for c in cfgs:
        t = open(c, encoding="utf-8", errors="replace").read()
        out.append({"rel": rel(c, root),
                    "trace": re.search(r"trace\s*:\s*['\"]([^'\"]+)", t),
                    "screenshot": re.search(r"screenshot\s*:\s*['\"]([^'\"]+)", t),
                    "retries": re.search(r"retries\s*:\s*([^,\n}/]+)", t),
                    "reporter": "json" in t or "junit" in t})
    return out


def _retries_note(m):
    """Team decision 1: Playwright retries must be 0 (the graph owns the single retry)."""
    if not m:
        return "not set (Playwright default 0; OK)"
    v = m.group(1).strip()
    if v == "0":
        return "0 (OK: graph owns the retry)"
    return f"{v} (FLAG: team decision is retries=0, the graph owns the single retry)"


# ---------------------------------------------------------------- main
def pct(a, b):
    return f"{a / b * 100:.1f}% ({a}/{b})" if b else NA


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    here = os.path.dirname(os.path.abspath(__file__))
    ap.add_argument("--root", default=os.path.dirname(here), help="project root (default: parent of qa/)")
    ap.add_argument("--results", action="append", help=f"result file(s) (Playwright JSON or JUnit); default: {DEFAULT_RESULTS}")
    ap.add_argument("--discover", action="store_true", help="instead of the default path, search automation/ and reports/ for result files (newest used)")
    ap.add_argument("--all-runs", action="store_true", help="with --discover: aggregate all result files instead of only the newest")
    ap.add_argument("--include-p2", action="store_true", help="put P2 cases in scope for the coverage criterion (default: P1 only)")
    ap.add_argument("--held-results", default=None, help="held-suite results (default automation/results/held/results.held.pwjson); mock-only, synthetic data, never gating")
    ap.add_argument("--tolerant-results", default=None, help="tolerant-suite results (default automation/results/tolerant/results.tolerant.pwjson); Tolerant section only")
    ap.add_argument("--event-due", action="store_true", help="event-driven cases (schedule: event-driven) are due this cycle: in scope whatever their tier (tests/README.md)")
    ap.add_argument("--rerun", action="append", default=[], help="explicit rerun result file(s); a fail that passes here is reported as flaky-on-rerun")
    ap.add_argument("--id-regex", default=DEFAULT_ID_RE, help="regex for case IDs in scripts/results")
    ap.add_argument("--module", default=DEFAULT_MODULE, help="module pack to audit by case-ID prefix/folder (P2P, O2C, R2R, ...) or 'all' (default: P2P)")
    ap.add_argument("--out", default=None, help="report path for a single module (default: qa/audit-report.md for P2P, qa/audit-report-<module>.md otherwise)")
    a = ap.parse_args()
    root = os.path.abspath(a.root)
    id_re = re.compile(a.id_regex)
    now = datetime.datetime.now().astimezone().strftime("%Y-%m-%d %H:%M %Z (UTC%z)")

    def default_out(m):
        return os.path.join(root, "qa", "audit-report.md" if m == "P2P" else f"audit-report-{m.lower()}.md")

    if _want(a.module):
        m = _want(a.module)
        audit_module(a, root, m, a.out or default_out(m), id_re, now)
        return 0
    # --module all: every module seen in cases, one report each + an index with per-module sections
    w = []
    _, allc = _load_all_cases(root, w)
    mods = sorted({case_module(c) for c in allc}) or [DEFAULT_MODULE]
    sums = []
    for m in mods:
        print(f"== {m}")
        sums.append(audit_module(a, root, m, default_out(m), id_re, now))
    L = ["# QA Audit Report: all modules", "", f"Generated by `qa/audit.py --module all` at {now}. Mock-only; no Fusion pod used.", "",
         f"Coverage columns count in-scope cases (default P1). **Stand-in only** includes the 8 partly substituted P1 cases ruled stand-ins by the {DECIDED_STANDINS_NOTE}; "
         + ("\"(n tag pending)\" = applied by the audit until Automation's @stand-in tag reaches the results." if any(x.get('si_pending') for x in sums)
            else "all of them now carry the @stand-in tag in the results (no tag pending)."), "",
         f"| Module | Cases | Tiers | In scope | {'P1+P2' if a.include_p2 else 'P1'} fully covered | {'P1+P2' if a.include_p2 else 'P1'} stand-in only | In-scope w/o script | In-scope scripted not run | Pass/Fail/Flaky/Skip | Sign-off blockers | Report |",
         "|---|---|---|---|---|---|---|---|---|---|---|"]
    for x in sums:
        sio = f"{x['si_only']}" + (f" ({x['si_pending']} tag pending)" if x.get('si_pending') else "")
        L.append(f"| {x['module']} | {x['cases']} | {x['tiers']} | {x['in_scope']} | {x['fully']} | {sio} | {x['no_script']} | {x['not_run']} | {x['results']} | "
                 f"{'; '.join(x['blockers']) or 'none'} | `{rel(x['out'], root)}` |")
    L += ["", "### Lifecycle fields (tests/README.md)", "",
          "| Module | Retired | Tolerant | Tolerant results P/F/Fl/S | Held | Held mock-only runs (non-gating) | Conditional | Event-driven | Data warnings |", "|---|---|---|---|---|---|---|---|---|"]
    for x in sums:
        L.append(f"| {x['module']} | {x['retired']} | {x['tolerant']} | {x['tol_results']} | {x['held']} | {x['held_ran']} | {x['conditional']} | {x['event_driven']} | {len(x['lc_warn'])} |")
    L.append(f"| **Total** | {sum(x['retired'] for x in sums)} | {sum(x['tolerant'] for x in sums)} | | {sum(x['held'] for x in sums)} | {sum(int(str(x['held_ran']).split()[0]) for x in sums if str(x['held_ran'])[:1].isdigit())} | "
             f"{sum(x['conditional'] for x in sums)} | {sum(x['event_driven'] for x in sums)} | {sum(len(x['lc_warn']) for x in sums)} |")
    L.append("")
    for x in sums:
        L += [f"## {x['module']}", "", f"Scope {x['scope']}. Details: `{rel(x['out'], root)}`.", ""]
        L += [f"- {b}" for b in x["blockers"]] or ["- No structural blockers."]
        L.append("")
    out = os.path.join(root, "qa", "audit-report-all.md")
    open(out, "w", encoding="utf-8").write("\n".join(L))
    print(f"index written: {out}")
    return 0


def audit_module(a, root, module, out_path, id_re, now):
    warn = []
    case_files, cases = load_cases(root, warn, module)
    case_ids = [c["id"] for c in cases]
    dup = sorted({i for i in case_ids if case_ids.count(i) > 1})
    known = set(case_ids)
    scripts = load_scripts(root, known, id_re, module)
    runs = find_results(root, a.results, a.discover)
    primary = runs if (a.all_runs or a.results or not a.discover) else ([max(runs, key=lambda r: r["mtime"])] if runs else [])
    rerun_runs = find_results(root, a.rerun) if a.rerun else []
    tests = [dict(t, _src=r["path"]) for r in primary for t in r["tests"]]
    for t in tests:
        t["ids"] = case_ids_from_tags(t.get("spec_tags", t["tags"]), id_re)
    n_tests_all = len(tests)
    tests = [t for t in tests if in_module(t["ids"], module)]  # other modules' results are not this pack's

    # mappings
    case_to_scripts = {c: [s["rel"] for s in scripts if c in s["ids"]] for c in known}
    no_script = sorted(c for c, v in case_to_scripts.items() if not v)
    orphan_scripts = [s for s in scripts if not (s["ids"] & known)]

    EXEC = ("pass", "fail", "flaky")
    def script_ran(s):
        """Ran = at least one EXECUTED result (pass/fail/flaky). A skipped/fixme-only script did NOT run."""
        base = os.path.basename(s["path"])
        return any(t["file"] and (os.path.basename(t["file"]) == base or s["rel"].endswith(t["file"]))
                   and t["status"] in EXEC for t in tests)
    scripts_not_run = [s for s in scripts if not script_ran(s)] if primary else scripts

    order = {"fail": 4, "flaky": 3, "pass": 2, "skipped": 1, "unknown": 0}
    case_status = {}
    for t in tests:
        for i in t["ids"] & known:
            if order[t["status"]] > order.get(case_status.get(i), -1):
                case_status[i] = t["status"]
    cnt = {k: sum(1 for t in tests if t["status"] == k) for k in order}
    _tol_ids = {c for c in known if case_class(next(x for x in cases if x["id"] == c)) == "tolerant"}
    # tolerant entries that leaked into the gate results: still in main totals (C5 parity), excluded from gating line
    tol_in_main = [t for t in tests if (t["ids"] & known) and (t["ids"] & known) <= _tol_ids]
    gate_cnt = {k: cnt[k] - sum(1 for t in tol_in_main if t["status"] == k) for k in order}
    # QA decision: the tolerant run (separate file) feeds ONLY the Tolerant suite section; never totals, never gating
    tol_path = getattr(a, "tolerant_results", None) or os.path.join(root, "automation", "results", "tolerant", "results.tolerant.pwjson")
    tol_run = parse_playwright_json(tol_path) if os.path.isfile(tol_path) else None
    tol_tests = []
    if tol_run:
        for t in tol_run["tests"]:
            t["ids"] = case_ids_from_tags(t.get("spec_tags", t["tags"]), id_re)
            if in_module(t["ids"], module) and t["ids"]:
                tol_tests.append(t)
    tol_cnt = {k: sum(1 for t in tol_tests if t["status"] == k) for k in order}
    tol_status = {}
    for t in tol_tests:
        for i in t["ids"]:
            if order[t["status"]] > order.get(tol_status.get(i), -1):
                tol_status[i] = t["status"]
    tol_unknown = sorted({i for t in tol_tests for i in t["ids"]} - _tol_ids)
    # held-suite results (separate file). Chief of Staff decision 9 Oct 2026 18:30 IST: the HCM/CX hold covers client
    # pods / real data only; mock runs with synthetic data are ALLOWED, recorded as mock-only, and never gate (no totals,
    # no coverage, module stays HELD) until masking is confirmed. Held cases in the GATE file are still flagged.
    held_path = getattr(a, "held_results", None) or os.path.join(root, "automation", "results", "held", "results.held.pwjson")
    held_run = parse_playwright_json(held_path) if os.path.isfile(held_path) else None
    held_tests = []
    if held_run:
        for t in held_run["tests"]:
            t["ids"] = case_ids_from_tags(t.get("spec_tags", t["tags"]), id_re)
            if t["ids"] and in_module(t["ids"], module):
                held_tests.append(t)
    held_cnt = {k: sum(1 for t in held_tests if t["status"] == k) for k in order}

    # explicit reruns: fail in main results, pass in a rerun -> flaky-on-rerun (reported separately so the
    # main counts stay comparable with reports/generate_report.py, which counts the results file only)
    rerun_flaky = []
    if rerun_runs:
        rr = [t for r in rerun_runs for t in r["tests"]]
        for t in tests:
            if t["status"] == "fail" and any(x["title"] == t["title"] and os.path.basename(x["file"] or "") == os.path.basename(t["file"] or "")
                                             and x["status"] in ("pass", "flaky") for x in rr):
                rerun_flaky.append(t)

    # tiered coverage (team decision 2)
    prio = {c["id"]: c.get("priority", "") for c in cases}
    scope = {c: scope_of(prio.get(c), a.include_p2) for c in known}
    # lifecycle fields (tests/README.md): retired / held / tolerant leave every scope (coverage, blockers, deferred
    # gaps); event-driven goes in scope whatever its tier only when --event-due says its event is in the next cycle;
    # conditional keeps its tier scope (client answers are never invented) and is listed separately.
    cmap = {c["id"]: c for c in cases}
    flags = {c: case_flags(cmap[c]) for c in known}
    cls = {c: case_class(cmap[c]) for c in known}
    event_due = bool(getattr(a, "event_due", False))
    for c in known:
        if cls[c]:
            scope[c] = cls[c]
        elif flags[c]["event_driven"] and event_due:
            scope[c] = "blocking"
    no_script = [c for c in no_script if cls[c] != "retired"]  # retired: "do not script or run"
    _, all_cases_x = _load_all_cases(root, [])
    all_by_id = {c["id"]: c for c in all_cases_x}
    lc_retired = sorted(c for c in known if cls[c] == "retired")
    lc_held = sorted(c for c in known if cls[c] == "held")
    lc_tol_flag = sorted(c for c in known if flags[c]["tolerant"])
    lc_tol = sorted(c for c in known if cls[c] == "tolerant")
    lc_cond = sorted(c for c in known if flags[c]["conditional"])
    lc_event = sorted(c for c in known if flags[c]["event_driven"])
    lc_warn = []
    for c in lc_retired:
        sb = cmap[c].get("superseded_by", "")
        if not sb:
            lc_warn.append(f"{c}: retired without superseded_by")
        elif sb not in all_by_id:
            lc_warn.append(f"{c}: successor {sb} not found in tests/cases")
        elif case_class(all_by_id[sb]) == "retired":
            lc_warn.append(f"{c}: successor {sb} is itself retired")
    for c in sorted(known):
        f_, x = flags[c], cmap[c]
        if (x.get("suite", "").lower() == "tolerant") != (x.get("go_no_go", "").lower() in ("false", "no", "0")):
            lc_warn.append(f"{c}: suite={x.get('suite') or '-'} but go_no_go={x.get('go_no_go') or '-'} (README: tolerant implies go_no_go false)")
        if f_["tolerant"] and not x.get("suite_reason"):
            lc_warn.append(f"{c}: tolerant without suite_reason")
        if f_["held"] and not x.get("execution_hold_reason"):
            lc_warn.append(f"{c}: execution_hold without execution_hold_reason")
    full_cov = {c for s_ in scripts for c in s_["full_ids"]}
    standin_cases = {c for s_ in scripts for c in s_["standin_ids"] if c in known and c not in full_cov}
    # result entries are authoritative when present (tags built at runtime, e.g. caseTags(), are invisible statically):
    # a case whose result entries are ALL stand-in is covered by substitute, whatever the static scan said.
    res_si, res_full = set(), set()
    for t in tests:
        (res_si if STANDIN_RE.search(" ".join([t["title"]] + list(t["tags"]))) else res_full).update(t["ids"] & known)
    for c in res_si - res_full:
        standin_cases.add(c)
        full_cov.discard(c)
    tagged_si = set(standin_cases)
    decided = sorted(c for c in DECIDED_STANDINS if c in known)
    decided_pending = [c for c in decided if c not in tagged_si]  # @stand-in tag not yet in results/scripts
    for c in decided:
        standin_cases.add(c)
        full_cov.discard(c)
    substitute = sorted(standin_cases)
    in_scope = {c for c in known if scope[c] == "blocking"}
    fully = sorted(c for c in in_scope if c in full_cov and c not in standin_cases)
    # generate_report.py C1: an unrun script blocks only if it maps to an in-scope case or to no known case
    blocking_scripts = [s_ for s_ in scripts if (s_["ids"] & in_scope) or not (s_["ids"] & known)]
    blk_scripts_not_run = [s_ for s_ in scripts_not_run if s_ in blocking_scripts] if primary else []
    other_scripts_not_run = [s_ for s_ in scripts_not_run if s_ not in blocking_scripts] if primary else []
    untiered = sorted(c for c in known if tier(prio.get(c)) is None)
    deferred = sorted(c for c in known if scope[c] == "deferred")
    def gaps_for(sc):
        ns = sorted(c for c in known if scope[c] == sc and not case_to_scripts[c])
        nr = sorted(c for c in known if scope[c] == sc and case_to_scripts[c] and case_status.get(c) not in ("pass", "fail", "flaky"))
        return ns, nr
    blk_ns, blk_nr = gaps_for("blocking")
    # fixme / skipped: scripted but not executed
    fixme_by_tier, skipped_cases = {}, {}
    for t in tests:
        if t["status"] == "skipped":
            for i in t["ids"] & known:
                skipped_cases[i] = "fixme" if t.get("fixme") else "skipped"
    for i, kind in skipped_cases.items():
        k = (tier(prio.get(i)) or "untiered", kind)
        fixme_by_tier[k] = fixme_by_tier.get(k, 0) + 1
    be_ns, be_nr = gaps_for("best_effort")
    by_tier = {}
    for c in known:
        by_tier[tier(prio.get(c)) or "untiered"] = by_tier.get(tier(prio.get(c)) or "untiered", 0) + 1
    executed = cnt["pass"] + cnt["fail"] + cnt["flaky"]
    unmapped_tests = [t for t in tests if not (t["ids"] & known)]
    cases_with_script_not_run = sorted(c for c in known if case_to_scripts[c] and c not in case_status)

    tri_files, tri = load_triage(root, {r["path"] for r in runs})
    tri_cls = [triage_class(r) for r in tri]
    n_def = sum(1 for c, _ in tri_cls if c == "defect")
    n_non = sum(1 for c, _ in tri_cls if c == "non_defect")
    mix = {}
    for _, raw in tri_cls:
        mix[raw] = mix.get(raw, 0) + 1

    rep = find_gonogo(root, module)
    rep_counts, mock_note, fusion_claim = extract_report_counts(rep) if rep else ({}, False, False)
    audit_vals = {"pass": cnt["pass"], "fail": cnt["fail"], "flaky": cnt["flaky"], "skipped": cnt["skipped"],
                  "total": len(tests), "executed": executed, "cases": len(known), "scripts": len(scripts)}

    # ---------------- write report
    L = []
    P = L.append
    P(f"# QA Audit Report: {module} pack")
    P("")
    P(f"Generated by `qa/audit.py --module {module}` at {now}. Root: `{root}`. Case-ID parser: {IDS_SOURCE}.")
    P("")
    P("> **Mock-only.** Any results below come from the local mock P2P app, not Oracle Fusion. No Fusion pod was used.")
    P("")
    P("## 1. Inputs found")
    P("")
    P("| Input | Status |")
    P("|---|---|")
    P(f"| Coverage map `analysis/p2p-coverage-map.md` | {'present' if os.path.isfile(os.path.join(root, 'analysis', 'p2p-coverage-map.md')) else NA} |")
    P(f"| Test cases `tests/cases/**/*.yaml` for {module} | {f'{len(case_files)} file(s), {len(cases)} case(s)' if case_files else NA} |")
    P(f"| Playwright scripts `automation/**/*.spec|test.*` | {f'{len(scripts)} file(s)' if scripts else NA} |")
    P(f"| Default results file `{DEFAULT_RESULTS}` | {'present' if os.path.isfile(os.path.join(root, DEFAULT_RESULTS)) else NA} |")
    P(f"| Run results parsed (Playwright JSON / JUnit) | {', '.join(f'`{rel(r['path'], root)}` ({r['format']}, {len(r['tests'])} tests)' for r in runs) if runs else NA} |")
    P(f"| Result entries in this module / in file | {f'{len(tests)} / {n_tests_all}' if primary else NA} |")
    P(f"| Results used for counts | {', '.join(f'`{rel(r['path'], root)}`' for r in primary) if primary else NA}{' (newest only; use --all-runs to aggregate)' if len(runs) > 1 and len(primary) == 1 else ''} |")
    P(f"| Triage output | {', '.join(f'`{rel(f, root)}`' for f in tri_files) + f' ({len(tri)} verdicts)' if tri_files else NA} |")
    P(f"| Go/no-go report in `reports/` | {f'`{rel(rep, root)}`' if rep else NA} |")
    P(f"| Tier mapping | {TIER_SOURCE} |")
    P(f"| PyYAML | {'available' if yaml else 'not installed, regex fallback used'} |")
    P("")
    P("## 2. Summary numbers")
    P("")
    P("| Metric | Value |")
    P("|---|---|")
    P(f"| Cases designed | {len(known) if case_files else NA} |")
    P(f"| Duplicate case IDs | {', '.join(dup) if dup else ('0' if case_files else NA)} |")
    P(f"| Cases by tier | {', '.join(f'{k}: {v}' for k, v in sorted(by_tier.items())) if case_files else NA} |")
    P(f"| Cases without a script (all tiers) | {len(no_script) if case_files and scripts else NA if not case_files else f'{len(no_script)} (no scripts exist)'} |")
    P(f"| In-scope tiers for coverage | {'P1 + P2 (--include-p2)' if a.include_p2 else 'P1 only (default; use --include-p2 for P1+P2)'} + untiered |")
    P(f"| In-scope cases | {len(in_scope) if case_files else NA} |")
    P(f"| Lifecycle (tests/README.md): retired / tolerant / held / conditional / event-driven | "
      f"{f'{len(lc_retired)} / {len(lc_tol_flag)} / {len(lc_held)} / {len(lc_cond)} / {len(lc_event)}' if case_files else NA} (out of scope: retired, held, tolerant; see §4a) |")
    P(f"| Fully covered in-scope cases, excluding stand-ins | {f'{len(fully)} of {len(in_scope)}' if case_files else NA} |")
    P(f"| In-scope cases covered by substitute (stand-in) only | {sum(1 for c in substitute if scope[c] == 'blocking') if case_files else NA} |")
    if case_files:
        _tiers = sorted({tier(prio.get(c)) or "untiered" for c in in_scope}, key=lambda x: (x == "untiered", x))
        _parts = []
        for _t in _tiers:
            _cs = [c for c in in_scope if (tier(prio.get(c)) or "untiered") == _t]
            _fp = sum(1 for c in _cs if c in fully and case_status.get(c) == "pass")
            _sp = sum(1 for c in _cs if c in standin_cases and case_status.get(c) == "pass")
            _nr = sum(1 for c in _cs if case_status.get(c) not in ("pass", "fail", "flaky"))
            _bad = sum(1 for c in _cs if case_status.get(c) in ("fail", "flaky"))
            _parts.append(f"{_t}: {len(_cs)} in scope = {_fp} full passed + {_sp} stand-in passed + {_nr} not run + {_bad} fail/flaky")
        P(f"| Per tier (in scope): full vs stand-in, passed | {'; '.join(_parts)} |")
    P(f"| **In-scope (blocking) without a script** | {len(blk_ns) if case_files else NA} |")
    P(f"| **In-scope (blocking) with script but not run (incl. skipped/fixme)** | {len(blk_nr) if case_files and primary else (NA if not case_files else f'{len(blk_nr)} (no results file)')} |")
    P(f"| P2 best effort, out of scope this run (no script / not run) | {f'{len(be_ns)} / {len(be_nr)}' if case_files else NA} |")
    P(f"| P3/P4 deferred (excluded from coverage gaps) | {len(deferred) if case_files else NA} |")
    P(f"| Untiered cases (treated as blocking) | {len(untiered) if case_files else NA} |")
    P(f"| Scripts (files) | {len(scripts) if scripts else NA} |")
    P(f"| Scripts without a matching case | {len(orphan_scripts) if scripts and case_files else NA} |")
    P(f"| Scripts not run (all) | {len(scripts_not_run) if scripts and primary else (NA if not scripts else f'{len(scripts)} (no results found)')} |")
    P(f"| **In-scope scripts not run (no executed result; skipped/fixme = not run; blocking)** | {f'{len(blk_scripts_not_run)} of {len(blocking_scripts)}' if scripts and primary else (NA if not scripts else f'{len(blocking_scripts)} of {len(blocking_scripts)} (no results found)')} |")
    P(f"| Out-of-scope scripts not run (gap, not blocking) | {len(other_scripts_not_run) if scripts and primary else NA} |")
    P(f"| Cases with script but no result | {len(cases_with_script_not_run) if primary and case_files else NA} |")
    for k, lab in (("pass", "Tests passed"), ("fail", "Tests failed"), ("flaky", "Tests flaky (passed on retry)"), ("skipped", "Tests skipped"), ("unknown", "Tests unknown status")):
        P(f"| {lab} | {cnt[k] if primary else NA} |")
    P(f"| Executed (pass+fail+flaky) | {executed if primary else NA} |")
    P(f"| Skipped/fixme cases by tier (scripted, NOT run) | {(', '.join(f'{t_} {k}: {n}' for (t_, k), n in sorted(fixme_by_tier.items())) or '0') if primary else NA} |")
    P(f"| Fails that passed on explicit rerun (--rerun) | {len(rerun_flaky) if rerun_runs else 'no rerun file given'} |")
    P(f"| Flaky rate (results file; graph retry merged in) | {pct(cnt['flaky'], executed) if primary else NA} |")
    if rerun_runs:
        P(f"| Flaky rate incl. explicit reruns | {pct(cnt['flaky'] + len(rerun_flaky), executed) if primary else NA} |")
    P(f"| Result entries not mapped to a case ID | {len(unmapped_tests) if primary else NA} |")
    P(f"| Triaged failures: defect / non-defect / unclassified | {f'{n_def} / {n_non} / {len(tri) - n_def - n_non}' if tri else NA} |")
    P(f"| False-fail rate (non-defect / classified) | {pct(n_non, n_def + n_non) if tri else NA} |")
    P(f"| Verdicts flagged needs_review (unconfirmed) | {sum(1 for r in tri if r.get('needs_review') is True) if tri else NA} |")
    P(f"| Failures in results vs verdicts in triage | {f'{cnt['fail'] + cnt['flaky']} vs {len(tri)}' if tri and primary else NA} |")
    P("")
    P("## 3. Go/no-go report count check")
    P("")
    P("The GO/NO-GO decision is made by `reports/generate_report.py` (criteria C1-C6, the single source of truth; "
      "see qa/test-strategy.md §5). This section only checks that the report's counts match the raw results.")
    P("")
    if not rep:
        P(f"Go/no-go report: {NA}. Nothing to compare yet.")
    else:
        P(f"Report: `{rel(rep, root)}`. Mentions mock: **{'yes' if mock_note else 'NO: must state mock-only'}**. "
          f"Possible claim of running on Fusion: **{'YES: check wording' if fusion_claim else 'none detected'}**.")
        P("")
        P("| Metric | Report says | Audit recomputed | Match |")
        P("|---|---|---|---|")
        mism = 0
        for k in ("cases", "scripts", "total", "executed", "pass", "fail", "flaky", "skipped"):
            rv = rep_counts.get(k)
            av = audit_vals[k] if (primary or k in ("cases", "scripts")) else None
            if rv is None:
                P(f"| {k} | not found | {av if av is not None else NA} | n/a |")
                continue
            uniq = sorted(set(rv))
            ok = av is not None and av in uniq and len(uniq) == 1
            if av is not None and not ok:
                mism += 1
            P(f"| {k} | {', '.join(map(str, uniq))} | {av if av is not None else NA} | {'yes' if ok else ('cannot check' if av is None else 'NO')} |")
        P("")
        P(f"Mismatches: **{mism}**. Count extraction is regex-based, so QA confirms by reading the report before sign-off.")
    P("")
    P("## 4. Case → script → result traceability")
    P("")
    if not case_files:
        P(f"Cases: {NA}.")
    else:
        P("| Case ID | Priority | Scope | Script(s) | Result |")
        P("|---|---|---|---|---|")
        for c in cases:
            scp = scope.get(c["id"], "blocking")
            sc = ", ".join(f"`{x}`" + (" (stand-in)" if c["id"] in substitute else "") for x in case_to_scripts.get(c["id"], [])) or (scp if scp in ("deferred", "retired", "held", "tolerant") else "**MISSING**" if scp == "blocking" else "missing (best effort)")
            res = case_status.get(c["id"], (scp if scp in ("deferred", "retired", "held") else "not run") if primary else NA)
            P(f"| {c['id']} | {c['priority'] or '-'} | {scp.replace('_', ' ')} | {sc} | {res} |")
    P("")
    if substitute:
        P("### Covered by substitute (stand-in script), not fully covered")
        P("")
        for c in substitute:
            src = [s_['rel'] for s_ in scripts if c in s_["standin_ids"]] or case_to_scripts.get(c, [])
            why = (f"; stand-in by {DECIDED_STANDINS_NOTE} ({DECIDED_STANDINS[c]})"
                   + ("; **@stand-in tag pending (Automation)**" if c in decided_pending else "; tag present")) if c in DECIDED_STANDINS else ""
            P(f"- {c} ({prio.get(c) or 'untiered'}): " + ", ".join(f"`{x}`" for x in src)
              + f"; result: {case_status.get(c, 'not run' if primary else NA)}{why}")
        P("")
    if deferred:
        P("### Deferred (P3/P4): excluded from coverage gaps")
        P("")
        P(", ".join(deferred))
        P("")
    if be_ns or be_nr:
        P("### P2 best-effort gaps (reported, not blocking for coverage)")
        P("")
        if be_ns: P("- No script: " + ", ".join(be_ns))
        if be_nr: P("- Script not run: " + ", ".join(be_nr))
        P("")
    if untiered:
        P("### Untiered cases (no P1-P4 priority; treated as blocking)")
        P("")
        P(", ".join(untiered))
        P("")
    if rerun_flaky:
        P("### Failed in results file, passed on explicit rerun (flaky-on-rerun)")
        P("")
        for t in rerun_flaky:
            P(f"- `{t['file']}` › {t['title']}")
        P("")
    if orphan_scripts:
        P("### Scripts with no matching case ID")
        P("")
        for s in orphan_scripts:
            P(f"- `{s['rel']}` (IDs seen: {', '.join(sorted(s['ids'])) or 'none'})")
        P("")
    if primary and skipped_cases:
        P("### Scripted but not run (skipped / fixme)")
        P("")
        P("| Case | Tier | Scope | Kind |")
        P("|---|---|---|---|")
        for i in sorted(skipped_cases):
            P(f"| {i} | {prio.get(i) or '-'} | {scope[i].replace('_', ' ')} | {skipped_cases[i]} |")
        P("")
    if primary and blk_scripts_not_run:
        P("### In-scope scripts not run: no executed result (blocking)")
        P("")
        for s in blk_scripts_not_run:
            P(f"- `{s['rel']}`")
        P("")
    if primary and other_scripts_not_run:
        P("### Out-of-scope scripts with no result entry (not blocking)")
        P("")
        for s in other_scripts_not_run:
            P(f"- `{s['rel']}`")
        P("")
    if unmapped_tests:
        P("### Result entries without a case ID")
        P("")
        for t in unmapped_tests[:50]:
            P(f"- `{t['file']}` › {t['title']} [{t['status']}]")
        P("")
    if mix:
        P("### Triage verdict mix")
        P("")
        for k, v in sorted(mix.items(), key=lambda x: -x[1]):
            P(f"- {k}: {v} ({classify(k)})")
        P("")
    P("## 4a. Lifecycle fields (tests/README.md)")
    P("")
    P("Retired, held and tolerant cases are outside every scope (no coverage gap, no blocker, not deferred). "
      "Precedence when a case has several: retired > held > tolerant. Conditional cases keep their tier scope "
      "(the client answer is never assumed). Event-driven cases follow their tier unless `--event-due` is given "
      f"(their event falls in the next patch cycle), which puts them in scope whatever their tier. `--event-due`: **{'on' if event_due else 'off'}**.")
    P("")
    if not case_files:
        P(f"Cases: {NA}.")
    else:
        P("| Field | Cases | Treatment |")
        P("|---|---|---|")
        P(f"| status: retired | {len(lc_retired)} | excluded from coverage and scope; listed with successor |")
        P(f"| suite: tolerant / go_no_go: false | {len(lc_tol_flag)} ({len(lc_tol_flag) - len(lc_tol)} also held) | excluded from go/no-go and coverage blockers; own pass/fail below |")
        P(f"| execution_hold | {len(lc_held)} | not run, not blocking; reported as held |")
        P(f"| condition | {len(lc_cond)} | tier scope unchanged; listed with condition |")
        P(f"| schedule: event-driven | {len(lc_event)} | tier scope; in scope whatever tier with --event-due |")
        P("")
        P("### Retired (do not script or run)")
        P("")
        if lc_retired:
            P("| Case | Tier | Superseded by | Successor status | Script / result | Reason |")
            P("|---|---|---|---|---|---|")
            for c in lc_retired:
                sb = cmap[c].get("superseded_by", "")
                st = ("MISSING (no superseded_by)" if not sb else "NOT FOUND" if sb not in all_by_id else
                      f"present ({case_module(all_by_id[sb])}, {all_by_id[sb].get('priority') or 'untiered'}"
                      + (", retired" if case_class(all_by_id[sb]) == "retired" else "") + ")")
                sr = (", ".join(case_to_scripts[c]) or "none") + " / " + case_status.get(c, "no result")
                P(f"| {c} | {prio.get(c) or '-'} | {sb or '-'} | {st} | {sr} | {cmap[c].get('retired_reason') or '-'} |")
        else:
            P("None.")
        P("")
        P("### Tolerant suite (separate pass/fail; not counted toward go/no-go)")
        P("")
        if lc_tol_flag:
            P(f"Tolerant run: `{rel(tol_path, root)}` " + ("(not found)" if not tol_run else
              f"— pass {tol_cnt['pass']}, fail {tol_cnt['fail']}, flaky {tol_cnt['flaky']}, skipped {tol_cnt['skipped']} "
              f"({len(tol_tests)} entries for this module). Tolerant cases with an executed result: "
              f"{sum(1 for c in lc_tol if tol_status.get(c) in EXEC)}/{len(lc_tol)}. Never in main totals, never gating."))
            if tol_unknown:
                P(f"- Data warning: tolerant run has entries for case(s) not marked tolerant: {', '.join(tol_unknown)}")
            if tol_in_main:
                P(f"- Data warning: {len(tol_in_main)} tolerant entr(y/ies) in the gate results file (kept in §2/§3 totals for parity, excluded from gating): "
                  + ", ".join(sorted({i for t in tol_in_main for i in t['ids']})))
            P("")
            P(f"Gating counts (gate results excluding tolerant entries): pass {gate_cnt['pass']}, fail {gate_cnt['fail']}, flaky {gate_cnt['flaky']}, skipped {gate_cnt['skipped']}.")
            P("")
            P("| Case | Tier | Also held | Script(s) | Result | Reason |")
            P("|---|---|---|---|---|---|")
            for c in lc_tol_flag:
                P(f"| {c} | {prio.get(c) or '-'} | {'yes' if cls[c] == 'held' else 'no'} | {', '.join(case_to_scripts[c]) or 'none'} | "
                  f"{tol_status.get(c, case_status.get(c, 'no result'))} | {cmap[c].get('suite_reason') or '-'} |")
        else:
            P("None.")
        P("")
        P("### Held (execution_hold): not run, not blocking")
        P("")
        if lc_held:
            reasons = {}
            for c in lc_held:
                reasons.setdefault((cmap[c].get("execution_hold"), cmap[c].get("execution_hold_reason") or "-"), []).append(c)
            for (h, r), ids in sorted(reasons.items()):
                tiers_ = {}
                for c in ids:
                    tiers_[tier(prio.get(c)) or "untiered"] = tiers_.get(tier(prio.get(c)) or "untiered", 0) + 1
                P(f"- **{h}** ({len(ids)} cases; {', '.join(f'{k} {v}' for k, v in sorted(tiers_.items()))}): {r}")
                P(f"  - {', '.join(ids)}")
            ran = [c for c in lc_held if c in case_status]
            P(f"- Held cases with an entry in the gate results (should be none): {', '.join(ran) if ran else '0'}")
            hran = sorted({i for t in held_tests for i in t["ids"]})
            P(f"- Held-suite run `{rel(held_path, root)}`: " + ("not found" if not held_run else
              f"{len(held_tests)} entr(y/ies) for this module: pass {held_cnt['pass']}, fail {held_cnt['fail']}, flaky {held_cnt['flaky']}, "
              f"skipped {held_cnt['skipped']}. **Mock-only, synthetic data (allowed; Chief of Staff 9 Oct 18:30 IST).** "
              "Not in totals, not gating, no sign-off; module stays HELD until masking is confirmed."))
            if hran:
                P(f"- Held cases with a mock-only run ({len(hran)}): " + ", ".join(hran)
                  + ". Results: " + ", ".join(f"{i} {next(t['status'] for t in held_tests if i in t['ids'])}" for i in hran) + ".")
        else:
            P("None.")
        P("")
        P("### Conditional (condition field): listed separately, tier scope unchanged")
        P("")
        if lc_cond:
            P("| Case | Tier | Scope | Condition | Result |")
            P("|---|---|---|---|---|")
            for c in lc_cond:
                P(f"| {c} | {prio.get(c) or '-'} | {scope[c].replace('_', ' ')} | {cmap[c].get('condition')} | {case_status.get(c, 'no result') if primary else NA} |")
        else:
            P("None.")
        P("")
        P("### Event-driven (schedule: event-driven)")
        P("")
        if lc_event:
            P("| Case | Tier | Scope | Result |")
            P("|---|---|---|---|")
            for c in lc_event:
                P(f"| {c} | {prio.get(c) or '-'} | {scope[c].replace('_', ' ')} | {case_status.get(c, 'no result') if primary else NA} |")
        else:
            P("None.")
        P("")
        P("Lifecycle data warnings: " + ("; ".join(lc_warn) if lc_warn else "none"))
    P("")
    P("## 5. Script stability scan (static)")
    P("")
    if not scripts:
        P(f"Scripts: {NA}. Nothing to scan.")
        P("")
    else:
        tot = {}
        P("| Script | getBy* locators | Findings |")
        P("|---|---|---|")
        details = []
        for s in scripts:
            f, good = scan_script(s["text"])
            for r, d, _, _ in f:
                tot[(r, d)] = tot.get((r, d), 0) + 1
            P(f"| `{s['rel']}` | {good} | {len(f)} |")
            details += [f"- `{s['rel']}:{ln}` [{r}] {d}: `{src}`" for r, d, ln, src in f]
        P("")
        P("Totals by rule: " + ("; ".join(f"{r} {d}: {n}" for (r, d), n in sorted(tot.items())) or "none"))
        P("")
        if details:
            P("<details><summary>All findings</summary>")
            P("")
            L.extend(details[:500])
            P("")
            P("</details>")
        P("")
    cfgs = scan_config(root)
    P("Playwright config: " + (NA if not cfgs else "; ".join(
        f"`{c['rel']}` trace={c['trace'].group(1) if c['trace'] else 'NOT SET'}, screenshot={c['screenshot'].group(1) if c['screenshot'] else 'NOT SET'}, "
        f"retries={_retries_note(c['retries'])}, json/junit reporter={'yes' if c['reporter'] else 'NO'}" for c in cfgs)))
    P("")
    P("## 6. Sign-off status")
    P("")
    blockers = []
    if not case_files: blockers.append("no test cases")
    if not scripts: blockers.append("no Playwright scripts")
    if not primary: blockers.append("no run results")
    elif not tests: blockers.append(f"results file has no {module} result entries")
    if not rep: blockers.append("no go/no-go report")
    if case_files and blk_ns: blockers.append(f"{len(blk_ns)} in-scope case(s) without a script")
    if primary and blk_scripts_not_run: blockers.append(f"{len(blk_scripts_not_run)} in-scope script(s) not run")
    if primary and case_files and blk_nr: blockers.append(f"{len(blk_nr)} in-scope case(s) scripted but not executed (skipped/fixme/no result): " + ", ".join(blk_nr[:15]))
    if not primary and blocking_scripts: blockers.append(f"{len(blocking_scripts)} in-scope script(s) with no results")
    if primary and case_files:
        p1_not_pass = sorted(c for c in known if tier(prio.get(c)) == "P1" and scope[c] == "blocking" and case_status.get(c) not in (None, "pass", "deferred", "skipped"))  # skipped = not run (blocker above)
        if p1_not_pass: blockers.append(f"{len(p1_not_pass)} P1 case(s) ran but did not pass on first attempt: " + ", ".join(p1_not_pass[:15]))
    if primary and cnt["fail"] and not tri: blockers.append("failures present but no triage output")
    if primary and tri and cnt["fail"] > len(tri): blockers.append(f"{cnt['fail'] - len(tri)} failure(s) without a triage verdict")
    all_held = bool(case_files) and all(cls[c] in ("held", "retired") for c in known) and bool(lc_held)
    if all_held:  # whole pack on execution_hold: nothing may run, so missing scripts/results are not coverage blockers
        hold_names = sorted({cmap[c].get("execution_hold") for c in lc_held})
        blockers = [b for b in blockers if b == "no go/no-go report" or b.startswith("failures") or "failure(s)" in b]
        blockers.insert(0, f"HELD: all {len(lc_held)} case(s) on execution_hold ({', '.join(hold_names)}); no gating run and no sign-off until the hold is lifted (mock-only synthetic runs allowed, non-gating)")
    P("**QA sign-off: NOT GIVEN.** Blockers: " + "; ".join(blockers) + "." if blockers else
      "**No structural blockers found.** QA still reviews section 3 and the P1 results manually before signing.")
    if warn:
        P("")
        P("Warnings: " + "; ".join(warn))
    P("")
    os.makedirs(os.path.dirname(out_path), exist_ok=True)
    open(out_path, "w", encoding="utf-8").write("\n".join(L))

    # stdout summary
    print(f"audit written ({module}): {out_path}")
    print(f"tiers: {', '.join(f'{k}={v}' for k, v in sorted(by_tier.items())) if case_files else NA} | "
          f"scope: {'P1+P2' if a.include_p2 else 'P1'} | in-scope: {len(in_scope) if case_files else NA} | fully covered excl. stand-ins: {len(fully) if case_files else NA} | in-scope w/o script: {len(blk_ns) if case_files else NA} | in-scope scripted not run: {len(blk_nr) if case_files and primary else NA} | "
          f"covered-by-substitute: {len(substitute) if case_files else NA} | "
          f"P2 gaps: {len(be_ns) + len(be_nr) if case_files else NA} | deferred P3/P4: {len(deferred) if case_files else NA}")
    print(f"cases: {len(known) if case_files else NA} | scripts: {len(scripts) if scripts else NA} | "
          f"cases w/o script: {len(no_script) if case_files and scripts else NA} | orphan scripts: {len(orphan_scripts) if scripts and case_files else NA} | "
          f"in-scope scripts not run: {f'{len(blk_scripts_not_run)}/{len(blocking_scripts)}' if scripts and primary else NA} | "
          f"out-of-scope scripts not run: {len(other_scripts_not_run) if scripts and primary else NA}")
    print(f"results: {'pass %d fail %d flaky %d skipped %d' % (cnt['pass'], cnt['fail'], cnt['flaky'], cnt['skipped']) if primary else NA} | "
          f"false-fail rate: {pct(n_non, n_def + n_non) if tri else NA} | go/no-go report: {rel(rep, root) if rep else NA}")
    print(f"lifecycle: retired {len(lc_retired)} | tolerant {len(lc_tol_flag)} (results p/f/fl/s {tol_cnt['pass']}/{tol_cnt['fail']}/{tol_cnt['flaky']}/{tol_cnt['skipped']}) | "
          f"held {len(lc_held)} | conditional {len(lc_cond)} | event-driven {len(lc_event)} (--event-due {'on' if event_due else 'off'})"
          + (" | warnings: " + "; ".join(lc_warn) if lc_warn else ""))
    print("sign-off: " + ("NOT GIVEN; blockers: " + "; ".join(blockers) if blockers else "no structural blockers"))
    return {"module": module, "out": out_path, "cases": len(known) if case_files else NA,
            "tiers": ", ".join(f"{k}={v}" for k, v in sorted(by_tier.items())) if case_files else NA,
            "scope": "P1+P2" if a.include_p2 else "P1", "in_scope": len(in_scope) if case_files else NA,
            "fully": f"{len(fully)}/{len(in_scope)}" if case_files else NA,
            "si_only": f"{sum(1 for c in substitute if scope[c] == 'blocking')}/{len(in_scope)}" if case_files else NA,
            "si_pending": sum(1 for c in decided_pending if scope[c] == "blocking"), "no_script": len(blk_ns) if case_files else NA,
            "not_run": len(blk_nr) if case_files and primary else NA,
            "results": f"{cnt['pass']}/{cnt['fail']}/{cnt['flaky']}/{cnt['skipped']}" if primary else NA, "blockers": blockers,
            "retired": len(lc_retired), "tolerant": len(lc_tol_flag), "held": len(lc_held), "conditional": len(lc_cond),
            "event_driven": len(lc_event), "lc_warn": lc_warn,
            "held_ran": f"{len({i for t in held_tests for i in t['ids']})} ({held_cnt['pass']}/{held_cnt['fail']}/{held_cnt['flaky']}/{held_cnt['skipped']})" if held_run else NA,
            "tol_results": f"{tol_cnt['pass']}/{tol_cnt['fail']}/{tol_cnt['flaky']}/{tol_cnt['skipped']}" if tol_run else NA}


if __name__ == "__main__":
    sys.exit(main())