File size: 26,899 Bytes
51eaa60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""RB TestGen Kit (macOS/AX port of the Linux v7.5 kit) — a test's NAVIGATION
DEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded, and
self-auditable.

DIFFERENCE FROM LINUX: macOS tests are **pytest** (methods on Test* classes taking
the `ax` fixture, plain asserts) — NOT standalone scripts calling R.record(). So the
DECLARATION is a pytest marker on the test method:

    import rb_testgen_kit as kit

    @pytest.mark.rb(depth=1, jump_kind="reach", expect="Preferences window visible")
    def test_prefs_opens(self, ax_with_reset):
        before = kit.rb_showing(ax_with_reset)
        helpers.rb_reach_prefs(ax_with_reset)      # a nav helper you name rb_reach_* / rb_enter_*
        after = kit.rb_showing(ax_with_reset)
        assert kit.rb_reach(before, after, target="Preferences", source="menu bar")

conftest.py's pytest_runtest_makereport hook reads the marker + the test outcome and
writes {name, passed, depth, jump_kind, tier, expect} so the runner can fold it into
<module>_results.json. The audits below then read those records (+ the test SOURCE).

jump_kind (verbatim strings — the audit/stats key off them):
  "none"        no trigger; existence/structure only            -> tier 0
  "liveness"    only "did not crash / still alive"               -> tier 1 (weak; avoid)
  "reach"       a real surface jump: the TARGET surface's element
                APPEARED and the SOURCE surface's element DISAPPEARED -> tier 2
  "transition"  a state flip (CHECKED/ENABLED/mode) before->after -> tier 2
  "value"       a specific expected value/content was asserted    -> tier 3

DEPTH is the number of surfaces crossed before the assertion (0 = home/first screen,
1 = one dialog/panel/submenu, 2+ = deeper). A flat-tree read of a deep element is
depth 0 — depth counts surfaces the test actually navigated through.

REACH PROOF (so "reach" cannot be faked by reading a flat tree):
    before = rb_showing(ax)
    <trigger: click the menu item / status item>
    after  = rb_showing(ax)
    ok = rb_reach(before, after, target="Preferences", source="menu bar")

SELF-AUDIT (report-only — goals, NOT a hard gate on finalize):
    python3 -c "import rb_testgen_kit as k; k.rb_audit('<results_dir>')"
    python3 -c "import rb_testgen_kit as k; k.rb_lint('<results_dir>')"
    python3 -c "import rb_testgen_kit as k; k.rb_lint_sources('<testgen_dir>')"
    python3 -c "import rb_testgen_kit as k; k.rb_audit_depth('<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.
QUOTAS = {
    "existence_max": 0.30,    # jump_kind=="none" share of ALL tests
    "interactive_min": 0.60,  # reach|transition|value share of ALL tests
    "depth_ge1_min": 0.40,    # depth>=1 share of INTERACTIVE tests
    "depth_ge2_min": 0.10,    # depth>=2 share of INTERACTIVE tests
    "value_min": 0.25,        # jump_kind=="value" share of INTERACTIVE tests
}

# Depth family: a test "crosses a surface" iff it calls a member of the depth family.
# macOS accepts BOTH the naming convention rb_enter_*/rb_reach_* (write your own nav
# helper and NAME it so) AND the existing verifier_helpers/ax_helpers navigation
# functions (whitelist below) — so tests can reuse the mature reveal/navigate helpers.
DEPTH_FWD_RE = re.compile(r"^rb_(enter|reach)[a-z0-9_]*$")
DEPTH_BACK_RE = re.compile(r"^rb_back[a-z0-9_]*$")
# verifier_helpers / ax_helpers navigation functions that OPEN or move to a new surface.
FWD_WHITELIST = {
    "ensure_ui_visible", "ensure_panel_open", "open_actions_menu", "open_menu",
    "open_settings", "open_preferences", "open_dialog", "open_panel", "open_window",
    "navigate_month", "navigate", "switch_tab", "switch_mode", "switch_page",
    "select_tab", "reveal_window", "show_panel", "show_menu",
}
BACK_WHITELIST = {
    "dismiss_menus", "dismiss_panel", "dismiss_any_dialog", "close_panel",
    "close_window", "go_back",
}
# pytest fixtures that themselves navigate into a surface during setup (so a test taking
# one legitimately has depth>=1 without a nav call in its own body). `ax` does NOT navigate.
_NAV_FIXTURES = {"ax_with_reset", "open_panel"}
# MEASURED-TIER verdict families (ported from keliang): a tier2/3 jump_kind must be BACKED
# by its verdict function — transition->rb_flip*, value->rb_value*, reach->rb_reach* — whose
# bool result is the test's assertion. Self-named wrappers count by prefix.
TIER_FLIP_RE = re.compile(r"^rb_flip[a-z0-9_]*$")
TIER_VALUE_RE = re.compile(r"^rb_value[a-z0-9_]*$")
_JK_FAMILY = {"transition": "flip", "value": "value", "reach": "reach"}
# normalize plural (v73prep) / singular 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/panel/submenu)."""
    global _DEPTH
    _DEPTH += 1
    return _DEPTH


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


def _walk_tree_nodes(node, out, seen):
    """Yield 'role|name' for a macOS AXHelper.tree() dict node (+children)."""
    if not isinstance(node, dict) or seen[0] >= 8000:
        return
    seen[0] += 1
    role = str(node.get("role") or "")
    name = str(node.get("name") or node.get("value") or "")
    if role or name:
        out.add(f"{role}|{name}")
    for c in (node.get("children") or []):
        _walk_tree_nodes(c, out, seen)


def rb_showing(ax, max_depth: int = 12) -> set:
    """Snapshot the currently-reachable AX subtree under the app as {"role|name"}.
    macOS AX has no AT-SPI SHOWING/VISIBLE state, so we approximate "showing" by the
    live AX tree (AXChildren) the app currently exposes — a new window/sheet/popover
    adds its elements; a dismissed one removes them. Feed before+after a trigger to
    rb_reach() so a 'reach' test proves a REAL surface change, not a flat-tree read.
    Safe no-op (empty set) if `ax` cannot produce a tree."""
    out: set = set()
    try:
        tree = ax.tree(max_depth=max_depth)  # AXHelper.tree() -> nested dict
    except Exception:
        return out
    _walk_tree_nodes(tree, out, [0])
    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 surface jump from reading an element that was always there."""
    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 bool
    as the test's assertion. Does NOT touch depth — an in-page flip is 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 bool as the test's assertion. Tolerant: exact match,
    else the stringified `expected` appears in the stringified `observed` (mirrors rb_reach's
    tolerant match). Does NOT touch depth. You MAY write your own `rb_value_<what>()` wrapper."""
    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


def rb_connect(app_name: str | None = None, wait_for_ready: bool = False):
    """PORTABLE app acquisition for STANDALONE use — attach BY NAME to the running app
    via AXHelper (never spawn, never hardcode the install path), so the SAME test drives
    the reference AND the recreation. In normal pytest runs the `ax` fixture already does
    this; use rb_connect only for a script run outside pytest. Returns an AXHelper or None."""
    try:
        from ax_helpers import AXHelper
    except Exception:
        return None
    name = (app_name or os.environ.get("APP_NAME") or "").strip()
    if not name:
        return None
    try:
        return AXHelper(name, wait_for_ready=wait_for_ready)
    except Exception:
        return None


class RBResults:
    """Optional standalone recorder (parity with the Linux kit). In pytest mode the
    conftest hook records depth/jump instead; keep this for scripts that self-run."""

    def __init__(self, module: str, results_dir: str):
        self.module = module
        self.results_dir = results_dir
        self.tests: list[dict] = []
        rb_reset_depth()

    def record(self, name: str, passed, *, depth: int | None = None,
               jump_kind: str = "none", expect: str = "", msg: str = "") -> None:
        if jump_kind not in JUMP_KINDS:
            jump_kind = "none"
        d = _DEPTH if depth is None else int(depth)
        p = bool(passed)
        self.tests.append({
            "name": name, "passed": p, "status": "passed" if p else "failed",
            "depth": max(0, d), "jump_kind": jump_kind, "tier": tier_of(jump_kind),
            "expect": str(expect), "message": str(msg),
        })
        self._flush()

    def _flush(self) -> None:
        payload = {"module": self.module, "tests": self.tests,
                   "passed": sum(1 for t in self.tests if t["passed"]),
                   "total": len(self.tests)}
        for p in (os.path.join(self.results_dir, self.module, f"{self.module}_results.json"),
                  os.path.join(self.results_dir, f"{self.module}_results.json")):
            try:
                os.makedirs(os.path.dirname(p), exist_ok=True)
                with open(p, "w") as f:
                    json.dump(payload, f, indent=2)
            except Exception:
                pass


def _load_all(results_dir: str) -> list[dict]:
    """Every per-test record under results_dir (module subdirs included)."""
    recs: list[dict] = []
    seen_files = set()
    for pat in (os.path.join(results_dir, "*_results.json"),
                os.path.join(results_dir, "*", "*_results.json"),
                os.path.join(results_dir, "results", "*_results.json")):
        for path in glob.glob(pat):
            key = os.path.relpath(path, results_dir)
            if key in seen_files or os.path.basename(path) == "baseline_results.json":
                continue
            seen_files.add(key)
            try:
                data = json.load(open(path))
            except Exception:
                continue
            for t in (data.get("tests", []) if isinstance(data, dict) else []):
                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 and check the double-axis quotas. Prints
    PASS/GAP per quota so the orchestrator can target its Improve round. REPORT-ONLY."""
    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) or 0) >= 1)
    d2 = sum(1 for r in inter if int(r.get("depth", 0) or 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 — try a deeper reach/value test, or finalize (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}


def rb_lint(results_dir: str) -> list:
    """Flag weak/inconsistent declarations: reach/transition/value with empty expect,
    liveness (tier1), unknown jump_kind, negative depth. Prints + 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) or 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) but break on the
# recreation (eval, app at a different path). Each is a hard portability defect on macOS.
_BAD_SOURCE_PATTERNS = [
    (r"\.pipeline_refapp|/pipeline_work/",
     "names a pipeline-internal reference path (gone/locked at eval) — attach via the ax fixture / rb_connect()"),
    (r"/workspace/output/recreation|/var/tmp/pipeline_results",
     "names an eval-only / pipeline path — a test must not know where the app is installed"),
    (r"defaults['\"\s,]+write",
     "seeds app state via `defaults write` — the recreation may use a different bundle id / defaults; drive state via the GUI"),
    (r"open\s+-a\s+[\"']?[A-Z]",
     "launches the app by a hardcoded name via `open -a` — use the ax fixture (host launches the app)"),
    (r"subprocess\.(?:Popen|run|call)\([^)]*[\"'][^\"']*/(?:Applications|Users|usr|bin|var)/",
     "spawns the app by an absolute path — attach to the launched instance via the ax fixture / rb_connect()"),
    (r"AXUIElementCreateApplication\(",
     "creates an AX app handle directly (usually a hardcoded pid/path) — use the ax fixture so the SAME test drives reference AND recreation"),
]


def rb_lint_sources(testgen_dir: str) -> list:
    """Scan authored test/helper .py for NON-PORTABLE patterns (pipeline paths, defaults
    seeding, absolute-path spawn, direct AX app creation) — so the suite drives the
    recreation, not just the reference. REPORT-ONLY. Skips the kit/runner/helper libs."""
    _SKIP = ("rb_testgen_kit.py", "run_ax_tests.py", "ax_test_runner.py",
             "ax_helpers.py", "verifier_helpers.py", "conftest.py", "verifier_template.py",
             "verifier_lint.py", "lint.py", "prune_failing_tests.py", "vlm_judge.py")
    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 _SKIP]
    issues = []
    for p in py:
        base = os.path.basename(p)
        try:
            src = open(p, errors="replace").read()
        except Exception:
            continue
        for pat, why in _BAD_SOURCE_PATTERNS:
            if re.search(pat, src):
                issues.append(f"{base}: {why}")
    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 cross-check (report-only): does the SOURCE back the DECLARED depth? ──
# macOS tests are pytest: declaration is a `@pytest.mark.rb(depth=, jump_kind=)` decorator
# on a Test* class method. A method with declared depth>=1 or jump_kind="reach" must call a
# depth-family member (rb_enter*/rb_reach* OR a whitelisted nav helper) directly, in a
# file-local helper it calls, or in an imported helper — else it is FAKE depth.
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 _is_fwd(cn: str) -> bool:
    return bool(DEPTH_FWD_RE.match(cn)) or cn in FWD_WHITELIST


def _depth_calls(fn_node, local_funcs, budget: int = 2, seen=None):
    """(n_fwd, n_reach): depth-family forward calls in fn_node, descending up to `budget`
    levels into file-local functions it calls. Cycle-guarded. A LOWER BOUND on surfaces."""
    seen = seen if seen is not None else set()
    n_fwd = n_reach = 0
    for node in ast.walk(fn_node):
        if not isinstance(node, ast.Call):
            continue
        cn = _ast_call_name(node)
        if _is_fwd(cn):
            n_fwd += 1
            if cn.startswith("rb_reach"):
                n_reach += 1
        elif budget > 0 and cn in local_funcs and cn not in seen:
            seen.add(cn)
            f, r = _depth_calls(local_funcs[cn], local_funcs, budget - 1, seen)
            n_fwd += f
            n_reach += r
    return n_fwd, n_reach


def _rb_marker(fn_node):
    """(depth, jump_kind) from a @pytest.mark.rb(...) decorator on a test method, else None."""
    for dec in getattr(fn_node, "decorator_list", []):
        if not isinstance(dec, ast.Call):
            continue
        if _ast_call_name(dec) != "rb":
            continue
        depth, jk = 0, "none"
        for kw in dec.keywords:
            if kw.arg == "depth" and isinstance(kw.value, ast.Constant):
                try:
                    depth = int(kw.value.value)
                except Exception:
                    depth = 0
            elif kw.arg == "jump_kind" and isinstance(kw.value, ast.Constant):
                jk = str(kw.value.value)
        return depth, jk
    return None


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 each @pytest.mark.rb(...) marker — so a test can't just TYPE depth=2.
    REPORT-ONLY: flags a declared depth>=1 or jump_kind="reach" whose method (and the local
    helpers it calls) has NO depth-family call (rb_enter*/rb_reach* or a whitelisted nav
    helper). Fix = add the nav helper you used (or name it rb_enter_*/rb_reach_*), or lower
    the declared depth. depth-only; jump verdicts are a later phase."""
    issues = []
    pys = sorted(glob.glob(os.path.join(testgen_dir, "test_ax_*.py"))
                 + glob.glob(os.path.join(testgen_dir, "tests", "test_ax_*.py")))
    for p in pys:
        try:
            src = open(p, errors="replace").read()
            tree = ast.parse(src)
        except Exception:
            continue
        mod = os.path.basename(p)[len("test_ax_"):-len(".py")]
        local_funcs = {n.name: n for n in ast.walk(tree)
                       if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))}
        for node in ast.walk(tree):
            if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
                continue
            if not node.name.startswith("test_"):
                continue
            marker = _rb_marker(node)
            if marker is None:
                continue
            depth, jk = marker
            if not (depth >= 1 or jk == "reach"):
                continue
            # A method is "backed" iff IT (or a file-local helper it calls) makes a
            # depth-family call, OR it takes a navigating fixture (ax_with_reset opens a
            # panel in its setup). We DELIBERATELY do NOT fall back to file-level backing
            # — that would let a fake-depth method ride on another test's nav call.
            params = {a.arg for a in node.args.args}
            fixture_nav = bool(params & _NAV_FIXTURES)
            n_fwd, n_reach = _depth_calls(node, local_funcs)
            if n_fwd == 0 and not fixture_nav:
                issues.append(f"{mod}:{node.name}: declared depth={depth}/jump_kind={jk} but NO "
                              f"backing rb_enter*/rb_reach*/nav-helper call (fake depth)")
            elif jk == "reach" and n_reach == 0 and not fixture_nav:
                issues.append(f"{mod}:{node.name}: jump_kind=reach but no rb_reach* proof call "
                              f"(use kit.rb_reach(before,after,...) to prove the surface jump)")
    if issues:
        print(f"[rb_audit_depth] {len(issues)} fake-depth issue(s) (REPORT-ONLY — add the "
              f"rb_reach/rb_enter/nav-helper 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)")
    return issues


def _tier_calls(fn_node, local_funcs, budget: int = 2, seen=None):
    """Set of verdict families {'flip','value','reach'} called in fn_node, descending up to
    `budget` levels into file-local helpers it calls. Cycle-guarded. Mirrors _depth_calls —
    self-named wrappers (rb_flip_*/rb_value_*/rb_reach_*) count by prefix."""
    seen = seen if seen is not None else set()
    fams = set()
    for node in ast.walk(fn_node):
        if not isinstance(node, ast.Call):
            continue
        cn = _ast_call_name(node)
        if TIER_FLIP_RE.match(cn):
            fams.add("flip")
        elif TIER_VALUE_RE.match(cn):
            fams.add("value")
        elif cn.startswith("rb_reach"):
            fams.add("reach")
        elif budget > 0 and cn in local_funcs and cn not in seen:
            seen.add(cn)
            fams |= _tier_calls(local_funcs[cn], local_funcs, budget - 1, seen)
    return fams


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 in
    each @pytest.mark.rb(...) marker — so a test can't just TYPE jump_kind="value". REPORT-ONLY
    (NOT a finalize gate). A tier2/3 claim must be backed by its verdict call: transition->rb_flip*,
    value->rb_value* (reach->rb_reach* is already covered by rb_audit_depth). Flags a declared
    transition/value whose method (and the local helpers it calls) has NO such verdict call.
    Fix = add rb_flip(before,after)/rb_value(observed,expected) and pass its result as the assert,
    or drop to a weaker jump_kind you can prove. Pytest-marker form (mirrors rb_audit_depth),
    NOT keliang's record() form."""
    issues = []
    pys = sorted(glob.glob(os.path.join(testgen_dir, "test_ax_*.py"))
                 + glob.glob(os.path.join(testgen_dir, "tests", "test_ax_*.py")))
    for p in pys:
        try:
            src = open(p, errors="replace").read()
            tree = ast.parse(src)
        except Exception:
            continue
        mod = os.path.basename(p)[len("test_ax_"):-len(".py")]
        local_funcs = {n.name: n for n in ast.walk(tree)
                       if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))}
        for node in ast.walk(tree):
            if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
                continue
            if not node.name.startswith("test_"):
                continue
            marker = _rb_marker(node)
            if marker is None:
                continue
            _depth, jk = marker
            fam = _JK_FAMILY.get(jk)
            if fam is None or jk == "reach":   # none/liveness need no verdict; reach->rb_audit_depth
                continue
            fams = _tier_calls(node, local_funcs)
            if fam not in fams:
                issues.append(f"{mod}:{node.name}: declared jump_kind={jk} (tier {tier_of(jk)}) but "
                              f"NO backing rb_{fam}* verdict call — unbacked tier")
    if issues:
        print(f"[rb_audit_tier] {len(issues)} unbacked-tier issue(s) (REPORT-ONLY — back a "
              f"transition with rb_flip(before,after) and a value with rb_value(observed,expected), "
              f"passing its result as the assertion; or drop to a jump_kind you can 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]}")