File size: 27,635 Bytes
598838a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""RB TestGen Kit — depth/jump audit, verdict helpers, and portability lint.

LOCATION ON THE VM: deployed read-only to the testgen output dir.
(NEVER edit; `import rb_testgen_kit` or `from rb_uia import rb_showing, rb_reach, ...`)

Tests use pytest format with @pytest.mark.rb() markers. The conftest.py handles
result collection automatically. This kit provides:
  - Verdict helpers: rb_showing, rb_reach, rb_flip, rb_value
  - Depth tracking: rb_enter, rb_back (used by the `rb` fixture)
  - Self-audit: rb_audit, rb_lint, rb_lint_sources, rb_audit_depth, rb_audit_tier

PYTEST TEST FORMAT:
    @pytest.mark.rb(jump_kind="reach", expect="Preferences dialog visible")
    def test_prefs_opens(app, rb):
        rb.enter("prefs")
        before = rb_showing(app)
        # ... trigger ...
        after = rb_showing(app)
        assert rb_reach(before, after, target="Preferences", source="toolbar")

VERDICT HELPERS (prove the jump kind — a bare `assert True` is unbacked):
    rb_reach(before, after, target, source) — tier2 reach (surface jump)
    rb_flip(before, after)                  — tier2 transition (state flip)
    rb_value(observed, expected)            — tier3 value (specific content)

SELF-AUDIT (report-only, NOT a hard gate):
    python -c "import rb_testgen_kit as k; k.rb_audit('<results_dir>')"
    python -c "import rb_testgen_kit as k; k.rb_audit_depth('<testgen_dir>','<results_dir>')"
    python -c "import rb_testgen_kit as k; k.rb_audit_tier('<testgen_dir>','<results_dir>')"
"""
from __future__ import annotations

import ast
import glob
import json
import os
import re

JUMP_KINDS = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3}

# Double-axis quota TARGETS (fractions) — goals rb_audit REPORTS, NOT a hard gate. Tune here only.
QUOTAS = {
    "existence_max": 0.30,    # jump_kind=="none" share of ALL tests           (structure gate)
    "interactive_min": 0.60,  # reach|transition|value share of ALL tests
    "depth_ge1_min": 0.40,    # depth>=1 share of INTERACTIVE tests            (real navigation)
    "depth_ge2_min": 0.10,    # depth>=2 share of INTERACTIVE tests            (deep chains)
    "value_min": 0.25,        # jump_kind=="value" share of INTERACTIVE tests  (tier3 strength)
}

# Depth family (naming convention) — see rb_audit_depth. A test "crosses a surface" iff it
# calls a member of the depth family; rb_back* pops one. Semantic aliases (rb_enter_dialog,
# rb_reach_prefs) are matched BY PREFIX so the kit stays small and testcases stay diverse.
DEPTH_FWD_RE = re.compile(r"^rb_(enter|reach)[a-z0-9_]*$")   # forward crossing / proven jump
DEPTH_BACK_RE = re.compile(r"^rb_back[a-z0-9_]*$")           # pop a surface
DEPTH_RESET_RE = re.compile(r"^rb_reset_depth$")
# Verdict family (tier audit): a tier2/3 claim must be backed by its verdict function.
# rb_reach* is counted by rb_audit_depth; rb_flip* and rb_value* are counted here.
VERDICT_RE = re.compile(r"^rb_(reach|flip|value)[a-z0-9_]*$")
_JK_FAMILY = {"reach": "reach", "transition": "flip", "value": "value"}
# normalize plural (v73prep) / singular (kltg74) module names so a JSON module ("button")
# and a file stem ("buttons") join.
_MODULE_ALIAS = {"menus": "menu", "buttons": "button", "states": "state",
                 "structures": "structure", "texts": "text",
                 "computations": "computation", "workflows": "workflow"}

_DEPTH = 0  # module-global surface counter for rb_enter/rb_back


def tier_of(jump_kind: str) -> int:
    return JUMP_KINDS.get(jump_kind, 2)


def rb_reset_depth() -> None:
    global _DEPTH
    _DEPTH = 0


def rb_enter(_surface: str = "") -> int:
    """Call right after your test navigates into a new surface (dialog/page/submenu)."""
    global _DEPTH
    _DEPTH += 1
    return _DEPTH


def rb_back() -> int:
    global _DEPTH
    _DEPTH = max(0, _DEPTH - 1)
    return _DEPTH


def rb_showing(root) -> set:
    """Snapshot visible UIA elements under root as {"control_type|name", ...}.
    Safe no-op ({}) if pywinauto is unavailable or root is None."""
    out = set()
    if root is None:
        return out
    try:
        seen = 0
        for el in root.descendants():
            seen += 1
            if seen > 6000:
                break
            try:
                if not el.is_visible():
                    continue
                ct = el.element_info.control_type or ""
                nm = el.element_info.name or ""
                out.add(f"{ct}|{nm}")
            except Exception:
                pass
    except Exception:
        pass
    return out


def rb_reach(before, after, target: str, source: str | None = None) -> bool:
    """True-jump verdict: the TARGET surface's discriminating element newly APPEARED
    AND (if given) the SOURCE surface's discriminating element DISAPPEARED. This is
    what separates a real page jump from reading an element that was always in the tree."""
    before = set(before or [])
    after = set(after or [])
    t = target.lower()
    appeared = any(t in k.lower() for k in (after - before))
    if source is None:
        return appeared
    s = source.lower()
    src_before = any(s in k.lower() for k in before)
    src_after = any(s in k.lower() for k in after)
    return appeared and src_before and not src_after


def rb_flip(before, after, expect: str = "") -> bool:
    """In-page STATE-FLIP verdict (tier2 `transition`): the observed state actually CHANGED
    before->after (a CHECKED/ENABLED/mode/selection value read the two times). Pass its return
    as record()'s `passed`. Does NOT touch depth — a flip is in-page (declare depth=0 unless you
    navigated a surface to reach the control). You MAY write your own `rb_flip_<what>()` wrapper."""
    try:
        return before != after
    except Exception:
        return False


def rb_value(observed, expected) -> bool:
    """VALUE verdict (tier3 `value`): a specific expected value/content matched what you OBSERVED
    on the reference. Pass its return as record()'s `passed`. Tolerant: exact match, else the
    stringified `expected` appears in the stringified `observed` (substring/normalized), mirroring
    rb_reach's tolerant match. Does NOT touch depth. You MAY write your own `rb_value_<what>()`."""
    if observed is None:
        return False
    if observed == expected:
        return True
    try:
        return bool(str(expected)) and str(expected) in str(observed)
    except Exception:
        return False


# NOTE: rb_connect() and RBResults have been removed — replaced by:
#   - rb_uia.get_app() for app acquisition (used by conftest.py's `app` fixture)
#   - conftest.py's pytest hooks for automatic result collection
# Tests now use pytest format: `def test_*(app, rb):` with `@pytest.mark.rb(...)`


def _load_all(results_dir: str) -> list[dict]:
    recs: list[dict] = []
    seen_files = set()
    for pat in (os.path.join(results_dir, "*_results.json"),
                os.path.join(results_dir, "results", "*_results.json")):
        for path in glob.glob(pat):
            base = os.path.basename(path)
            if base in seen_files:
                continue
            seen_files.add(base)
            try:
                data = json.load(open(path))
            except Exception:
                continue
            for t in data.get("tests", []):
                if isinstance(t, dict) and "name" in t:
                    recs.append(t)
    return recs


def rb_audit(results_dir: str, quotas: dict | None = None) -> dict:
    """Aggregate declared depth/jump_kind across a suite and check the double-axis
    quotas. Prints PASS/FAIL per quota with the concrete gap (how many tests to add),
    so the orchestrator can target its Improve round. Call BEFORE finalizing."""
    q = quotas or QUOTAS
    recs = _load_all(results_dir)
    n = len(recs)
    if not n:
        print(f"[rb_audit] no records under {results_dir}")
        return {"total": 0}
    kinds = [r.get("jump_kind", "none") for r in recs]
    none_n = sum(1 for k in kinds if k == "none")
    live_n = sum(1 for k in kinds if k == "liveness")
    inter = [r for r in recs if r.get("jump_kind") in ("reach", "transition", "value")]
    ni = len(inter) or 1
    d1 = sum(1 for r in inter if int(r.get("depth", 0)) >= 1)
    d2 = sum(1 for r in inter if int(r.get("depth", 0)) >= 2)
    val = sum(1 for r in inter if r.get("jump_kind") == "value")

    def line(label, got, need, kind):
        ok = got >= need if kind == "min" else got <= need
        return (ok, f"  [{'ok ' if ok else 'GAP'}] {label}: {got:.0%} "
                    f"({'≥' if kind=='min' else '≤'} {need:.0%})")

    checks = [
        line("existence(none)/all", none_n / n, q["existence_max"], "max"),
        line("interactive/all", len(inter) / n, q["interactive_min"], "min"),
        line("depth≥1 /interactive", d1 / ni, q["depth_ge1_min"], "min"),
        line("depth≥2 /interactive", d2 / ni, q["depth_ge2_min"], "min"),
        line("value(tier3)/interactive", val / ni, q["value_min"], "min"),
    ]
    print(f"[rb_audit] {results_dir}  total={n}  interactive={len(inter)}  "
          f"none={none_n} liveness={live_n} depth≥1={d1} depth≥2={d2} value={val}")
    for _ok, msg in checks:
        print(msg)
    passed = all(ok for ok, _ in checks)
    print(f"[rb_audit] {'ALL TARGETS MET' if passed else 'some targets below — OPTIONALLY add a deeper reach/value test, or finalize if you have already tried enough angles (these are goals, NOT a hard gate)'}")
    return {"total": n, "interactive": len(inter), "none": none_n, "liveness": live_n,
            "depth_ge1": d1, "depth_ge2": d2, "value": val,
            "passed": passed, "checks": [m for _o, m in checks]}


def rb_lint(results_dir: str) -> list:
    """Flag weak/inconsistent declarations: missing expect on a value/transition/reach
    test, unknown jump_kind, or negative depth. Prints and returns the issues."""
    recs = _load_all(results_dir)
    issues = []
    for r in recs:
        jk = r.get("jump_kind", "none")
        nm = r.get("name", "?")
        if jk not in JUMP_KINDS:
            issues.append(f"{nm}: unknown jump_kind {jk!r}")
        if jk in ("reach", "transition", "value") and not str(r.get("expect", "")).strip():
            issues.append(f"{nm}: jump_kind={jk} but empty expect (declare the specific observed target)")
        if jk == "liveness":
            issues.append(f"{nm}: liveness is tier1 — replace with the app-authored effect you can observe")
        if int(r.get("depth", 0)) < 0:
            issues.append(f"{nm}: negative depth")
    if issues:
        print(f"[rb_lint] {len(issues)} issue(s):")
        for i in issues:
            print("  - " + i)
    else:
        print("[rb_lint] no issues")
    return issues


# Non-portable source patterns: pass on the reference (testgen, app launched by runner)
# but break on the recreation (eval, app elsewhere). Each is a hard portability defect.
_BAD_SOURCE_PATTERNS = [
    (r"C:\\\\rb_pipeline|C:/rb_pipeline",
     "hardcodes the pipeline path (varies per task) — use the `app` fixture from conftest (backed by rb_uia.get_app())"),
    (r"\\\\workspace\\\\install|/workspace/install",
     "names a Linux-style install path — not applicable on Windows; use the `app` fixture from conftest"),
    (r"subprocess\.(?:Popen|run|call)\([^)]*[\"'][A-Z]:\\\\",
     "spawns the app by an absolute path — use the `app` fixture for portability"),
    (r"Application\([^)]*\)\.(?:start|connect)\([^)]*path\s*=",
     "uses pywinauto .start() or .connect(path=...) — use the `app` fixture for portability"),
]


def rb_lint_sources(testgen_dir: str) -> list:
    """Scan authored test/helper .py for NON-PORTABLE patterns (hardcoded install paths,
    self-spawn by absolute path) and for helper/test API DRIFT
    (a test calls `H.<attr>()` that the imported helper module does not define — the
    hotspot connect_running/spawn_with_file class of bug). Returns + prints the issues.
    Run BEFORE finalize; a clean result means the suite will drive the recreation, not
    just the reference."""
    import glob
    import re
    import ast
    py = [p for p in (glob.glob(os.path.join(testgen_dir, "*.py"))
                      + glob.glob(os.path.join(testgen_dir, "tests", "*.py")))
          if os.path.basename(p) not in ("rb_testgen_kit.py", "run_uia_tests.py")]
    defined: dict[str, set] = {}
    for p in py:
        mod = os.path.splitext(os.path.basename(p))[0]
        names: set = set()
        try:
            for node in ast.parse(open(p).read()).body:
                if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
                    names.add(node.name)
                elif isinstance(node, ast.Assign):
                    for t in node.targets:
                        if isinstance(t, ast.Name):
                            names.add(t.id)
        except Exception:
            pass
        defined.setdefault(mod, set()).update(names)
    issues = []
    for p in py:
        base = os.path.basename(p)
        try:
            src = open(p).read()
        except Exception:
            continue
        for pat, why in _BAD_SOURCE_PATTERNS:
            if re.search(pat, src):
                issues.append(f"{base}: {why}")
        for m in re.finditer(r"import\s+(\w+)\s+as\s+(\w+)", src):
            mod, alias = m.group(1), m.group(2)
            if mod not in defined:
                continue
            for am in re.finditer(rf"\b{alias}\.(\w+)\s*\(", src):
                attr = am.group(1)
                if attr not in defined[mod]:
                    issues.append(
                        f"{base}: calls {alias}.{attr}() but {mod}.py never defines {attr} "
                        f"(helper/test drift — the eval copy will AttributeError)")
                    break
    if issues:
        print(f"[rb_lint_sources] {len(issues)} portability issue(s):")
        for i in issues:
            print("  - " + i)
    else:
        print("[rb_lint_sources] no portability issues")
    return issues


# ── MEASURED DEPTH + TIER cross-check (report-only) ──────────────────────────
def _ast_call_name(node) -> str:
    f = node.func
    if isinstance(f, ast.Attribute):
        return f.attr
    if isinstance(f, ast.Name):
        return f.id
    return ""


def _verdict_family(cn: str) -> str:
    if cn.startswith("rb_reach"):
        return "reach"
    if cn.startswith("rb_flip"):
        return "flip"
    if cn.startswith("rb_value"):
        return "value"
    return ""


def _scan(fn_node, local_funcs, budget: int = 2, seen=None):
    """Walk fn_node (+ up to `budget` levels of file-local functions it calls; cycle-guarded)
    and return (n_fwd, n_back, n_reach, verdicts, guarded):
      DEPTH axis — n_fwd/n_back = rb_enter*|rb_reach* / rb_back* counts;
                   n_reach = the rb_reach* subset.
      TIER axis  — verdicts = verdict families present among {reach, flip, value};
                   guarded = an assert/try gates the code."""
    seen = seen if seen is not None else set()
    n_fwd = n_back = n_reach = 0
    verdicts = set()
    guarded = False
    for node in ast.walk(fn_node):
        if isinstance(node, (ast.Assert, ast.Try)):
            guarded = True
        if not isinstance(node, ast.Call):
            continue
        cn = _ast_call_name(node)
        is_fwd = bool(DEPTH_FWD_RE.match(cn))
        is_back = bool(DEPTH_BACK_RE.match(cn))
        is_verdict = bool(VERDICT_RE.match(cn))
        if is_fwd:
            n_fwd += 1
            if cn.startswith("rb_reach"):
                n_reach += 1
        elif is_back:
            n_back += 1
        if is_verdict:
            verdicts.add(_verdict_family(cn))
        if not (is_fwd or is_back or is_verdict) and budget > 0 and cn in local_funcs and cn not in seen:
            seen.add(cn)
            f, b, r, v, g = _scan(local_funcs[cn], local_funcs, budget - 1, seen)
            n_fwd += f
            n_back += b
            n_reach += r
            verdicts |= v
            guarded = guarded or g
    return n_fwd, n_back, n_reach, verdicts, guarded


def _record_name_passed(call):
    """(name, passed_node) for a record() call: name = string-literal name arg (else None);
    passed_node = AST node of the `passed` argument."""
    a = call.args
    if a and isinstance(a[0], ast.Constant) and isinstance(a[0].value, str):
        return a[0].value, (a[1] if len(a) >= 2 else None)
    if len(a) >= 2 and isinstance(a[1], ast.Constant) and isinstance(a[1].value, str):
        return a[1].value, (a[2] if len(a) >= 3 else None)
    return None, None


def _passed_form(passed_node, guarded: bool) -> str:
    """Classify record()'s `passed`: 'bare_literal', 'guarded_literal', 'derived', or 'missing'."""
    if passed_node is None:
        return "missing"
    if isinstance(passed_node, ast.Constant) and isinstance(passed_node.value, (bool, int)):
        return "guarded_literal" if guarded else "bare_literal"
    return "derived"


def _enclosing_funcs(tree):
    spans = []
    for n in ast.walk(tree):
        if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)):
            end = max((getattr(c, "lineno", n.lineno) for c in ast.walk(n)), default=n.lineno)
            spans.append((n.lineno, end, n))
    return spans


def _scope_of(line, spans):
    best = None
    for s, e, node in spans:
        if s <= line <= e and (best is None or s > best[0]):
            best = (s, e, node)
    return best[2] if best else None


def _has_depth_family(tree) -> bool:
    return any(isinstance(n, ast.Call) and DEPTH_FWD_RE.match(_ast_call_name(n))
               for n in ast.walk(tree))


def _verdict_families_in(tree) -> set:
    return {_verdict_family(_ast_call_name(n)) for n in ast.walk(tree)
            if isinstance(n, ast.Call) and VERDICT_RE.match(_ast_call_name(n))}


def _depth_backing_map(testgen_dir: str):
    """Parse the suite's test_uia_*.py (+ imported LOCAL helpers) and return
    (per_record, per_module) carrying BOTH axes' source evidence:
      per_record[(module,name)] = {measured_depth, measured_backing, n_reach,   # DEPTH axis
                                   verdicts:set, passed_form:str}               # TIER axis
      per_module[module]        = {module_backing:bool, verdict_families:set, unmatched:int}."""
    all_py = [p for p in (glob.glob(os.path.join(testgen_dir, "*.py"))
                          + glob.glob(os.path.join(testgen_dir, "tests", "*.py")))
              if os.path.basename(p) not in ("rb_testgen_kit.py", "run_uia_tests.py")]
    trees = {}
    helper_depth = {}       # stem -> bool  (imported-helper DEPTH backing)
    helper_verdicts = {}    # stem -> set   (imported-helper TIER verdicts)
    for p in all_py:
        try:
            t = ast.parse(open(p, errors="replace").read())
        except Exception:
            continue
        trees[p] = t
        stem = os.path.splitext(os.path.basename(p))[0]
        helper_depth[stem] = _has_depth_family(t)
        helper_verdicts[stem] = _verdict_families_in(t)
    per_record, per_module = {}, {}
    for p in [q for q in all_py if os.path.basename(q).startswith("test_uia_")]:
        t = trees.get(p)
        if t is None:
            continue
        stem = os.path.basename(p)[len("test_uia_"):-len(".py")]
        mod = _MODULE_ALIAS.get(stem, stem)
        local_funcs = {n.name: n for n in ast.walk(t)
                       if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))}
        spans = _enclosing_funcs(t)
        imported = set()
        for n in ast.walk(t):
            if isinstance(n, ast.Import):
                for al in n.names:
                    imported.add(al.name.split(".")[0])
            elif isinstance(n, ast.ImportFrom) and n.module:
                imported.add(n.module.split(".")[0])
        module_backing = _has_depth_family(t) or any(helper_depth.get(h) for h in imported)
        verdict_families = set(_verdict_families_in(t))
        for h in imported:
            verdict_families |= helper_verdicts.get(h, set())
        unmatched = 0
        for n in ast.walk(t):
            if not (isinstance(n, ast.Call) and _ast_call_name(n) == "record"):
                continue
            nm, passed = _record_name_passed(n)
            fn = _scope_of(n.lineno, spans) if nm is not None else None
            if nm is None or fn is None:
                unmatched += 1
                continue
            n_fwd, n_back, n_reach, verdicts, guarded = _scan(fn, local_funcs)
            measured_depth = max(0, max((n_fwd - n_reach) - n_back, 1 if n_reach >= 1 else 0))
            per_record[(mod, nm)] = {"measured_depth": measured_depth,
                                     "measured_backing": n_fwd >= 1, "n_reach": n_reach,
                                     "verdicts": verdicts,
                                     "passed_form": _passed_form(passed, guarded)}
        per_module[mod] = {"module_backing": module_backing,
                           "verdict_families": verdict_families, "unmatched": unmatched}
    return per_record, per_module


def _load_declared_by_module(results_dir: str):
    """(module, name, depth:int, jump_kind) declared records — KEEPS the module (unlike
    _load_all, whose per-test dicts drop it)."""
    out, seen = [], set()
    for pat in (os.path.join(results_dir, "*_results.json"),
                os.path.join(results_dir, "results", "*_results.json")):
        for path in glob.glob(pat):
            base = os.path.basename(path)
            if base in seen or base == "baseline_results.json":
                continue
            seen.add(base)
            try:
                data = json.load(open(path))
            except Exception:
                continue
            m = data.get("module", "") if isinstance(data, dict) else ""
            mod = _MODULE_ALIAS.get(m, m) or base[: -len("_results.json")]
            for t in (data.get("tests", []) if isinstance(data, dict) else []):
                if not (isinstance(t, dict) and "name" in t):
                    continue
                try:
                    d = int(t.get("depth", 0) or 0)
                except Exception:
                    d = 0
                out.append((mod, t["name"], d, t.get("jump_kind", "none")))
    return out


def rb_audit_depth(testgen_dir: str, results_dir: str | None = None) -> list:
    """MEASURE navigation depth from the test SOURCE (AST) and cross-check the DECLARED
    depth/jump_kind in <module>_results.json — so a test can't just TYPE depth=2. REPORT-ONLY
    (NOT a finalize gate): flags a declared depth>=1 or jump_kind="reach" that has NO backing
    call from the depth family rb_enter*/rb_reach* (directly, in a local wrapper it calls, or in
    an imported local helper). Variable-named records fall back to module-level backing so the
    wrapper/closure idiom is not false-flagged. depth-only; jump verdicts are a later phase."""
    results_dir = results_dir or testgen_dir
    per_record, per_module = _depth_backing_map(testgen_dir)
    issues = []
    for mod, name, depth, jk in _load_declared_by_module(results_dir):
        strong = depth >= 1 or jk == "reach"
        rec = per_record.get((mod, name))
        if rec is not None:
            if strong and not rec["measured_backing"]:
                issues.append(f"{mod}:{name}: declared depth={depth}/jump_kind={jk} but NO "
                              f"backing rb_enter*/rb_reach* call (fake depth)")
            elif jk == "reach" and rec["n_reach"] == 0:
                issues.append(f"{mod}:{name}: jump_kind=reach but no rb_reach* call in its code")
        elif strong and not per_module.get(mod, {}).get("module_backing", True):
            issues.append(f"{mod}:{name}: declared depth={depth}/jump_kind={jk} but the module "
                          f"has NO rb_enter*/rb_reach* call anywhere (fake depth)")
    if issues:
        print(f"[rb_audit_depth] {len(issues)} fake-depth issue(s) (REPORT-ONLY — fix by adding "
              f"the rb_reach/rb_enter you navigated with, or lower the declared depth):")
        for i in issues:
            print("  - " + i)
    else:
        print("[rb_audit_depth] no fake-depth issues (declared depth/reach backed by nav calls)")
    unm = sum(v.get("unmatched", 0) for v in per_module.values())
    if unm:
        print(f"[rb_audit_depth] note: {unm} record(s) use non-literal names "
              f"(joined at module level, not per-test)")
    return issues


def rb_audit_tier(testgen_dir: str, results_dir: str | None = None) -> list:
    """MEASURE jump RIGOR from the test SOURCE (AST) and cross-check the DECLARED jump_kind.
    REPORT-ONLY (NOT a finalize gate). A tier2/3 claim must be backed by its verdict function —
    transition->rb_flip*, value->rb_value* — AND that verdict's bool result must be the record()'s
    `passed` (a bare-literal True is unbacked). reach's rb_reach* presence is already covered by
    rb_audit_depth, so here reach is only checked for a bare-literal pass."""
    results_dir = results_dir or testgen_dir
    per_record, per_module = _depth_backing_map(testgen_dir)
    issues = []
    for mod, name, _depth, jk in _load_declared_by_module(results_dir):
        fam = _JK_FAMILY.get(jk)
        if fam is None:
            continue
        rec = per_record.get((mod, name))
        if rec is not None:
            has = fam in rec["verdicts"]
            if jk == "reach":
                if has and rec["passed_form"] == "bare_literal":
                    issues.append(f"{mod}:{name}: jump_kind=reach — rb_reach* present but the "
                                  f"pass is a bare literal True (verdict not used as the result)")
            elif not has:
                issues.append(f"{mod}:{name}: declared jump_kind={jk} (tier {tier_of(jk)}) but no "
                              f"rb_{fam}* verdict call — the tier is unbacked")
            elif rec["passed_form"] == "bare_literal":
                issues.append(f"{mod}:{name}: declared jump_kind={jk} — rb_{fam}* present but the "
                              f"pass is a bare literal True (verdict not used as the result)")
        elif jk != "reach" and fam not in per_module.get(mod, {}).get("verdict_families", set()):
            issues.append(f"{mod}:{name}: declared jump_kind={jk} but the module has no "
                          f"rb_{fam}* verdict anywhere")
    if issues:
        print(f"[rb_audit_tier] {len(issues)} unbacked-tier issue(s) (REPORT-ONLY — back a "
              f"transition with rb_flip(), a value with rb_value(), and pass its result as the "
              f"test's `passed`; or drop to a weaker jump_kind you can actually prove):")
        for i in issues:
            print("  - " + i)
    else:
        print("[rb_audit_tier] no unbacked-tier issues (transition/value backed by verdict calls)")
    return issues


if __name__ == "__main__":
    import sys
    _fns = {"audit": rb_audit, "lint": rb_lint, "lint_sources": rb_lint_sources}
    _fns2 = {"audit_depth": rb_audit_depth, "audit_tier": rb_audit_tier}
    if sys.argv[1:2] and sys.argv[1] in _fns2 and len(sys.argv) >= 3:
        _fns2[sys.argv[1]](sys.argv[2], sys.argv[3] if len(sys.argv) >= 4 else None)
    elif len(sys.argv) >= 3 and sys.argv[1] in _fns:
        _fns[sys.argv[1]](sys.argv[2])
    else:
        print("usage: rb_testgen_kit.py {audit|lint|lint_sources <dir> | "
              "{audit_depth|audit_tier} <testgen_dir> [results_dir]}")