#!/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//; 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"(? 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//, 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 '@' 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"(? 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//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"(?]*>.*?", " ", text, flags=re.S | re.I) text = re.sub(r"\s*]*>", " | ", 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-.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("
All findings") P("") L.extend(details[:500]) P("") P("
") 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())