File size: 29,396 Bytes
fb62a97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55ac80e
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
#!/usr/bin/env python3
"""Rule-based failure classifier for Playwright JSON reporter output.

Input : a Playwright JSON report (``reporter: [['json', {outputFile: 'results.json'}]]``
        or ``npx playwright test --reporter=json > results.json``).
Output: one record per test (passed / failed / flaky / skipped) and, for every
        failed or flaky test, a classification into one of

            ui_change | data | timing | environment | real_defect   (or ``unclassified``)

        ``timing`` is a page slower than the script's wait; ``environment`` is the pod or the network
        (HTTP 5xx, sign-in refused, Oracle's edge refusing the browser, a crashed browser, a pass that
        stopped before it reported). Neither is a product defect.

        with a confidence score in [0, 1] and the evidence (matched signals).

Pure standard library.  No LLM, no network.  This classifier only reads what
Playwright wrote; it never contacts Oracle Fusion or any other system.
"""
from __future__ import annotations

import json
import re
from dataclasses import dataclass, field, asdict
from pathlib import Path
from typing import Iterable

try:  # shared tier logic (QA mapping) and case-ID/tag parsing; see triage/risk.py, triage/ids.py
    from .risk import tier, is_high_risk  # noqa: F401
    from . import ids as case_ids
except ImportError:
    from risk import tier, is_high_risk  # noqa: F401
    import ids as case_ids

CLASSES = ("ui_change", "data", "timing", "environment", "real_defect")
CLASS_LABELS = {
    "ui_change": "UI change",
    "data": "Data",
    "timing": "Timing",
    "environment": "Environment (pod or network)",
    "real_defect": "Real defect",
    "unclassified": "Unclassified (needs human)",
}
REVIEW_THRESHOLD = 0.6  # below this a human must review the classification

ANSI_RE = re.compile(r"\x1b\[[0-9;]*[A-Za-z]")

# Business words that make an assertion mismatch look like a functional defect.
BUSINESS_RE = re.compile(
    r"\b(amount|total|subtotal|price|unit[ _-]?price|quantity|qty|status|state|match(?:ed|ing)?|"
    r"hold|holds|approv\w*|reject\w*|tax|payment|paid|balance|variance|tolerance|currency|"
    r"invoice|receipt|requisition|purchase[ _-]?order|po[ _-]?(?:number|line|status)|"
    r"supplier|accounting|distribution|encumbrance|budget|discount|freight|due[ _-]?date|"
    r"validated|validation[ _-]?status|cancel\w*|closed|open)\b",
    re.I,
)
INTERMEDIATE_STATE_RE = re.compile(
    r"received(?: string| value)?:\s*['\"]?\s*(pending|processing|in progress|in process|submitted|"
    r"validating|running|queued|incomplete|draft)\b",
    re.I,
)
NOT_FOUND_RE = re.compile(
    r"element\(s\) not found|resolved to 0 elements|no element(?:s)? match|unable to find element|"
    r"failed to find element|<element\(s\) not found>",
    re.I,
)
EXPECT_RE = re.compile(r"expect\(|\bexpected(?: string| value| substring| pattern)?:|assertionerror", re.I)
RECEIVED_VALUE_RE = re.compile(r"received(?: string| value| substring)?:\s*(?!<element)(\S.*)", re.I)
HTTP4XX_RE = re.compile(
    r"(?:\bstatus(?:\s*code)?\D{0,12}|received:\s*|\bhttp\s*|\bresponse\D{0,12})(4\d\d)\b|"
    r"\b(4\d\d)\s+(?:bad request|unauthorized|forbidden|not found|conflict|unprocessable|gone)",
    re.I,
)
# the browser never reached the application: Oracle's edge (Akamai) refused it, or the sign-in did not get through
EDGE_DENIED_RE = re.compile(
    r"\bakamai\b|edgesuite\.net|you don't have permission to access .{0,200} on this server|"
    r"access denied[\s\S]{0,300}reference\s*#\s*[0-9a-f]+\.[0-9a-f.]+",
    re.I,
)
SIGN_IN_RE = re.compile(
    r"idcs-signin|invalid (?:user ?name|user id) or password|(?:user ?name|user id) or password (?:is )?(?:incorrect|invalid)|"
    r"account (?:is |has been )?locked|password (?:has )?expired|sign[ -]?in (?:failed|refused|was refused)|authentication failed|"
    r"waiting for (?:navigation|url)[^\n]{0,40}(?:atkhomepagewelcome|fusewelcome)",
    re.I,
)
BROWSER_CRASH_RE = re.compile(
    r"target crashed|page crashed|browser (?:has )?(?:crashed|disconnected)|browser closed unexpectedly|"
    r"out of memory|\boom\b|sigkill|browsertype\.launch",
    re.I,
)
NETWORK_RE = re.compile(
    r"net::err_(?:connection_\w+|timed_out|empty_response|name_not_resolved|internet_disconnected|address_unreachable|"
    r"tunnel_connection_failed|proxy_connection_failed|network_changed|ssl_protocol_error|cert_\w+)|"
    r"\beconn(?:refused|reset|aborted)\b|\benotfound\b|\betimedout\b|socket hang up",
    re.I,
)
# a whole pass that ended without a result of its own (the runner was lost or the pass overran): no step was judged
PASS_LOST_RE = re.compile(
    r"stopped before it reported|produced no report|did not finish the attempt in time|runner (?:no longer knows|restarted)|"
    r"results are lost",
    re.I,
)
HTTP5XX_RE = re.compile(
    r"(?:\bstatus(?:\s*code)?\D{0,12}|received:\s*|\bhttp\s*|\bresponse\D{0,12})(5\d\d)\b|"
    r"\b(5\d\d)\s+(?:internal server error|bad gateway|service unavailable|gateway timeout)",
    re.I,
)


@dataclass
class Signal:
    cls: str
    weight: float
    evidence: str


@dataclass
class Classification:
    category: str
    confidence: float
    scores: dict
    evidence: list
    conflict: bool
    needs_review: bool


@dataclass
class TestRecord:
    test_id: str
    title: str
    full_title: str
    file: str
    line: int | None
    project: str
    case_id: str | None
    tags: list
    outcome: str  # passed | failed | flaky | skipped
    attempts: int
    duration_ms: int
    errors: list = field(default_factory=list)  # [{attempt, status, message, stack, snippet}]
    artifacts: list = field(default_factory=list)  # [{attempt, name, contentType, path}]
    classification: Classification | None = None
    risk: str | None = None
    owner: str | None = None  # from a Playwright annotation {type: 'owner'}
    fixme_reasons: list = field(default_factory=list)  # descriptions of fixme/skip annotations
    not_applicable: str | None = None  # why the scenario does not apply to this pod's setup (annotation 'not-applicable')
    tag_ids: list = field(default_factory=list)  # every case ID from @<CASE-ID> tags (tags only)
    spec_tags: list = field(default_factory=list)  # spec-level tags exactly as Playwright wrote them (what qa/audit.py reads)

    def to_dict(self) -> dict:
        d = asdict(self)
        return d


# --------------------------------------------------------------------------- utils

def strip_ansi(text: str | None) -> str:
    return ANSI_RE.sub("", text or "")


def _failing_snippet_lines(snippet: str) -> str:
    """Playwright code frames mark the failing line with a leading '>'."""
    lines = [l for l in strip_ansi(snippet).splitlines() if l.lstrip().startswith(">")]
    return "\n".join(lines)


def _noisy_or(weights: Iterable[float]) -> float:
    p = 1.0
    for w in weights:
        p *= 1.0 - max(0.0, min(1.0, w))
    return 1.0 - p


# --------------------------------------------------------------------------- rules

def extract_signals(message: str, stack: str = "", snippet: str = "", result_status: str = "") -> list[Signal]:
    """Turn one error (message/stack/snippet) into weighted class signals."""
    msg = strip_ansi(message)
    code = _failing_snippet_lines(snippet)
    low = msg.lower()
    sig: list[Signal] = []

    def add(cls, w, ev):
        sig.append(Signal(cls, w, ev))

    first_line = low.strip().splitlines()[0] if low.strip() else ""
    is_expect = bool(EXPECT_RE.search(first_line)) or "waiting for expect(" in low or (
        "expected" in low and "received" in low
    )
    not_found = bool(NOT_FOUND_RE.search(low))
    received = RECEIVED_VALUE_RE.search(msg)
    has_value_mismatch = is_expect and received is not None and not not_found

    # ---------------- UI change
    if "strict mode violation" in low:
        add("ui_change", 0.9, "Strict mode violation: locator matched multiple elements (DOM/locator changed)")
    if not_found:
        add("ui_change", 0.85, "Locator not found (element(s) not found / resolved to 0 elements)")
    if re.search(r"is not an? <?(select|input|checkbox|radio|textarea)|not an? <input>|element is not an? <", low):
        add("ui_change", 0.7, "Element type differs from what the script expects")
    if re.search(r"tohaveurl|tohavetitle", low) and is_expect:
        add("ui_change", 0.4, "Page URL/title assertion failed (route or page changed)")
        add("timing", 0.3, "URL/title assertion may have run before navigation completed")

    # the pod or the network explains a wait that timed out: a lost pass, or a sign-in that did not get through
    pass_lost = bool(PASS_LOST_RE.search(msg))
    signing_in = bool(SIGN_IN_RE.search(msg) or SIGN_IN_RE.search(code))
    crashed = bool(BROWSER_CRASH_RE.search(msg))

    # Locator wait that timed out without ever resolving: genuinely ambiguous.
    waiting_locator = re.search(r"waiting for (locator\(|getby\w+\(|selector )", low)
    if waiting_locator and "timeout" in low and not is_expect and not not_found and not signing_in:
        if "resolved to" in low:
            pass  # element existed; actionability handled below
        else:
            add("ui_change", 0.5, "Action timed out waiting for a locator that never resolved (element renamed/removed?)")
            add("timing", 0.5, "Action timed out waiting for a locator (page may simply be slow)")

    # ---------------- Environment (the pod or the network, not the page being slower than the wait)
    if pass_lost:
        add("environment", 0.9, "The whole pass stopped before it reported (runner lost or pass overran): no step was judged")
    if EDGE_DENIED_RE.search(msg):
        add("environment", 0.9, "Oracle's edge (Akamai) refused the browser: Access Denied from the network, not the application")
    if signing_in:
        add("environment", 0.85, "Sign-in did not get through (password refused, user locked, or the sign-in page did not load)")
    if crashed:
        add("environment", 0.85, "The browser crashed or ran out of memory")
    if NETWORK_RE.search(low):
        add("environment", 0.8, "Network error: the pod could not be reached")

    # ---------------- Timing
    if (re.search(r"test timeout of \d+ms exceeded", low) or result_status == "timedOut") and not pass_lost:
        add("timing", 0.7, "Test-level timeout exceeded")
    if not signing_in and re.search(r"(page\.goto|goto|waitfornavigation|waitforurl|waitforloadstate|navigat\w*)[^\n]{0,80}timeout|"
                                    r"timeout[^\n]{0,80}(navigat\w*|waitforurl|waitforloadstate|page\.goto)", low):
        add("timing", 0.85, "Navigation / page-load wait timed out")
    if re.search(r"(waitforresponse|waitforrequest|waitforevent|waitforfunction|waitforselector)[^\n]{0,80}timeout|"
                 r"timeout[^\n]{0,80}(waitforresponse|waitforrequest|waitforevent|waitforfunction|waitforselector)", low):
        add("timing", 0.8, "Explicit waitFor* call timed out")
    if re.search(r"element is not (visible|stable|enabled|editable|attached)|intercepts pointer events|"
                 r"element was detached|detached from the dom|not attached to the dom", low):
        add("timing", 0.75, "Element present but not actionable in time (not visible/stable/enabled, overlay)")
    if re.search(r"execution context was destroyed|target page, context or browser has been closed", low) and not crashed:
        add("timing", 0.5, "Page/context closed or navigated mid-action (race)")
    if not is_expect and "timeouterror" in low and not (pass_lost or signing_in):
        add("timing", 0.6, "TimeoutError raised")
    elif not is_expect and re.search(r"timeout \d+ms exceeded", low) and not sig:
        add("timing", 0.5, "Action timeout exceeded")
    if has_value_mismatch and INTERMEDIATE_STATE_RE.search(msg):
        add("timing", 0.5, "Received value is an intermediate state (e.g. Pending/Processing): async process may not have finished")

    # ---------------- Data
    http4 = HTTP4XX_RE.search(msg) or HTTP4XX_RE.search(code)
    if http4:
        add("data", 0.8, f"HTTP {http4.group(1) or http4.group(2)} client error (bad/missing/conflicting input data)")
    if re.search(r"validation (error|failed)|failed validation|is required|required field|mandatory field|"
                 r"invalid (value|supplier|item|account|date|currency|business unit|bu|location|ship-to|bill-to)", low):
        add("data", 0.75, "Validation / required-field error from the application")
    if re.search(r"\b(record|supplier|vendor|item|po|purchase order|requisition|invoice|receipt|user|buyer)"
                 r"(?:\s+['\"]?[\w#./-]+['\"]?)?\s+(not found|does not exist|doesn't exist|is missing|missing)|no (matching )?(records?|rows|data|results) found|"
                 r"missing (test )?data", low):
        add("data", 0.75, "Referenced record missing (test data not seeded?)")
    if re.search(r"duplicate|already exists|unique constraint", low):
        add("data", 0.8, "Duplicate / already-exists error (data reuse between runs?)")
    if re.search(r"test data|seed(ed)? data|data recipe|fixture data", low):
        add("data", 0.5, "Error mentions test data / seed data")

    # a server error: Fusion (or a proxy before it) failed to answer, which the pod's state explains, not the business step
    http5 = HTTP5XX_RE.search(msg) or HTTP5XX_RE.search(code)
    if http5:
        add("environment", 0.7, f"HTTP {http5.group(1) or http5.group(2)} server error from the pod (or a proxy before it)")

    # ---------------- Real defect
    if has_value_mismatch:
        # Remove HTTP-status idioms so 'response.status()' is not treated as a business status.
        scan = re.sub(r"\w*\.status\(\)|statuscode|status code", " ", msg + "\n" + code, flags=re.I)
        # only look at the expect expression, Locator, Expected and Received lines
        focus = "\n".join(
            l for l in scan.splitlines()
            if re.search(r"expect\(|locator:|expected|received|^\s*>", l, re.I)
        )
        focus = re.sub(r"\.(?:not\.)?to[A-Z]\w*", " ", focus)  # drop matcher names (toMatch, toHaveText...)
        focus = re.sub(r"(?i)\b(expected|received)(?: string| value| substring| pattern)?:", " ", focus)
        focus = re.sub(r"(?i)waiting for expect|call log", " ", focus)
        focus = re.sub(r"([a-z])([A-Z])", r"\1 \2", focus)  # invoiceTotal -> invoice Total
        focus = re.sub(r"[_\-.]", " ", focus)
        words = sorted({m.group(0).lower() for m in BUSINESS_RE.finditer(focus)})
        if http5:
            pass  # the status assertion is the server error above
        elif words and not http4:
            exp = re.search(r"expected(?: string| value| substring)?:\s*(.*)", msg, re.I)
            detail = f" (expected {exp.group(1).strip()[:60]}, received {received.group(1).strip()[:60]})" if exp else ""
            add("real_defect", 0.85, f"Assertion mismatch on business value(s) [{', '.join(words)}]{detail}")
        elif not http4:
            add("real_defect", 0.4, "Assertion mismatch with no business-value keyword (could be defect or script expectation)")
    return sig


def classify_signals(signals: list[Signal]) -> Classification:
    scores = {c: 0.0 for c in CLASSES}
    for c in CLASSES:
        scores[c] = round(_noisy_or(s.weight for s in signals if s.cls == c), 3)
    ranked = sorted(scores.items(), key=lambda kv: kv[1], reverse=True)
    (top_cls, top), (_, second) = ranked[0], ranked[1]
    ordered = sorted(signals, key=lambda s: (s.cls != top_cls, -s.weight))  # strongest supporting signal first
    evidence = [f"[{CLASS_LABELS[s.cls]} +{s.weight:.2f}] {s.evidence}" for s in ordered]
    if top <= 0:
        return Classification("unclassified", 0.0, scores, evidence or ["No known signal matched"], False, True)
    conf = top * (1 - 0.8 * second / top) if second > 0 else top
    conf = round(max(0.0, min(1.0, conf)), 2)
    conflict = second >= 0.3 and second >= 0.5 * top
    if conflict:
        evidence.append(f"Conflicting signals: {ranked[0][0]}={top:.2f} vs {ranked[1][0]}={second:.2f} -> confidence lowered")
    return Classification(top_cls, conf, scores, evidence, conflict, conf < REVIEW_THRESHOLD)


def classify_errors(errors: list[dict]) -> Classification:
    """Classify a test from all of its failed attempts' errors (deduplicated signals)."""
    seen, signals = set(), []
    for e in errors:
        for s in extract_signals(e.get("message", ""), e.get("stack", ""), e.get("snippet", ""), e.get("status", "")):
            key = (s.cls, s.evidence)
            if key not in seen:
                seen.add(key)
                signals.append(s)
    return classify_signals(signals)


# --------------------------------------------------------------------------- report parsing

CASE_ID_RE = case_ids.CASE_ID_RE  # shared, module-neutral (triage/ids.py)


def _tag_ids(spec: dict, test: dict) -> list[str]:
    """Case IDs from @<CASE-ID> tags ONLY (Playwright JSON stores tags without the '@'; both forms accepted).
    Titles, file names, fixme/skip reasons and other annotation text are never read for IDs: a recipe name such as
    DR-O2C-INT-003 in a fixme reason must not become a case ID (it created a fake 'DR' module). qa/audit.py has no
    dedicated case annotation, so none is read here either."""
    return list(dict.fromkeys(i for i in (case_ids.tag_case_id(t) for t in (spec.get("tags") or []) + (test.get("tags") or [])) if i))


def _case_id(spec: dict, test: dict, titles: list[str] | None = None) -> str | None:
    """Primary case ID = first case-ID tag (see _tag_ids). `titles` is accepted for compatibility and ignored."""
    ids = _tag_ids(spec, test)
    return ids[0] if ids else None


_SPEC_FILE = re.compile(r"\.(spec|test)\.[cm]?[jt]sx?$")


def spec_file(spec: dict, root_file: str | None) -> str:
    """The test file a result belongs to. Playwright's spec.file is where test() was called; when a spec file builds its
    test through a shared helper (the Fusion step runner: steps/AP-FUS-011.spec.ts calls src/fusion/steps.ts), that is
    the helper, so the result is credited to the top-level suite's file, the spec that was actually run."""
    f = spec.get("file", "") or ""
    if root_file and f != root_file and not _SPEC_FILE.search(f):
        return root_file
    return f


def _walk_suites(suites: list, parents: list[str], root_file: str | None = None):
    for s in suites or []:
        title = s.get("title", "")
        chain = parents + ([title] if title else [])
        root = root_file or s.get("file")
        for spec in s.get("specs", []) or []:
            yield spec, chain, root
        yield from _walk_suites(s.get("suites", []), chain, root)


def _outcome(test: dict) -> str:
    st = test.get("status")
    results = test.get("results") or []
    if st == "skipped":
        return "skipped"
    if st == "flaky":
        return "flaky"
    if st == "unexpected":
        return "failed"
    if st == "expected":
        return "passed"
    # Fallback for reports without test.status
    statuses = [r.get("status") for r in results]
    if not statuses or all(s == "skipped" for s in statuses):
        return "skipped"
    if statuses[-1] == "passed":
        return "flaky" if any(s in ("failed", "timedOut", "interrupted") for s in statuses[:-1]) else "passed"
    return "failed"


def load_report(path: str | Path) -> dict:
    with open(path, encoding="utf-8") as f:
        data = json.load(f)
    if not isinstance(data, dict) or "suites" not in data:
        raise ValueError(f"{path} is not a Playwright JSON reporter file (no 'suites' key)")
    return data


def parse_report(data: dict, base_dir: Path | None = None) -> list[TestRecord]:
    records: list[TestRecord] = []
    for spec, chain, root_file in _walk_suites(data.get("suites", []), []):
        for test in spec.get("tests", []) or []:
            results = test.get("results") or []
            titles = chain + [spec.get("title", "")]
            errors, artifacts = [], []
            for r in results:
                attempt = r.get("retry", 0)
                errs = r.get("errors") or ([r["error"]] if r.get("error") else [])
                if r.get("error") and r.get("errors"):
                    # 'error' duplicates errors[0]; keep the richer one (stack/snippet)
                    errs = [r["error"]] + [e for e in r["errors"][1:]]
                for e in errs:
                    errors.append({
                        "attempt": attempt,
                        "status": r.get("status", ""),
                        "message": strip_ansi(e.get("message") or e.get("value") or ""),
                        "stack": strip_ansi(e.get("stack", "")),
                        "snippet": strip_ansi(e.get("snippet", "")),
                        "location": e.get("location"),
                    })
                if r.get("status") in ("failed", "timedOut", "interrupted") and not errs:
                    errors.append({"attempt": attempt, "status": r.get("status"), "message": f"Attempt {r.get('status')} with no error message", "stack": "", "snippet": ""})
                for a in r.get("attachments", []) or []:
                    if a.get("path"):
                        artifacts.append({"attempt": attempt, "name": a.get("name", ""),
                                          "contentType": a.get("contentType", ""), "path": a["path"]})
            outcome = _outcome(test)
            rec = TestRecord(
                test_id=spec.get("id", ""),
                title=spec.get("title", ""),
                full_title=" > ".join(t for t in titles if t),
                file=spec_file(spec, root_file),
                line=spec.get("line"),
                project=test.get("projectName") or test.get("projectId") or "",
                case_id=_case_id(spec, test),
                tag_ids=_tag_ids(spec, test),
                spec_tags=list(spec.get("tags") or []),
                tags=list(dict.fromkeys((spec.get("tags") or []) + (test.get("tags") or []))),
                outcome=outcome,
                attempts=len(results),
                duration_ms=int(sum(r.get("duration", 0) or 0 for r in results)),
                errors=errors,
                artifacts=artifacts,
            )
            rec.fixme_reasons = list(dict.fromkeys(str(a.get("description")) for a in (test.get("annotations") or [])
                                                   if str(a.get("type", "")).lower() in ("fixme", "skip", "fail")
                                                   and a.get("description")))
            # a run-time annotation sits on the test or on its last result, depending on Playwright's version
            notes = list(test.get("annotations") or []) + [a for r in results[-1:] for a in (r.get("annotations") or [])]
            rec.not_applicable = next((str(a.get("description")) for a in notes
                                       if str(a.get("type", "")).lower() == "not-applicable" and a.get("description")), None)
            rec.owner = next((str(a.get("description")) for a in (test.get("annotations") or [])
                              if str(a.get("type", "")).lower() == "owner" and a.get("description")), None)
            if outcome in ("failed", "flaky") and errors:
                failed_errors = [e for e in errors if e["status"] != "passed"] or errors
                rec.classification = classify_errors(failed_errors)
            elif outcome == "failed":
                rec.classification = Classification("unclassified", 0.0, {c: 0.0 for c in CLASSES},
                                                    ["Test failed but report has no error text"], False, True)
            records.append(rec)
    return records


# --------------------------------------------------------------------------- case risk (tests/cases/*.yaml)

def _minimal_yaml_cases(text: str) -> list[dict]:
    """Very small fallback when PyYAML is absent: pulls id/title/risk scalars.

    Handles 'id: X', 'case_id: X', 'risk: high', 'risk_level: high' and the
    nested form 'risk:\\n  level: high' (also rating/score).  A new id starts a new case.
    """
    cases, cur, pending_risk_block = [], None, False
    for raw in text.splitlines():
        line = raw.split(" #")[0].rstrip()
        if not line.strip() or line.strip().startswith("#"):
            continue
        m = re.match(r"^\s*-?\s*([A-Za-z_]+)\s*:\s*(.*)$", line)
        if not m:
            continue
        key, val = m.group(1).lower(), m.group(2).strip().strip("'\"")
        if key in ("id", "case_id", "caseid", "test_id") and val:
            cur = {"id": val}
            cases.append(cur)
            pending_risk_block = False
        elif cur is None:
            continue
        elif key in ("risk", "risk_level", "risklevel", "risk_rating") :
            if val and not val.startswith(("{", "[")):
                cur["risk"] = val
                pending_risk_block = False
            elif val.startswith("{"):
                mm = re.search(r"(level|rating|value)\s*:\s*([\w\- ]+)", val)
                if mm:
                    cur["risk"] = mm.group(2).strip()
            else:
                pending_risk_block = True
        elif pending_risk_block and key in ("level", "rating", "value", "overall", "score"):
            cur["risk"] = val
            pending_risk_block = False
        elif key in ("title", "name") and "title" not in cur:
            cur["title"] = val
    return cases


def _risk_from_obj(r):
    if isinstance(r, dict):
        for k in ("level", "rating", "value", "overall", "score"):
            if k in r:
                return r[k]
        return None
    return r


def load_case_risks(cases_dir: str | Path) -> dict[str, dict]:
    """Return {case_id: {'risk': str, 'title': str, 'file': str}} from tests/cases/*.yaml|yml."""
    out: dict[str, dict] = {}
    d = Path(cases_dir)
    if not d.is_dir():
        return out
    try:
        import yaml  # type: ignore
    except Exception:  # pragma: no cover - depends on env
        yaml = None
    for f in sorted(list(d.rglob("*.yaml")) + list(d.rglob("*.yml"))):
        text = f.read_text(encoding="utf-8", errors="replace")
        cases: list[dict] = []
        if yaml is not None:
            try:
                for doc in yaml.safe_load_all(text):
                    items = doc if isinstance(doc, list) else (doc.get("cases") or doc.get("tests") or [doc]) if isinstance(doc, dict) else []
                    for it in items:
                        if isinstance(it, dict):
                            cid = it.get("id") or it.get("case_id") or it.get("caseId")
                            if cid:
                                risk = _risk_from_obj(it.get("risk", it.get("risk_level")))
                                cases.append({"id": str(cid), "risk": None if risk is None else str(risk),
                                              "title": it.get("title") or it.get("name") or ""})
            except Exception:
                cases = _minimal_yaml_cases(text)
        else:
            cases = _minimal_yaml_cases(text)
        for c in cases:
            out[c["id"]] = {"risk": c.get("risk"), "title": c.get("title", ""), "file": str(f)}
    return out


def attach_risk(records: list[TestRecord], case_risks: dict[str, dict]) -> None:
    for r in records:
        if r.case_id and r.case_id in case_risks:
            r.risk = case_risks[r.case_id].get("risk")
        else:
            for t in r.tags:  # fallback: @risk-high / @risk:high / @high-risk tags
                m = re.match(r"@?(?:risk[:=_-](\w+)|(\w+)[-_]risk)$", str(t), re.I)
                if m:
                    r.risk = m.group(1) or m.group(2)
                    break


def triage(results_path: str | Path, cases_dir: str | Path | None = None) -> dict:
    data = load_report(results_path)
    records = parse_report(data)
    case_risks = load_case_risks(cases_dir) if cases_dir else {}
    attach_risk(records, case_risks)
    cfg = data.get("config", {}) or {}
    return {
        "source": str(results_path),
        "playwright_version": cfg.get("version"),
        "base_urls": sorted({(p.get("use") or {}).get("baseURL") for p in cfg.get("projects", []) or []
                             if (p.get("use") or {}).get("baseURL")}),
        "stats": data.get("stats", {}),
        "run_errors": [strip_ansi(e.get("message", "")) for e in data.get("errors", []) or []],
        "case_risks": case_risks,
        "records": [r.to_dict() for r in records],
    }


def main(argv=None) -> int:
    import argparse
    ap = argparse.ArgumentParser(description="Classify Playwright failures (UI change / data / timing / environment / real defect).")
    ap.add_argument("results", help="Playwright JSON reporter file (results.json)")
    ap.add_argument("--cases-dir", default=None, help="tests/cases directory with *.yaml (for risk)")
    ap.add_argument("-o", "--out", default="-", help="write triage JSON here (default stdout)")
    a = ap.parse_args(argv)
    out = triage(a.results, a.cases_dir)
    s = json.dumps(out, indent=2, default=str)
    if a.out == "-":
        print(s)
    else:
        Path(a.out).parent.mkdir(parents=True, exist_ok=True)
        Path(a.out).write_text(s, encoding="utf-8")
    return 0


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