File size: 62,949 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
#!/usr/bin/env python3
"""Go/no-go report generator (Markdown + HTML) from triage output.

Usage:
    python3 reports/generate_report.py --results automation/results/results.json   # runs triage first
    python3 reports/generate_report.py --triage reports/triage.json

The decision uses ONE rule: QA's exit criteria, qa/test-strategy.md section 5 ("Go/No-Go sign-off by QA"),
with the definitions in section 6. GO only if ALL of these hold:
  C1 Coverage (tiered, QA patch qa/proposed-generate_report-C1-tiered.patch): every in-scope case has a script and
     every in-scope script was run. In scope = P1 + untiered by default, P1 + P2 + untiered with --include-p2.
     P3/P4 (and P2 by default) are listed as gaps and never block. Stand-in scripts satisfy C1 (QA section 2a).
  C2 Every P1 case passed (first attempt; flaky is not a pass). Every P2 failure has a triage verdict.
     A P2 failure classified real defect (any confidence) blocks unless reports/human-review.json waives it
     or reclassifies it as not_defect (Chief of Staff decision, 9 Oct 2026).
  C3 Flaky rate <= 5% of executed tests, and every flaky test has an owner.
  C4 False-fail rate is reported with its denominator.
  C5 Report counts match the counts qa/audit.py recomputes from the raw result file.
  C6 Report states "mock app, not Oracle Fusion" and lists the open gaps.
Lifecycle fields (tests/README.md, qa/test-strategy.md section 2b) via qa/audit.py case_flags/case_class/scope_of:
  retired/held/tolerant cases are outside every scope (never gate C1/C2; excluded from C3 and the C2 P2-defect check),
  --event-due puts event-driven cases in scope, and a module whose cases are all held gets the decision HELD.
Case IDs of result entries come from @<CASE-ID> tags only (never titles or annotation text).
Exit codes: 0 GO, 1 any NO-GO, 3 HELD (no NO-GO, some module held); run_triage.py adds 2 = WAITING.
Case/script/run mapping and count recomputation reuse qa/audit.py's own functions, so this
report and QA's audit agree by construction. Deterministic; no LLM.

Human input (optional) for "confirmed", "waiver" and "owner": reports/human-review.json
    {"<case id or full test title>": {"confirmed": "real_defect" | "not_defect", "waiver": "...", "owner": "..."}}
"""
from __future__ import annotations

import datetime as _dt
import hashlib
import html
import importlib.util
import json
import os
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "triage"))
import classifier as clf  # noqa: E402
import ids as case_ids  # noqa: E402  (shared case-ID / tag / stand-in parsing)
from risk import tier, is_high_risk  # noqa: E402,F401  (single shared tier mapping)

RULE_SOURCE = "qa/test-strategy.md section 5 (exit criteria) + section 6 (definitions)"
FLAKY_MAX = 0.05  # QA C3
MOCK_NOTE = (
    "**Results come from Playwright runs against the LOCAL MOCK app (mock-app/), NOT Oracle Fusion.** "
    "No Oracle Fusion pod, credentials or client data were used. This report validates the test pack and the "
    "triage pipeline only; it is not a sign-off for any Fusion patch."
)
NON_DEFECT = ("ui_change", "data", "timing", "environment")   # causes on the testing side or the pod, never a product defect


def target_words(tri: dict) -> dict:
    """Where the results come from, stated on every report (C6). A run on a registered Oracle Fusion test pod says so and
    names the pod; everything else is the local mock and keeps MOCK_NOTE word for word."""
    if str(tri.get("run_mode", "")).startswith("live (Oracle Fusion"):
        pod = tri.get("target") or "an Oracle Fusion test pod"
        return {"note": f"**Results come from Playwright runs against {pod}, a non-production Oracle Fusion pod, with test "
                        f"data only.** A consultant approved the scenarios, judges any failures and signs off this report.",
                "run": "Fusion run", "against": "run against the Oracle Fusion test pod", "tag": "Fusion"}
    return {"note": MOCK_NOTE, "run": "mock run", "against": "run against mock", "tag": "mock"}
UNASSIGNED_NOTE = (
    "Tests that carry no case-ID tag with a module prefix (@<MODULE>-<AREA>-<NUMBER>; case IDs are read from tags only, "
    "never from titles or annotation text) cannot be assigned to a module. Following qa/audit.py (in_module), they are kept and COUNTED in every module's report, "
    "and listed here so they are never silently dropped. Give them a case ID to assign them."
)
STANDIN_NOTE = (
    "Stand-in tests (tag `@stand-in`, `@standin`, `@substitute`, or 'stand-in' in the title) exercise a substitute path "
    "(e.g. a REST import instead of the spreadsheet UI). Per qa/test-strategy.md section 2a they satisfy C1 coverage, but they are "
    "NOT real coverage: the real UI path stays untested. Their results ARE included in the Total/Executed/Passed/Failed/Flaky/Skipped "
    "counts above (they are real Playwright runs against the mock, and qa/audit.py counts them too, see C5), and C2 applies to them as to any test. "
    "They are EXCLUDED from the 'fully covered' figure below."
)


def load_qa_audit(root: Path):
    p = root / "qa" / "audit.py"
    if not p.is_file():
        return None
    spec = importlib.util.spec_from_file_location("qa_audit", p)
    mod = importlib.util.module_from_spec(spec)
    try:
        spec.loader.exec_module(mod)
    except Exception:
        return None
    return mod


def _now_ist() -> str:
    return _dt.datetime.now(_dt.timezone(_dt.timedelta(hours=5, minutes=30))).strftime("%Y-%m-%d %H:%M IST")


def _sha256(path: str) -> str:
    try:
        return hashlib.sha256(Path(path).read_bytes()).hexdigest()[:16]
    except OSError:
        return "n/a"


def _rel(p: str, base: Path = ROOT) -> str:
    try:
        return os.path.relpath(p, base).replace(os.sep, "/")
    except ValueError:
        return p


# Canonical count keys (QA vocabulary, qa/test-strategy.md section 6). summarize() returns exactly these in
# s["counts"]; every caller (this CLI, triage/run_triage.py, tests) must format counts via counts_line().
COUNT_KEYS = ("total", "executed", "pass", "fail", "flaky", "skipped")


def counts_line(s: dict) -> str:
    c = s["counts"]
    return " ".join(f"{k}={c[k]}" for k in COUNT_KEYS)


def _status(outcome: str) -> str:  # QA vocabulary
    return {"passed": "pass", "failed": "fail", "flaky": "flaky", "skipped": "skipped"}[outcome]


def _owner(r: dict, review: dict) -> str | None:
    for k in (r.get("case_id"), r["full_title"]):
        if k and review.get(k, {}).get("owner"):
            return review[k]["owner"]
    return r.get("owner")


def _review_for(r: dict, review: dict) -> dict:
    for k in (r.get("case_id"), r["full_title"]):
        if k and k in review:
            return review[k]
    return {}


DEFAULT_MODULE = "P2P"
# Exit codes shared by this CLI and triage/run_triage.py.
EXIT_GO, EXIT_NO_GO, EXIT_WAITING, EXIT_HELD = 0, 1, 2, 3
HELD_NOTE = ("HELD: every case of this module is on execution_hold (tests/README.md), so nothing may run and no sign-off is "
             "possible until the hold is lifted. This is not a GO and not a NO-GO; C1-C6 below are shown for information only.")
LIFECYCLE_NOTE = ("Lifecycle fields (tests/README.md, qa/test-strategy.md section 2b), read with qa/audit.py's case_flags/case_class; "
                  "precedence retired > held > tolerant. Retired, held and tolerant cases are outside every scope: they never "
                  "gate C1/C2, and their result entries are excluded from C3 (flaky) and the C2 P2-defect check. The totals in "
                  "Counts still include their result entries (as qa/audit.py counts them, C5); the gating subset excludes them.")


def exit_code(decisions) -> int:
    """0 = every module GO; 1 = any NO-GO; 3 = no NO-GO but at least one module HELD (2 = WAITING, no results)."""
    d = list(decisions)
    if any(x == "NO-GO" for x in d):
        return EXIT_NO_GO
    if any(x == "HELD" for x in d):
        return EXIT_HELD
    return EXIT_GO


def want_module(module) -> str | None:
    """Same convention as qa/audit.py _want(): None/''/'all' = every module, else upper-case module code."""
    return None if module in (None, "", "all", "ALL") else str(module).upper()


def record_ids(r: dict, qa=None) -> list[str]:
    """Case IDs of a result record: ONLY its case-ID tags, via qa/audit.py's own case_ids_from_tags() on the
    spec-level tags (exactly what the audit reads), so the report and the audit cannot drift. Never titles, file
    names, fixme/skip reasons or annotation text (DR-O2C-INT-003 in a fixme reason created a fake 'DR' module).
    Without qa/audit.py: triage/ids.py tag_case_id(), which the audit documents as the same rule."""
    tags = r.get("spec_tags") if r.get("spec_tags") is not None else (r.get("tags") or [])
    if qa is not None and hasattr(qa, "case_ids_from_tags"):
        return sorted(qa.case_ids_from_tags(tags, case_ids.CASE_ID_RE))
    return sorted({i for i in (case_ids.tag_case_id(t) for t in tags) if i})


def _qa_tests(qa, path, module):
    """Entries of a Playwright JSON file for `module`, parsed and ID-tagged exactly like qa/audit.py audit_module():
    qa.parse_playwright_json + qa.case_ids_from_tags(spec_tags) + qa.in_module. None if the file is absent/unparsable."""
    if not qa or not path or not Path(str(path)).is_file():
        return None
    parsed = qa.parse_playwright_json(str(path))
    if not parsed:
        return None
    out = []
    for t in parsed["tests"]:
        t = dict(t, ids=qa.case_ids_from_tags(t.get("spec_tags", t["tags"]), case_ids.CASE_ID_RE))
        if qa.in_module(t["ids"], module):
            out.append(t)
    return out


def side_results_path(root: Path, kind: str) -> Path:
    """Separate suites qa/audit.py reads: automation/results/<kind>/results.<kind>.pwjson (kind = tolerant | held)."""
    return Path(root) / "automation" / "results" / kind / f"results.{kind}.pwjson"


def module_view(tri: dict, root: Path = ROOT, module=DEFAULT_MODULE) -> dict:
    """Restrict a triage dict to one module, with qa/audit.py's rule (qa.in_module): keep a test if any of its
    case-ID TAGS has that module, or if it carries no module ID at all. ID-less tests are therefore kept (and counted)
    in EVERY module's report, as qa/audit.py does, and are flagged 'unassigned' so they are listed, never dropped."""
    want = want_module(module)
    if tri.get("module", "unset") == want:
        return tri
    qa = load_qa_audit(root)
    recs = []
    for r in tri["records"]:
        ids = set(record_ids(r, qa))
        mods = {case_ids.module_of(x) for x in ids} - {None}
        keep = (qa.in_module(ids, want) if qa else (want is None or not mods or want in mods))
        if keep:
            recs.append(dict(r, module_ids=sorted(ids), modules=sorted(mods), unassigned=not mods))
    return dict(tri, records=recs, module=want)


def modules_in(tri: dict, root: Path = ROOT) -> list[str]:
    """Modules present in designed cases (qa.case_module) or in result case-ID tags. ID-less tests add no module."""
    qa = load_qa_audit(root)
    mods = set()
    if qa:
        _, allc = qa.load_cases(str(root), [], None)
        mods |= {qa.case_module(c) for c in allc}
    for r in module_view(tri, root, None)["records"]:
        mods |= set(r["modules"])
    return sorted(mods) or [DEFAULT_MODULE]


def _lifecycle(qa, cases, root: Path):
    """Lifecycle classes from tests/README.md fields, via qa/audit.py's own helpers (case_flags / case_class):
    precedence retired > held > tolerant. Returns (cls, flags) keyed by case id."""
    cls, flags = {}, {}
    for c in cases:
        if qa and hasattr(qa, "case_class"):
            cls[c["id"]], flags[c["id"]] = qa.case_class(c), qa.case_flags(c)
        else:
            cls[c["id"]], flags[c["id"]] = None, {k: False for k in ("retired", "held", "tolerant", "conditional", "event_driven")}
    return cls, flags


def _lifecycle_warnings(qa, root: Path, cases, cls, flags) -> list[str]:
    """Same checks, same wording as qa/audit.py audit_module() (successor check over ALL modules' cases)."""
    if not qa:
        return []
    _, allc = qa._load_all_cases(str(root), [])
    all_by_id = {c["id"]: c for c in allc}
    cmap = {c["id"]: c for c in cases}
    w = []
    for c in sorted(i for i in cmap if cls[i] == "retired"):
        sb = cmap[c].get("superseded_by", "")
        if not sb:
            w.append(f"{c}: retired without superseded_by")
        elif sb not in all_by_id:
            w.append(f"{c}: successor {sb} not found in tests/cases")
        elif qa.case_class(all_by_id[sb]) == "retired":
            w.append(f"{c}: successor {sb} is itself retired")
    for c in sorted(cmap):
        x = cmap[c]
        if (x.get("suite", "").lower() == "tolerant") != (x.get("go_no_go", "").lower() in ("false", "no", "0")):
            w.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 flags[c]["tolerant"] and not x.get("suite_reason"):
            w.append(f"{c}: tolerant without suite_reason")
        if flags[c]["held"] and not x.get("execution_hold_reason"):
            w.append(f"{c}: execution_hold without execution_hold_reason")
    return w


def summarize(tri: dict, root: Path = ROOT, review: dict | None = None, include_p2: bool = False,
              module=DEFAULT_MODULE, event_due: bool = False) -> dict:
    review = review or {}
    qa = load_qa_audit(root)
    tri = module_view(tri, root, module)
    want = tri["module"]
    recs = tri["records"]
    for r in recs:
        r["qa_status"] = _status(r["outcome"])
    # Totals: every result entry of the module, INCLUDING tolerant/held/retired entries, exactly as qa/audit.py
    # counts them (C5 parity, qa/test-strategy.md section 2b). Gating counts below exclude non-gating entries.
    cnt = {k: sum(1 for r in recs if r["qa_status"] == k) for k in ("pass", "fail", "flaky", "skipped")}
    cnt["total"] = len(recs)
    cnt["executed"] = cnt["pass"] + cnt["fail"] + cnt["flaky"]

    crit, gaps = {}, []

    # ---- inputs via qa/audit.py
    cases, scripts, known, id_re = [], [], set(), None
    if qa:
        warn: list = []
        _, cases = qa.load_cases(str(root), warn, want)
        known = {c["id"] for c in cases}
        id_re = case_ids.CASE_ID_RE  # shared module-neutral pattern
        scripts = qa.load_scripts(str(root), known, id_re, want)
    cmap = {c["id"]: c for c in cases}
    prio = {c["id"]: c.get("priority") or "" for c in cases}
    cls, flags = _lifecycle(qa, cases, root)
    lc_warn = _lifecycle_warnings(qa, root, cases, cls, flags)

    # ---- scope, exactly as qa/audit.py: tier scope (qa.scope_of), then retired/held/tolerant leave every scope,
    # and with --event-due an event-driven case is in scope whatever its tier. Conditional keeps its tier scope.
    def _tier_scope(c):
        if qa and hasattr(qa, "scope_of"):
            return qa.scope_of(prio.get(c), include_p2)
        t = tier(prio.get(c))
        return "blocking" if t in (None, "P1") or (t == "P2" and include_p2) else ("best_effort" if t == "P2" else "deferred")
    scope = {c: _tier_scope(c) for c in known}
    for c in known:
        if cls[c]:
            scope[c] = cls[c]
        elif flags[c]["event_driven"] and event_due:
            scope[c] = "blocking"
    NONGATING = ("retired", "held", "tolerant")

    # ---- per-record case IDs: ONLY from the record's case-ID tags (triage/ids.py tag_case_id), never from titles or
    # annotation text. A record is non-gating when all its known case IDs are retired/held/tolerant.
    for r in recs:
        ids = set(r.get("module_ids") or []) & known
        r["case_ids"] = sorted(ids)
        nongating = bool(ids) and all(cls[i] in NONGATING for i in ids)
        r["lifecycle"] = next(k for k in NONGATING if any(cls[i] == k for i in ids)) if nongating else None  # retired > held > tolerant
        r["gating"] = r["lifecycle"] is None
        gid = [i for i in ids if cls[i] not in NONGATING] or list(ids)
        r["priority"] = ", ".join(sorted({prio[i] for i in ids if prio.get(i)})) or None
        r["tier"] = min((tier(prio.get(i)) for i in gid if tier(prio.get(i))), default=None)
    gating = [r for r in recs if r["gating"]]
    gcnt = {k: sum(1 for r in gating if r["qa_status"] == k) for k in ("pass", "fail", "flaky", "skipped")}
    gcnt["total"] = len(gating)
    gcnt["executed"] = gcnt["pass"] + gcnt["fail"] + gcnt["flaky"]
    by_class: dict[str, int] = {}
    for r in gating:
        if r["outcome"] == "failed":
            c = (r.get("classification") or {}).get("category", "unclassified")
            by_class[c] = by_class.get(c, 0) + 1
    order = {"fail": 4, "flaky": 3, "pass": 2, "skipped": 1}
    case_status: dict[str, str] = {}
    for r in recs:
        for i in r["case_ids"]:
            if order[r["qa_status"]] > order.get(case_status.get(i), 0):
                case_status[i] = r["qa_status"]

    # ---- lifecycle listing (own non-blocking sections)
    def _scripts_for(c):
        return [s_["rel"] for s_ in scripts if c in s_["ids"]]
    def _res(c):
        return case_status.get(c, "no result")
    lifecycle = {
        "retired": [{"case": c, "priority": prio.get(c) or "-", "superseded_by": cmap[c].get("superseded_by") or "-",
                     "reason": cmap[c].get("retired_reason") or "-", "scripts": _scripts_for(c), "result": _res(c)}
                    for c in sorted(known) if cls[c] == "retired"],
        "held": [{"case": c, "priority": prio.get(c) or "-", "hold": cmap[c].get("execution_hold") or "-",
                  "reason": cmap[c].get("execution_hold_reason") or "-", "result": _res(c)}
                 for c in sorted(known) if cls[c] == "held"],
        "tolerant": [{"case": c, "priority": prio.get(c) or "-", "also": cls[c] if cls[c] != "tolerant" else None,
                      "scripts": _scripts_for(c), "result": _res(c), "reason": cmap[c].get("suite_reason") or "-"}
                     for c in sorted(known) if flags[c]["tolerant"]],
        "conditional": [{"case": c, "priority": prio.get(c) or "-", "condition": cmap[c].get("condition") or "-",
                         "scope": scope[c], "result": _res(c)} for c in sorted(known) if flags[c]["conditional"]],
        "event_driven": [{"case": c, "priority": prio.get(c) or "-", "scope": scope[c], "result": _res(c)}
                         for c in sorted(known) if flags[c]["event_driven"]],
        "warnings": lc_warn, "event_due": event_due,
    }
    tol_recs = [r for r in recs if r["lifecycle"] == "tolerant"]
    lifecycle["tolerant_counts"] = {k: sum(1 for r in tol_recs if r["qa_status"] == k) for k in ("pass", "fail", "flaky", "skipped")}
    lifecycle["tolerant_in_main"] = sorted({i for r in tol_recs for i in r["case_ids"]})
    ST = ("pass", "fail", "flaky", "skipped")
    rank = {"fail": 4, "flaky": 3, "pass": 2, "skipped": 1, "unknown": 0}
    # ---- Tolerant suite: separate file, read exactly like qa/audit.py (parse_playwright_json + case_ids_from_tags +
    # in_module, entries with a case ID only). Shown in its own section; NEVER in totals, C1-C6 or verdicts.
    tol_path = side_results_path(root, "tolerant")
    tol_tests = [t for t in (_qa_tests(qa, tol_path, want) or []) if t["ids"]]
    tol_status: dict = {}
    for t in tol_tests:
        for i in t["ids"]:
            if rank.get(t["status"], 0) > rank.get(tol_status.get(i), -1):
                tol_status[i] = t["status"]
    tol_ids_cls = {c for c in known if cls[c] == "tolerant"}
    lifecycle["tolerant_suite"] = {
        "path": _rel(str(tol_path), root), "found": tol_path.is_file(), "entries": len(tol_tests),
        "counts": {k: sum(1 for t in tol_tests if t["status"] == k) for k in ST},
        "with_run": sum(1 for c in tol_ids_cls if tol_status.get(c) in ("pass", "fail", "flaky")), "n_tolerant": len(tol_ids_cls),
        "unknown": sorted({i for t in tol_tests for i in t["ids"]} - tol_ids_cls)}
    for x in lifecycle["tolerant"]:
        x["suite_result"] = tol_status.get(x["case"], "no run")
    # ---- Held cases with results (QA detection, qa/audit.py audit_module): (a) entries for held cases in the gate
    # results file; (b) any entry for this module in the held-suite file automation/results/held/results.held.pwjson.
    held_path = side_results_path(root, "held")
    held_tests = [t for t in (_qa_tests(qa, held_path, want) or []) if t["ids"]]
    gate_held = sorted(x["case"] for x in lifecycle["held"] if x["result"] != "no result")
    # (b) held-suite file: mock-only runs with synthetic data, ALLOWED (Chief of Staff, 9 Oct 2026 18:30 IST), as
    # qa/audit.py records them. Shown, never counted, module stays HELD. Not a breach.
    held_mock = None
    if held_tests:
        held_mock = {"file": _rel(str(held_path), root), "runs": len(held_tests),
                     "ids": sorted({i for t in held_tests for i in t["ids"]}),
                     "counts": {k: sum(1 for t in held_tests if t["status"] == k) for k in ST}}
    # (a) held cases in the main (gate) results file: a real HOLD BREACH (qa/audit.py: "should be none").
    hold_breach = None
    if gate_held:
        hold_breach = {"gate_file": _rel(str(tri.get("source", "")), root), "gate_ids": gate_held,
                       "gate_runs": sum(1 for r in recs if r["lifecycle"] == "held")}
    retired_with_result = [x["case"] for x in lifecycle["retired"] if x["result"] != "no result"]
    retired_with_script = [x["case"] for x in lifecycle["retired"] if x["scripts"]]
    held_with_result = [x["case"] for x in lifecycle["held"] if x["result"] != "no result"]
    if lc_warn:
        gaps.append(f"{len(lc_warn)} lifecycle data warning(s): " + "; ".join(lc_warn[:10]))
    if retired_with_script or retired_with_result:
        gaps.append("Retired case(s) still scripted or with a result entry (README: do not script or run): "
                    + ", ".join(sorted(set(retired_with_script) | set(retired_with_result))))
    if held_with_result:
        gaps.append("Held case(s) with a result entry (execution_hold says no run): " + ", ".join(held_with_result))

    # ---- C1 coverage: in-scope cases only. Retired/held/tolerant are never in scope; P3/P4 (and P2 by default) never block.
    in_scope = {c for c in known if scope[c] == "blocking"}
    deferred = sorted(c for c in known if scope[c] in ("deferred", "best_effort"))
    if deferred:
        gaps.append(f"{len(deferred)} case(s) out of tier scope this run ({'P3/P4' if include_p2 else 'P2/P3/P4'}), not counted in C1: " + ", ".join(deferred[:20]))
    if qa and hasattr(qa, "STANDIN_RE"):
        full = {c for s_ in scripts for c in s_.get("full_ids", s_["ids"])}
        sub = sorted(c for c in in_scope if c not in full and any(c in s_.get("standin_ids", ()) for s_ in scripts))
        if sub:
            gaps.append("Covered by substitute (stand-in script), not fully covered: " + ", ".join(sub))
    if not qa:
        crit["C1"] = (False, "qa/audit.py not available, coverage cannot be computed")
    elif not cases:
        crit["C1"] = (False, "No designed cases found in tests/cases/*.yaml")
    else:
        no_script = sorted(c for c in in_scope if not any(c in s["ids"] for s in scripts))
        # "Run" = has at least one EXECUTED result (pass/fail/flaky; QA section 6). Skipped/fixme is not run, except a scenario
        # the automation found not applicable to this pod's setup (a type the pod lacks, approval it does not use): it ran
        # as far as the pod allows and says why, so it is accounted for, and listed below
        executed = [r for r in recs if r["qa_status"] in ("pass", "fail", "flaky") or r.get("not_applicable")]
        na = sorted({(c, r["not_applicable"]) for r in recs if r.get("not_applicable") for c in r["case_ids"]})
        if na:
            gaps.append(f"{len(na)} case(s) not applicable on this pod: " + "; ".join(f"{c} ({why})" for c, why in na))
        def ran(s):
            base = os.path.basename(s["path"])
            return any(r["file"] and (os.path.basename(r["file"]) == base or s["rel"].endswith(r["file"])) for r in executed)
        executed_cases = {i for r in executed for i in r["case_ids"]}
        scripted_not_run = sorted(c for c in in_scope if c not in no_script and c not in executed_cases)
        # An unrun script blocks C1 only if it maps to an in-scope case or to no known case (same as qa/audit.py).
        blocking_scripts = [s for s in scripts if (s["ids"] & in_scope) or not (s["ids"] & known)]
        not_run_all = [s["rel"] for s in scripts if not ran(s)]
        not_run = [s["rel"] for s in blocking_scripts if not ran(s)]
        ok = not no_script and not not_run and not scripted_not_run and bool(scripts)
        scope_lbl = ("P1+P2" if include_p2 else "P1") + (" + event-driven (--event-due)" if event_due else "")
        detail = (f"{len(in_scope) - len(no_script)}/{len(in_scope)} in-scope case(s) ({scope_lbl}; retired/held/tolerant excluded) have a script; "
                  f"{len(in_scope) - len(no_script) - len(scripted_not_run)}/{len(in_scope) - len(no_script)} scripted in-scope case(s) were executed "
                  f"(skipped/fixme = not run); {len(blocking_scripts) - len(not_run)}/{len(blocking_scripts)} in-scope script file(s) were run")
        if not scripts:
            detail += "; no Playwright script found for this module"
        if scripted_not_run:
            nr_desc = []
            for c in scripted_not_run:
                rs = [r for r in recs if c in r["case_ids"]]
                why = "; ".join(sorted({(next((a for a in r.get("fixme_reasons", [])), None) or r["outcome"]) for r in rs})) or "no result entry"
                nr_desc.append(f"{c} ({prio.get(c) or 'untiered'}: {why})")
            gaps.append(f"{len(scripted_not_run)} in-scope case(s) scripted but not executed: " + "; ".join(nr_desc))
        crit["C1"] = (ok, detail)
        if no_script:
            gaps.append(f"{len(no_script)} in-scope case(s) without a script: " + ", ".join(no_script[:40]) + (" ..." if len(no_script) > 40 else ""))
        if not_run:
            gaps.append("In-scope script(s) with no executed result: " + ", ".join(not_run))
        other_nr = sorted(set(not_run_all) - set(not_run))
        if other_nr:
            gaps.append("Out-of-scope script(s) with no executed result (not blocking): " + ", ".join(other_nr))
        out_ns = sorted(c for c in deferred if not any(c in s["ids"] for s in scripts))
        if out_ns:
            gaps.append(f"{len(out_ns)} out-of-scope case(s) without a script (not blocking): " + ", ".join(out_ns[:20]))

    # ---- Stand-in (substitute) coverage, QA strategy section 2a: satisfies C1 but is NOT real coverage
    # Same computation as qa/audit.py audit_module(): static script scan (qa.load_scripts full_ids/standin_ids), then
    # result entries (parsed by qa.parse_playwright_json, IDs by qa.case_ids_from_tags) are authoritative: a case whose
    # entries are ALL stand-in (qa.STANDIN_RE over spec title + tags/annotations) is stand-in only.
    sre = getattr(qa, "STANDIN_RE", None) or case_ids.STANDIN_RE
    full_ids = {c for s_ in scripts for c in s_.get("full_ids", s_["ids"])}
    standin_cases = {c for s_ in scripts for c in s_.get("standin_ids", ()) if c in known and c not in full_ids}
    qtests = _qa_tests(qa, tri.get("source"), want)
    if qtests is not None:
        res_si, res_full = set(), set()
        for t in qtests:
            (res_si if sre.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_ids.discard(c)
    else:
        for c in known:
            rs = [r for r in recs if c in r["case_ids"]]
            if rs and all(sre.search(" ".join([r["full_title"]] + list(r.get("tags") or []))) for r in rs):
                standin_cases.add(c)
    standins = []
    for c in sorted(standin_cases):
        rs = [r for r in recs if c in r["case_ids"]]
        standins.append({"case": c, "priority": prio.get(c) or "-", "in_scope": c in in_scope,
                         "scripts": _scripts_for(c),
                         "outcomes": [f"{r['outcome']} [{r['project']}]" for r in rs] or ["not run"]})
    fully = sorted(c for c in in_scope if c in full_ids and c not in standin_cases)
    def _split(cs):
        cs = set(cs)
        f_ = sorted(c for c in cs if c in full_ids and c not in standin_cases)
        si = sorted(c for c in cs if c in standin_cases)
        return {"n": len(cs), "fully": f_, "standin": si, "not_covered": sorted(cs - set(f_) - set(si))}
    coverage = {"p1": _split(c for c in in_scope if tier(prio.get(c)) == "P1"), "all": _split(in_scope)}

    # ---- C2 in-scope P1 passed; gating P2 failures triaged; no P2 defect without waiver/reclassification
    p1 = sorted(c for c in in_scope if tier(prio.get(c)) == "P1")
    p1_bad = [f"{c} ({case_status.get(c, 'not run')})" for c in p1 if case_status.get(c) != "pass"]
    p2_fail = [r for r in gating if r["tier"] == "P2" and r["qa_status"] == "fail"]
    p2_untriaged = [r for r in p2_fail if (r.get("classification") or {}).get("category", "unclassified") == "unclassified"]
    def _blocking_p2_defect(r):
        hv = _review_for(r, review)
        is_defect = hv.get("confirmed") == "real_defect" or (r.get("classification") or {}).get("category") == "real_defect"
        return is_defect and hv.get("confirmed") != "not_defect" and not hv.get("waiver")
    p2_defects = [r for r in p2_fail if _blocking_p2_defect(r)]
    parts = [f"in-scope P1 case(s) passing on first attempt: {len(p1) - len(p1_bad)} of {len(p1)} (tolerant/held/retired excluded)"]
    if p1_bad:
        parts.append("not passed: " + ", ".join(p1_bad))
    parts.append(f"gating P2 failures without a triage verdict: {len(p2_untriaged)} of {len(p2_fail)}")
    parts.append(f"P2 real-defect failures not waived or human-reclassified: {len(p2_defects)}"
                 + (" (" + ", ".join(r.get("case_id") or r["full_title"] for r in p2_defects) + ")" if p2_defects else ""))
    crit["C2"] = (not p1_bad and not p2_untriaged and not p2_defects, "; ".join(parts))
    if not p1 and in_scope:
        gaps.append("No in-scope case is tiered P1, so 'every P1 case passed' is vacuous.")
    untiered = sorted(c for c in known if not tier(prio.get(c)) and cls[c] is None)
    if untiered:
        gaps.append(f"{len(untiered)} designed case(s) have no P1-P4 priority: " + ", ".join(untiered[:20]))

    # ---- C3 flaky rate and owners (gating entries only; tolerant flakiness is reported in its own section)
    flaky = [r for r in gating if r["qa_status"] == "flaky"]
    rate = len(flaky) / gcnt["executed"] if gcnt["executed"] else None
    no_owner = [r for r in flaky if not _owner(r, review)]
    ok3 = rate is not None and rate <= FLAKY_MAX and not no_owner
    crit["C3"] = (ok3, (f"flaky rate {rate:.1%} = {len(flaky)}/{gcnt['executed']} gating executed (limit {FLAKY_MAX:.0%}; tolerant/held/retired entries excluded)"
                        if rate is not None else "no gating executed tests, flaky rate undefined")
                  + f"; flaky test(s) without an owner: {len(no_owner)}")
    if any(r["tier"] == "P1" for r in flaky):
        gaps.append("P1 flaky tests present (QA target for P1 is 0%).")

    # ---- C4 false-fail rate (section 6), over gating failures
    triaged = [r for r in gating if r["qa_status"] == "fail"
               and (r.get("classification") or {}).get("category", "unclassified") != "unclassified"]
    non_def, unconfirmed, defect = 0, 0, 0
    for r in triaged:
        cl, hv = r["classification"], _review_for(r, review).get("confirmed")
        if hv == "not_defect" or (cl["category"] in NON_DEFECT and not cl["needs_review"] and hv != "real_defect"):
            non_def += 1
        elif hv == "real_defect" or cl["category"] == "real_defect":
            defect += 1
        else:
            unconfirmed += 1
    ffr = f"{non_def / len(triaged):.1%}" if triaged else "n/a"
    crit["C4"] = (True, f"false-fail rate {ffr} = non-defect {non_def} / triaged gating failures {len(triaged)}; "
                        f"{unconfirmed} low-confidence non-defect verdict(s) are unconfirmed and not in the numerator; "
                        f"{defect} defect verdict(s)")

    # ---- C5 counts vs qa/audit.py recomputation of the same raw file
    n_cases = len(known) if qa else None
    n_scripts = len(scripts) if qa else None
    if not qa:
        crit["C5"] = (False, "qa/audit.py not available, counts cannot be cross-checked")
    else:
        if qtests is None:
            crit["C5"] = (False, "qa/audit.py could not parse the results file")
        else:
            # Independent recount exactly as `qa/audit.py --module <m>`: qa.parse_playwright_json +
            # qa.case_ids_from_tags + qa.in_module (the same functions our record filter uses).
            a = {k: sum(1 for t in qtests if t["status"] == k) for k in ("pass", "fail", "flaky", "skipped")}
            a["total"] = len(qtests)
            diff = {k: (cnt[k], a[k]) for k in a if cnt[k] != a[k]}
            crit["C5"] = (not diff, f"counts match qa/audit.py --module {want or 'all'} (totals include tolerant/held/retired entries, as the audit counts them)"
                          if not diff else f"mismatch (report, audit): {diff}")

    # ---- C6 by construction
    crit["C6"] = (True, f"report states where the results come from ({target_words(tri)['tag']}) and has an open-gaps section")

    unconfirmed_defects = [r for r in gating if r["qa_status"] == "fail" and (r.get("classification") or {}).get("category") == "real_defect"
                           and not _review_for(r, review).get("confirmed")]
    if unconfirmed_defects:
        gaps.append(f"{len(unconfirmed_defects)} failure(s) classified real defect await human confirmation: "
                    + ", ".join(r.get("case_id") or r["full_title"] for r in unconfirmed_defects))
    review_needed = [r for r in gating if r["qa_status"] == "fail" and (r.get("classification") or {}).get("needs_review")]
    if review_needed:
        gaps.append(f"{len(review_needed)} verdict(s) below confidence {clf.REVIEW_THRESHOLD} need human review.")
    other_fail = [r for r in gating if r["qa_status"] == "fail" and r["tier"] not in ("P1", "P2")]
    if other_fail:
        gaps.append(f"{len(other_fail)} failure(s) on P3/P4/untiered cases do not block under QA's rule but are open.")
    if tri.get("run_errors"):
        gaps.append(f"Playwright reported {len(tri['run_errors'])} run-level error(s); see below.")

    module_label = want or (", ".join(case_ids.modules(set(known) | {i for r in recs for i in r.get("tag_ids") or []})) or "All modules")
    unassigned = [r for r in recs if r.get("unassigned")]
    # HELD (qa/audit.py rule): every case of the module is on execution_hold (or retired) and at least one is held.
    held_all = bool(cases) and all(cls[c] in ("held", "retired") for c in known) and any(cls[c] == "held" for c in known)
    hold_reason = None
    if held_all:
        grp: dict = {}
        for x in lifecycle["held"]:
            grp.setdefault((x["hold"], x["reason"]), []).append(x["case"])
        hold_reason = "; ".join(f"{h} ({len(v)} case(s)): {rsn}" for (h, rsn), v in sorted(grp.items()))
        decision = "HELD"
    else:
        decision = "GO" if all(ok for ok, _ in crit.values()) else "NO-GO"
    return dict(counts=cnt, gating_counts=gcnt, by_class=by_class, criteria=crit, decision=decision, gaps=gaps,
                n_cases=n_cases, n_scripts=n_scripts, n_active_cases=sum(1 for c in known if cls[c] != "retired"),
                flaky_rate=rate, qa_available=qa is not None, include_p2=include_p2, event_due=event_due,
                module_label=module_label, module=want, unassigned=unassigned, tri=tri,
                standins=standins, n_in_scope=len(in_scope), n_fully=len(fully),
                lifecycle=lifecycle, hold_reason=hold_reason, coverage=coverage, hold_breach=hold_breach, held_mock=held_mock)


CRIT_TEXT = {
    "C1": "Coverage: every in-scope case (P1, or P1+P2 with --include-p2; untiered counts; event-driven with --event-due; never retired/held/tolerant) has a script that was executed (skipped/fixme = not run)",
    "C2": "Every in-scope P1 case passed; gating P2 failures triaged; no P2 defect unless waived or human-reclassified",
    "C3": "Flaky rate at most 5 percent of executed, every flaky test has an owner",
    "C4": "False-fail rate reported with denominator",
    "C5": "Report counts match qa/audit.py recomputation",
    "C6": "Statement of where the results come from (mock app or Fusion test pod) and open gaps listed",
}


def _artifacts(r: dict, html_mode=False) -> str:
    keep = [a for a in r.get("artifacts", []) if a["name"] in ("trace", "screenshot", "video", "error-context")
            or a["contentType"].startswith("image/") or a["path"].endswith(".zip")]
    if html_mode:
        return "<br>".join(f'<a href="{html.escape(_rel(a["path"], ROOT / "reports"))}">{html.escape(a["name"])} (try {a["attempt"]})</a>' for a in keep)
    return "<br>".join(f"{a['name']} (try {a['attempt']}): `{_rel(a['path'])}`" for a in keep)


def _cell(s) -> str:
    return str(s if s is not None else "").replace("|", "\\|").replace("\n", " ")


def _count_rows(s: dict) -> list[tuple[str, object]]:
    # Vertical "| Label | N |" rows: the format qa/audit.py's count extractor reads.
    c = s["counts"]
    rows = [("Total", c["total"]), ("Executed", c["executed"]), ("Passed", c["pass"]), ("Failed", c["fail"]),
            ("Flaky", c["flaky"]), ("Skipped", c["skipped"])]
    # Designed cases and Scripts are always shown (0 when none) so qa/audit.py C5 can compare them for every module.
    # Designed cases = every case file of the module incl. retired (same base as qa/audit.py's 'cases').
    rows.append(("Designed cases", s["n_cases"] if s["n_cases"] is not None else "n/a"))
    rows.append(("Scripts", s["n_scripts"] if s["n_scripts"] is not None else "n/a"))
    return rows


def _sorted(recs):
    order = {"failed": 0, "flaky": 1, "skipped": 2, "passed": 3}
    return sorted(recs, key=lambda r: (order[r["outcome"]], r.get("case_id") or "", r["full_title"]))


def _lifecycle_blocks(s: dict) -> list[tuple[str, str, list[str], list[list]]]:
    """(heading, note, header, rows) for the non-blocking lifecycle sections, shared by Markdown and HTML."""
    lc = s["lifecycle"]
    tc = lc["tolerant_counts"]
    out = []
    ts = lc["tolerant_suite"]
    tsc = ts["counts"]
    note = (f"Cases with suite: tolerant / go_no_go: false. The tolerant suite runs separately (`{ts['path']}`, "
            + (f"{ts['entries']} entr(y/ies) for this module, P/F/Fl/S {tsc['pass']}/{tsc['fail']}/{tsc['flaky']}/{tsc['skipped']}; "
               f"tolerant cases with a run result: {ts['with_run']} of {ts['n_tolerant']})" if ts["found"] else "file not found)")
            + ". These results do NOT affect GO/NO-GO: they are never in the main totals, C1-C6 or the verdicts. Tolerant "
            f"entries found in the main results file (P/F/Fl/S {tc['pass']}/{tc['fail']}/{tc['flaky']}/{tc['skipped']}) stay in the "
            "main totals for C5 parity with qa/audit.py but are excluded from gating.")
    if ts["unknown"]:
        note += " Data warning: tolerant-suite entries for case(s) not marked tolerant: " + ", ".join(ts["unknown"]) + "."
    out.append(("Tolerant suite (does not affect GO/NO-GO)", note,
                ["Case", "Tier", "Also held/retired", "Script(s)", "Reason", "Main-file result", "Tolerant-suite result"],
                [[x["case"], x["priority"], x["also"] or "no", ", ".join(x["scripts"]) or "none", x["reason"], x["result"],
                  x.get("suite_result", "no run")] for x in lc["tolerant"]]))
    out.append(("Held (execution_hold): not run, not blocking",
                "Held cases are out of every scope. A held case with a result entry is flagged in Open gaps.",
                ["Case", "Tier", "Hold", "Reason", "Result"],
                [[x["case"], x["priority"], x["hold"], x["reason"], x["result"]] for x in lc["held"]]))
    out.append(("Retired (status: retired): excluded from scope and coverage",
                "Retired cases are never scripted, run or counted in coverage; listed with their successor. Successor check "
                "as in qa/audit.py: superseded_by present, successor exists in tests/cases, successor not retired.",
                ["Case", "Tier", "Superseded by", "Reason", "Script(s)", "Result"],
                [[x["case"], x["priority"], x["superseded_by"], x["reason"], ", ".join(x["scripts"]) or "none", x["result"]] for x in lc["retired"]]))
    out.append(("Event-driven (schedule: event-driven)",
                ("--event-due is ON: event-driven cases that are not retired/held/tolerant are in scope and blocking whatever their tier."
                 if lc["event_due"] else "--event-due is OFF: event-driven cases keep their tier scope."),
                ["Case", "Tier", "Scope this run", "Result"],
                [[x["case"], x["priority"], x["scope"], x["result"]] for x in lc["event_driven"]]))
    out.append(("Conditional (condition field): tier scope unchanged",
                "Listed for information; client answers are never assumed.",
                ["Case", "Tier", "Condition", "Scope this run", "Result"],
                [[x["case"], x["priority"], x["condition"], x["scope"], x["result"]] for x in lc["conditional"]]))
    return out


def _coverage_lines(s: dict) -> list[str]:
    """'P1 in scope: N fully covered, M stand-in only' (+ not covered), same sets as qa/audit.py (fully covered
    excl. stand-ins / covered-by-substitute)."""
    out = []
    all_lbl = f"All in scope ({'P1+P2' if s['include_p2'] else 'P1'} + untiered" + (" + event-driven" if s.get("event_due") else "") + ")"
    for key, label in (("p1", "P1 in scope"), ("all", all_lbl)):
        c = s["coverage"][key]
        line = f"{label}: {c['n']} case(s); {len(c['fully'])} fully covered, {len(c['standin'])} stand-in only"
        if c["not_covered"]:
            more = " ..." if len(c["not_covered"]) > 15 else ""
            line += f", {len(c['not_covered'])} not covered (no script: {', '.join(c['not_covered'][:15])}{more})"
        if c["standin"]:
            line += f". Stand-in only: {', '.join(c['standin'])}"
        out.append(line + ".")
    return out


def coverage_short(s: dict) -> str:
    c = s["coverage"]["p1"]
    nc = f" / {len(c['not_covered'])} not covered" if c["not_covered"] else ""
    return f"{len(c['fully'])} fully / {len(c['standin'])} stand-in only{nc} (of {c['n']})"


HELD_MOCK_LABEL = "Held cases run on mock only (synthetic data, allowed by Chief of Staff 9 Oct 18:30 IST; not counted)"


def held_mock_text(s: dict) -> str | None:
    """Runs in the separate held-suite file: informational, matches qa/audit.py's wording/decision."""
    h = s.get("held_mock")
    if not h:
        return None
    c = h["counts"]
    return (f"{HELD_MOCK_LABEL}: {h['runs']} run(s) in `{h['file']}` (P/F/Fl/S {c['pass']}/{c['fail']}/{c['flaky']}/{c['skipped']}): "
            + ", ".join(h["ids"]) + ". Not in totals, coverage or C1-C6; the module stays HELD until the hold is lifted.")


def breach_text(s: dict) -> str | None:
    """Held cases with entries in the MAIN results file: a real hold breach (qa/audit.py flags these too)."""
    b = s.get("hold_breach")
    if not b:
        return None
    return (f"HOLD BREACH: {b['gate_runs']} entr(y/ies) for held case(s) in the main results `{b['gate_file']}`: "
            + ", ".join(b["gate_ids"]) + ". Held cases must not run in the gate suite. The decision stays HELD.")


def _gating_line(s: dict) -> str:
    g = s["gating_counts"]
    return (f"Gating subset (excludes tolerant, held and retired entries) as entries/run/P/F/Fl/S: "
            f"{g['total']}/{g['executed']}/{g['pass']}/{g['fail']}/{g['flaky']}/{g['skipped']}. "
            f"Active designed case(s) excluding retired: {s['n_active_cases']}.")


def render_markdown(tri: dict, s: dict) -> str:
    tri = s["tri"]
    c = s["counts"]
    tw = target_words(tri)
    L = [f"# {s['module_label']} patch test: go/no-go report", "", f"> {tw['note']}", "",
         f"- Generated: {_now_ist()}",
         f"- Results file: `{_rel(tri['source'])}` (sha256 {_sha256(tri['source'])})"]
    if tri.get("playwright_version"):
        L.append(f"- Playwright version: {tri['playwright_version']}")
    if tri.get("base_urls"):
        L.append(f"- Base URL(s) in config: {', '.join(tri['base_urls'])}")
    L += [f"- Decision rule: QA exit criteria, `{RULE_SOURCE}` (single rule).",
          f"- Classifier: rule-based (`triage/classifier.py`), no LLM; confidence below {clf.REVIEW_THRESHOLD} needs a human.",
          "", f"## Decision: **{s['decision']}** ({tw['run']})", ""]
    if s["decision"] == "HELD":
        L += [f"**{HELD_NOTE}**", "", f"Hold reason: {s['hold_reason']}", ""]
    if breach_text(s):
        L += [f"> **{breach_text(s)}**", ""]
    if held_mock_text(s):
        L += [f"> {held_mock_text(s)}", ""]
    L += ["| Criterion | Result | Detail |", "|---|---|---|"]
    for k, (ok, detail) in s["criteria"].items():
        L.append(f"| {k} {CRIT_TEXT[k]} | {'met' if ok else 'NOT MET'} | {_cell(detail)} |")
    L += ["", f"## Counts (QA definitions, {tw['against']})", "",
          "First-attempt passes only; flaky tests are executed but not passed.", "",
          "| Metric | Count |", "|---|---|"]
    L += [f"| {k} | {v} |" for k, v in _count_rows(s)]
    L += ["", _gating_line(s), "", "Coverage split (same sets as qa/audit.py):", ""] + [f"- {x}" for x in _coverage_lines(s)]
    if c["executed"]:
        L += ["", f"First-attempt success rate: {c['pass'] / c['executed']:.1%} of executed tests."]
    L += ["", "## Failures by class", "", "| Class | Count |", "|---|---|"]
    L += [f"| {clf.CLASS_LABELS[k]} | {s['by_class'].get(k, 0)} |" for k in list(clf.CLASSES) + ["unclassified"]]
    L += ["", "## Open gaps", ""]
    L += [f"- {g}" for g in s["gaps"]] or ["- None recorded."]
    skipped = [r for r in tri["records"] if r["outcome"] == "skipped"]
    L += ["", "## Skipped tests (not executed)", ""]
    if skipped:
        L += ["| Case | Priority | Reason (fixme/skip annotation) |", "|---|---|---|"]
        L += [f"| {_cell(', '.join(r.get('case_ids') or []) or r.get('case_id') or '-')} | {_cell(r.get('priority') or '-')} | "
              f"{_cell('; '.join(r.get('fixme_reasons') or []) or '-')} |" for r in skipped]
    else:
        L.append("None.")
    L += ["", "## Lifecycle: tolerant, held, retired, event-driven, conditional", "", LIFECYCLE_NOTE]
    if s["lifecycle"]["warnings"]:
        L += ["", "Lifecycle data warnings: " + "; ".join(s["lifecycle"]["warnings"])]
    for head, note, hdr, rows in _lifecycle_blocks(s):
        L += ["", f"### {head}", "", note, ""]
        if rows:
            L += ["| " + " | ".join(hdr) + " |", "|" + "---|" * len(hdr)]
            L += ["| " + " | ".join(_cell(x) for x in row) + " |" for row in rows]
        else:
            L.append("None.")
    L += ["", "## Unassigned tests (no module case ID)", "",
          UNASSIGNED_NOTE, ""]
    if s["unassigned"]:
        L += ["| Test | File | Outcome |", "|---|---|---|"]
        L += [f"| {_cell(r['full_title'])} | {_cell(r.get('file'))} | {r['outcome']} |" for r in s["unassigned"]]
    else:
        L.append("None.")
    L += ["", "## Stand-in (substitute) coverage: NOT real coverage", "",
          STANDIN_NOTE, "",
          f"Fully covered in-scope case(s), excluding stand-ins: {s['n_fully']} of {s['n_in_scope']} "
          f"(scope: {'P1+P2' if s['include_p2'] else 'P1'} + untiered).", ""]
    if s["standins"]:
        L += ["| Case | Priority | In scope | Stand-in script(s) | Stand-in result(s) |", "|---|---|---|---|---|"]
        L += [f"| {_cell(x['case'])} | {_cell(x['priority'])} | {'yes' if x['in_scope'] else 'no'} | "
              f"{_cell(', '.join(x['scripts']) or '-')} | {_cell('; '.join(x['outcomes']))} |" for x in s["standins"]]
    else:
        L.append("No stand-in cases in this run.")
    L += ["", "## Per-case results", "",
          "| Case | Test | Project | Priority | Attempts | Outcome | Class | Confidence | Review? | Top evidence | Artifacts |",
          "|---|---|---|---|---|---|---|---|---|---|---|"]
    for r in _sorted(tri["records"]):
        cl = r.get("classification") or {}
        ev = cl.get("evidence", [])
        L.append("| " + " | ".join(_cell(x) for x in [
            ", ".join(r.get("case_ids") or []) or r.get("case_id") or "-", r["full_title"], r["project"] or "-",
            r.get("priority") or "-", r["attempts"], r["outcome"].upper() if r["outcome"] in ("failed", "flaky") else r["outcome"],
            clf.CLASS_LABELS.get(cl.get("category"), "") if cl else "-",
            f"{cl['confidence']:.2f}" if cl else "-", ("yes" if cl.get("needs_review") else "no") if cl else "-",
            ev[0] if ev else "-", _artifacts(r) or "-"]) + " |")
    fails = [r for r in tri["records"] if r["outcome"] in ("failed", "flaky")]
    if fails:
        L += ["", "## Failure details"]
        for r in fails:
            cl = r.get("classification") or {}
            L += ["", f"### {r.get('case_id') or '-'}: {r['full_title']} [{r['project']}] ({r['outcome']})", "",
                  f"- File: `{r['file']}:{r['line']}`"]
            if cl:
                L.append(f"- Class: **{clf.CLASS_LABELS[cl['category']]}**, confidence {cl['confidence']:.2f}"
                         f"{' (conflicting signals)' if cl.get('conflict') else ''}"
                         f"{' - NEEDS HUMAN REVIEW' if cl.get('needs_review') else ''}")
                L.append("- Scores: " + ", ".join(f"{clf.CLASS_LABELS[k]} {v:.2f}" for k, v in cl["scores"].items()))
                L.append("- Evidence:")
                L += [f"  - {e}" for e in cl["evidence"]]
            if r["outcome"] == "flaky":
                L.append("- Flaky: failed, then passed on retry (QA: executed, not passed).")
            first = next((e for e in r["errors"] if e["message"]), None)
            if first:
                L += [f"- First error (attempt {first['attempt']}):", "", "```",
                      "\n".join(first["message"].splitlines()[:12]), "```"]
            if _artifacts(r):
                L.append(f"- Artifacts: {_artifacts(r)}")
    if tri.get("run_errors"):
        L += ["", "## Run-level errors"]
        for e in tri["run_errors"]:
            L += ["", "```", e[:2000], "```"]
    L += ["", "---", f"Reminder: {tw['note'].replace('**', '')}", ""]
    return "\n".join(L)


def render_html(tri: dict, s: dict) -> str:
    tri = s["tri"]
    e = html.escape
    color = {"NO-GO": "#b00020", "HELD": "#8a6d00"}.get(s["decision"], "#1b7f3b")
    held = (f"<p class='note'><b>{e(HELD_NOTE)}</b><br>Hold reason: {e(s['hold_reason'] or '')}</p>" if s["decision"] == "HELD" else "")
    if breach_text(s):
        held += f"<p class='note' style='background:#fdecea;border-color:#b00020'><b>{e(breach_text(s))}</b></p>"
    if held_mock_text(s):
        held += f"<p style='background:#eef4fb;border:1px solid #9bb8d9;padding:.6rem'>{e(held_mock_text(s))}</p>"
    cov_html = "".join(f"<li>{e(x)}</li>" for x in _coverage_lines(s))
    lc_html = f"<h2>Lifecycle: tolerant, held, retired, event-driven, conditional</h2><p>{e(LIFECYCLE_NOTE)}</p>"
    if s["lifecycle"]["warnings"]:
        lc_html += f"<p>Lifecycle data warnings: {e('; '.join(s['lifecycle']['warnings']))}</p>"
    for head, lnote, hdr, lrows in _lifecycle_blocks(s):
        lc_html += f"<h3>{e(head)}</h3><p>{e(lnote)}</p>"
        lc_html += ("<table><tr>" + "".join(f"<th>{e(h)}</th>" for h in hdr) + "</tr>" + "".join(
            "<tr>" + "".join(f"<td>{e(str(x))}</td>" for x in row) + "</tr>" for row in lrows) + "</table>") if lrows else "<p>None.</p>"
    crit = "".join(f"<tr><td>{k} {e(CRIT_TEXT[k])}</td><td>{'met' if ok else '<b>NOT MET</b>'}</td><td>{e(d)}</td></tr>"
                   for k, (ok, d) in s["criteria"].items())
    # third "unit" cell keeps each number separated from the next row's label once tags are stripped
    counts = "".join(f"<tr><td>{e(k)}</td><td>{v}</td><td>{'files' if k == 'Scripts' else 'items'}</td></tr>"
                     for k, v in _count_rows(s))
    cls_rows = "".join(f"<tr><td>{e(clf.CLASS_LABELS[k])}</td><td>{s['by_class'].get(k, 0)}</td></tr>"
                       for k in list(clf.CLASSES) + ["unclassified"])
    gaps = "".join(f"<li>{e(g)}</li>" for g in s["gaps"]) or "<li>None recorded.</li>"
    rows = []
    for r in _sorted(tri["records"]):
        cl = r.get("classification") or {}
        conf = f"{cl['confidence']:.2f}" if cl else "-"
        rows.append(
            f"<tr class='{r['outcome']}'><td>{e(', '.join(r.get('case_ids') or []) or r.get('case_id') or '-')}</td>"
            f"<td>{e(r['full_title'])}</td><td>{e(r['project'] or '-')}</td><td>{e(r.get('priority') or '-')}</td>"
            f"<td>{r['attempts']}</td><td>{e(r['outcome'])}</td>"
            f"<td>{e(clf.CLASS_LABELS.get(cl.get('category'), '')) if cl else '-'}</td><td>{conf}</td>"
            f"<td>{('yes' if cl.get('needs_review') else 'no') if cl else '-'}</td>"
            f"<td>{'<br>'.join(e(x) for x in cl.get('evidence', [])) or '-'}</td>"
            f"<td>{_artifacts(r, html_mode=True) or '-'}</td></tr>")
    tw = target_words(tri)
    note = e(tw["note"].replace("**", ""))
    unassigned_tbl = ("<table><tr><th>Test</th><th>File</th><th>Outcome</th></tr>" + "".join(
        f"<tr><td>{e(r['full_title'])}</td><td>{e(str(r.get('file')))}</td><td>{e(r['outcome'])}</td></tr>"
        for r in s["unassigned"]) + "</table>") if s["unassigned"] else "<p>None.</p>"
    standin_tbl = ("<table><tr><th>Case</th><th>Priority</th><th>In scope</th><th>Stand-in script(s)</th><th>Stand-in result(s)</th></tr>"
                   + "".join(f"<tr><td>{e(x['case'])} (STAND-IN)</td><td>{e(x['priority'])}</td><td>{'yes' if x['in_scope'] else 'no'}</td>"
                             f"<td>{e(', '.join(x['scripts']) or '-')}</td><td>{e('; '.join(x['outcomes']))}</td></tr>" for x in s["standins"])
                   + "</table>") if s["standins"] else "<p>No stand-in cases in this run.</p>"
    return f"""<!doctype html><html><head><meta charset="utf-8"><title>{e(s['module_label'])} go/no-go ({e(tw['tag'])})</title>
<style>body{{font-family:system-ui,sans-serif;margin:2rem;max-width:1400px}}table{{border-collapse:collapse;margin:1rem 0}}
td,th{{border:1px solid #ccc;padding:4px 8px;vertical-align:top;font-size:13px}}th{{background:#f3f3f3}}
.note{{background:#fff4e5;border:1px solid #f0a500;padding:.8rem}}.decision{{font-size:1.6rem;color:{color}}}
tr.failed{{background:#fdecea}}tr.flaky{{background:#fff8e1}}tr.skipped{{color:#777}}</style></head><body>
<h1>{e(s['module_label'])} patch test: go/no-go report</h1>
<div class="note"><b>{note}</b></div>
<p>Generated {e(_now_ist())} from <code>{e(_rel(tri['source']))}</code> (sha256 {_sha256(tri['source'])}).
Decision rule: QA exit criteria, <code>{e(RULE_SOURCE)}</code>.</p>
<p class="decision"><b>Decision: {s['decision']}</b> ({e(tw['run'])})</p>
{held}<table><tr><th>Criterion</th><th>Result</th><th>Detail</th></tr>{crit}</table>
<h2>Counts (QA definitions, {e(tw['against'])})</h2><table><tr><th>Metric</th><th>Count</th><th>Unit</th></tr>{counts}</table>
<p>{e(_gating_line(s))}</p>
<p>Coverage split (same sets as qa/audit.py):</p><ul>{cov_html}</ul>
<h2>Failures by class</h2><table><tr><th>Class</th><th>Count</th></tr>{cls_rows}</table>
<h2>Open gaps</h2><ul>{gaps}</ul>
{lc_html}
<h2>Unassigned tests (no module case ID)</h2><p>{e(UNASSIGNED_NOTE)}</p>{unassigned_tbl}
<h2>Stand-in (substitute) coverage: NOT real coverage</h2><p>{e(STANDIN_NOTE)}</p>
<p>Fully covered in-scope case(s), excluding stand-ins: {s['n_fully']} of {s['n_in_scope']}
(scope: {'P1+P2' if s['include_p2'] else 'P1'} + untiered).</p>{standin_tbl}
<h2>Per-case results</h2><table><tr><th>Case</th><th>Test</th><th>Project</th><th>Priority</th><th>Attempts</th><th>Outcome</th>
<th>Class</th><th>Confidence</th><th>Review?</th><th>Evidence</th><th>Artifacts</th></tr>{''.join(rows)}</table>
<p><b>{note}</b></p></body></html>
"""


def load_review(path: Path) -> dict:
    try:
        return json.loads(path.read_text(encoding="utf-8")) if path.is_file() else {}
    except (OSError, json.JSONDecodeError):
        return {}


def module_out_dir(base: Path, module) -> Path:
    """Output scheme: P2P -> <base>/ (legacy reports/go-no-go.*, unchanged); any other module M -> <base>/<m>/
    (lower-case, e.g. reports/o2c/go-no-go.md); --module all also writes <base>/go-no-go-all.md (index)."""
    want = want_module(module)
    return base if want in (None, DEFAULT_MODULE) else base / want.lower()


def write_reports(tri: dict, out_dir: Path, basename: str = "go-no-go", root: Path = ROOT,
                  review: dict | None = None, include_p2: bool = False, module=DEFAULT_MODULE, event_due: bool = False) -> dict:
    """Write one module's report into out_dir exactly (callers pick the dir via module_out_dir)."""
    out_dir.mkdir(parents=True, exist_ok=True)
    if review is None:
        review = load_review(root / "reports" / "human-review.json")
    s = summarize(tri, root, review, include_p2, module, event_due)
    (out_dir / "triage.json").write_text(json.dumps(s["tri"], indent=2, default=str), encoding="utf-8")
    (out_dir / f"{basename}.md").write_text(render_markdown(tri, s), encoding="utf-8")
    (out_dir / f"{basename}.html").write_text(render_html(tri, s), encoding="utf-8")
    return s


INDEX_HDR = "| Module | Decision | Criteria not met | Counts | Scripts | P1 in scope: coverage | Tolerant suite P/F/Fl/S (not gating) | Hold reason | Held cases: runs (mock only / main results) | Lifecycle (retired / held / tolerant) | Report |"


def write_all_modules(tri: dict, base: Path, root: Path = ROOT, review: dict | None = None,
                      include_p2: bool = False, event_due: bool = False) -> dict[str, dict]:
    """--module all: one report per module (module_out_dir scheme) + <base>/go-no-go-all.md index."""
    out = {}
    for m in modules_in(tri, root):
        out[m] = write_reports(tri, module_out_dir(base, m), root=root, review=review, include_p2=include_p2, module=m,
                               event_due=event_due)
    L = ["# All modules: go/no-go index (mock run)", "", f"> {MOCK_NOTE}", "",
         f"- Generated: {_now_ist()}; one decision per module, each by QA's rule (C1-C6). There is no combined decision.",
         "- Unassigned (ID-less) tests are counted in every module, as qa/audit.py does, so module totals can overlap.",
         f"- Scope: C1 {'P1+P2' if include_p2 else 'P1'} + untiered; --event-due {'ON' if event_due else 'OFF'}. HELD = every case of the "
         f"module is on execution_hold (no run, no sign-off; not a GO and not a NO-GO).",
         "- Exit code of run_triage.py / generate_report.py: 0 all GO, 1 any NO-GO, 3 no NO-GO but some HELD, 2 WAITING (no results).", "",
         INDEX_HDR, "|---|---|---|---|---|---|---|---|---|---|---|"]
    breaches, mock_notes = [], []
    for m, s in out.items():
        bad = "n/a (held)" if s["decision"] == "HELD" else (", ".join(k for k, (ok, _) in s["criteria"].items() if not ok) or "-")
        lc = s["lifecycle"]
        ts = lc["tolerant_suite"]
        tsc = ts["counts"]
        tol_s = f"{tsc['pass']}/{tsc['fail']}/{tsc['flaky']}/{tsc['skipped']}" if ts["entries"] else "-"
        b, h = s.get("hold_breach"), s.get("held_mock")
        parts = []
        if h:
            parts.append(f"{h['runs']} run(s) on mock only, {len(h['ids'])} case(s) (allowed, not counted)")
        if b:
            parts.append(f"**HOLD BREACH**: {b['gate_runs']} in main results ({', '.join(b['gate_ids'])})")
            breaches.append(f"- **{m}: {breach_text(s)}**")
        if h:
            mock_notes.append(f"- {m}: {held_mock_text(s)}")
        bshort = "; ".join(parts) or "-"
        L.append(f"| {m} | {s['decision']} | {bad} | {_cell(counts_line(s))} | {s['n_scripts']} | {coverage_short(s)} | {tol_s} | "
                 f"{_cell(s['hold_reason'] or '-')} | {bshort} | "
                 f"{len(lc['retired'])} / {len(lc['held'])} / {len(lc['tolerant'])} | `{_rel(str(module_out_dir(base, m) / 'go-no-go.md'))}` |")
    pre = []
    if breaches:
        pre += ["## HOLD BREACH (held cases in the main results)", ""] + breaches + [""]
    if mock_notes:
        pre += ["## Held cases run on mock only (allowed, not counted)", ""] + mock_notes + [""]
    if pre:
        i = L.index(INDEX_HDR)
        L[i:i] = pre + ["## Modules", ""]
    base.mkdir(parents=True, exist_ok=True)
    (base / "go-no-go-all.md").write_text("\n".join(L) + "\n", encoding="utf-8")
    return out


def main(argv=None) -> int:
    import argparse
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    g = ap.add_mutually_exclusive_group(required=True)
    g.add_argument("--triage", help="triage JSON written by triage/classifier.py")
    g.add_argument("--results", help="Playwright JSON results (runs the classifier first)")
    ap.add_argument("--root", default=str(ROOT), help="project root (tests/cases, automation/, qa/)")
    ap.add_argument("--out-dir", default=str(ROOT / "reports"))
    ap.add_argument("--include-p2", action="store_true", help="P2 cases count toward C1 coverage (default: P1 only)")
    ap.add_argument("--module", default=DEFAULT_MODULE, help="module pack by case-ID prefix (P2P, O2C, R2R, ...) or 'all' (default: P2P)")
    ap.add_argument("--event-due", action="store_true",
                    help="event-driven cases (schedule: event-driven) are due this cycle: in scope and blocking whatever their tier")
    a = ap.parse_args(argv)
    root = Path(a.root)
    tri = json.loads(Path(a.triage).read_text()) if a.triage else clf.triage(a.results, root / "tests" / "cases")
    base = Path(a.out_dir)
    if want_module(a.module) is None:
        res = write_all_modules(tri, base, root=root, include_p2=a.include_p2, event_due=a.event_due)
    else:
        res = {want_module(a.module): write_reports(tri, module_out_dir(base, a.module), root=root,
                                                    include_p2=a.include_p2, module=a.module, event_due=a.event_due)}
    for m, s in res.items():
        print(f"[{m}] {s['decision']} (QA rule, mock run): {counts_line(s)} -> {module_out_dir(base, m)}/go-no-go.md")
    return exit_code(s["decision"] for s in res.values())


if __name__ == "__main__":
    raise SystemExit(main())