File size: 24,257 Bytes
3fbbdd9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
conftest.py template for verifiers.

Provides fixtures: app_path, app_process, ax, ax_with_reset, open_panel.
Each test gets a fresh app instance — app is launched before and killed after every test.
"""

import json
import os
import signal
import subprocess
import tempfile
import time

import pytest


# ── RB TestGen kit: depth/jump declaration capture ──────────────────────────
# Tests declare navigation depth + jump rigor via @pytest.mark.rb(depth=, jump_kind=,
# expect=). This hook records the declaration + outcome so the runner can fold
# depth/jump/tier/expect into <module>_results.json (rb_audit/rb_lint read them).
# The record's `passed` is informational — the runner keeps pytest's exit code as the
# authoritative pass/fail, so a teardown-phase failure (e.g. app crash check) is never
# masked by a call-phase pass here.
_RB_TIER = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3}


def pytest_configure(config):
    config.addinivalue_line(
        "markers",
        "rb(depth, jump_kind, expect): declare navigation depth + jump rigor (RB TestGen kit)",
    )


@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    rep = outcome.get_result()
    if rep.when != "call":
        return
    rec_path = os.environ.get("RB_RECORD_FILE", "")
    if not rec_path:
        return
    m = item.get_closest_marker("rb")
    depth, jump_kind, expect = 0, "none", ""
    if m is not None:
        if m.args:
            try:
                depth = int(m.args[0])
            except Exception:
                depth = 0
        try:
            depth = int(m.kwargs.get("depth", depth) or 0)
        except Exception:
            depth = 0
        jump_kind = m.kwargs.get("jump_kind", "none") or "none"
        expect = m.kwargs.get("expect", "") or ""
    if jump_kind not in _RB_TIER:
        jump_kind = "none"
    rec = {
        "name": item.nodeid,
        "passed": bool(rep.passed),
        "depth": max(0, int(depth)),
        "jump_kind": jump_kind,
        "tier": _RB_TIER[jump_kind],
        "expect": str(expect),
    }
    try:
        d = os.path.dirname(rec_path)
        if d:
            os.makedirs(d, exist_ok=True)
        with open(rec_path, "w") as f:
            json.dump(rec, f)
    except Exception:
        pass


def _find_pid_by_name(name):
    # macOS kernel truncates process names to 16 chars (MAXCOMLEN).
    # Drop -x (exact match) and use substring match so name[:15] still
    # matches the 16-char truncated kernel name.
    search = name[:15]
    result = subprocess.run(
        ["pgrep", search], capture_output=True, text=True, timeout=5)
    if result.returncode != 0:
        return None
    pids = result.stdout.strip().split("\n")
    return int(pids[0]) if pids and pids[0] else None


def _kill_pid(pid):
    try:
        os.kill(pid, signal.SIGTERM)
        time.sleep(1)
        os.kill(pid, 0)
        os.kill(pid, signal.SIGKILL)
    except ProcessLookupError:
        pass


def _find_all_pids_by_name(name):
    search = name[:15]
    result = subprocess.run(
        ["pgrep", search], capture_output=True, text=True, timeout=5)
    if result.returncode != 0:
        return []
    return [int(p) for p in result.stdout.strip().split("\n") if p.strip()]


def _kill_existing_app(binary_name):
    # Kill ALL instances matching the name (not just the first). Otherwise a
    # still-running reference app (same binary name, launched in stage3/4) lingers
    # into the test run and can be scored in place of the recreation. Target
    # disambiguation for the process we actually test is done by executable PATH
    # in _resolve_target_pid below.
    if not binary_name:
        return
    for pid in _find_all_pids_by_name(binary_name):
        _kill_pid(pid)
    time.sleep(0.5)


def _get_all_pids():
    result = subprocess.run(["ps", "-axo", "pid="], capture_output=True, text=True)
    return [int(p.strip()) for p in result.stdout.splitlines() if p.strip().isdigit()]


def _get_process_name(pid):
    # Use args= (full command line) instead of comm= which is truncated to
    # 16 chars (MAXCOMLEN) by the macOS kernel — breaks detection for long
    # binary names like "MacOSReachabilityTestARC" (24 chars).
    result = subprocess.run(
        ["ps", "-p", str(pid), "-o", "args="], capture_output=True, text=True)
    if result.returncode == 0 and result.stdout.strip():
        exe = result.stdout.strip().split()[0]
        name = os.path.basename(exe)
        if name:
            return name
    result = subprocess.run(
        ["ps", "-p", str(pid), "-o", "comm="], capture_output=True, text=True)
    return os.path.basename(result.stdout.strip()) if result.returncode == 0 else None


def _get_process_args(pid):
    """Full command line (executable path + args) for a pid, kept WHOLE (not
    split). Substring tests on this are space-safe — Electron helpers like
    'Foo Helper (GPU)' and bundle paths with spaces are matched correctly, unlike
    args.split()[0] which breaks at the first space."""
    try:
        r = subprocess.run(["ps", "-p", str(pid), "-o", "args="],
                           capture_output=True, text=True, timeout=5)
        if r.returncode == 0 and r.stdout.strip():
            return r.stdout.strip()
    except Exception:
        pass
    return ""


# Command-line markers identifying the REFERENCE app (the ground-truth app kept
# running from stage3/4). It always runs from a pipeline-internal path; the
# recreation never does. A process whose command line contains one of these must
# never be scored — this is what stops a crashed/absent recreation from being
# silently scored as the still-running reference.
_REFERENCE_PATH_MARKERS = (".pipeline_refapp", "/pipeline_work/")


def _is_reference_proc(pid):
    a = _get_process_args(pid)
    return any(m in a for m in _REFERENCE_PATH_MARKERS)


def _args_under_app(pid, app_path):
    """True iff the pid's EXECUTABLE runs from inside app_path (it IS the app) — NOT a
    launcher like `open -W <bundle>` whose ARGUMENT merely contains the bundle path.

    A running .app's argv0 is <bundle>/Contents/MacOS/<binary>, so we require that inner
    executable path. The old bare-substring test (`app_path in args`) also matched the
    lingering `open -W <bundle>` process launch.sh leaves behind (`exec open -W …`);
    that launcher has NO AX tree, so the fixture bound to it → every element lookup
    returned nothing → reference-app baseline ~0% → the whole suite was pruned to 0."""
    if not app_path:
        return False
    args = _get_process_args(pid)
    ap = app_path.rstrip("/")
    if ap.endswith(".app"):
        # The real GUI process: argv0 == <bundle>/Contents/MacOS/<binary>.
        return (ap + "/Contents/MacOS/") in args
    # Non-bundle executable: require it as argv0 (command starts with it), not merely
    # mentioned as a later argument (which is how `open <path>` would match).
    return args == ap or args.startswith(ap + " ")


# Electron/CEF helper subprocesses live inside the app bundle too but are NOT the
# app. Identified by a --type= switch (renderer/gpu-process/utility) or a
# "Helper (...)" executable — matched on the full command line (space-safe).
_HELPER_MARKERS = ("--type=", " Helper", "(GPU)", "(Renderer)", "(Plugin)", "(CEF")


def _is_helper_proc(pid):
    a = _get_process_args(pid)
    return any(m in a for m in _HELPER_MARKERS)


def _name_matches(pid, names):
    pname = _get_process_name(pid)
    if not pname:
        return False
    for cand in names:
        if cand and (pname == cand
                     or cand.lower() in pname.lower()
                     or pname.lower() in cand.lower()):
            return True
    return False


def _resolve_target_pid(candidate_pids, app_path, binary_name, app_dir_name, app_name_env):
    """Pick the process of the APP UNDER TEST — never a sibling reference, never a helper.

    app_path is the app we were told to test: the OFFICIAL app at stage2 baseline
    (built under ~/pipeline_work/<app>/source/App.app) and the RECREATION at stage5
    eval. In both cases a process running from INSIDE app_path IS the target and must
    be selected — even though that path lives under /pipeline_work/.

    Selection order:
      1. the non-helper process running from INSIDE app_path (exact path match),
         checked BEFORE any reference-marker filtering — a process that literally runs
         from app_path can never be the "other" app, so it is always eligible.
      2. name match, for launch.sh setups that run the app from a build/DerivedData
         path DIFFERENT from app_path (very common: OFFICIAL_APP points at
         source/build/.../Release/App.app while launch.sh starts source/App.app). The
         reference (.pipeline_refapp) and helpers are excluded here.

    BUGFIX (baseline 0% root cause): the reference markers used to be a flat
    (".pipeline_refapp", "/pipeline_work/") pre-filter applied to ALL candidates. But
    the OFFICIAL app under test at stage2 baseline is itself built under
    ~/pipeline_work/<app>/... — so the "/pipeline_work/" marker excluded the only
    running instance, _resolve_target_pid returned None -> conftest raised
    `Could not find process` -> every baseline test errored -> the suite was pruned to
    0 -> the app went unscored. And the exact-path match in step 1 does NOT save it,
    because launch.sh frequently starts the app from a /pipeline_work/ sub-path that
    differs from OFFICIAL_APP (source/App.app vs source/build/.../App.app).
    Fix: suppress the broad "/pipeline_work/" marker when the app under test is ITSELF
    under /pipeline_work/ (i.e. baseline). ".pipeline_refapp" is always excluded. At
    stage5 eval the recreation lives under ~/Recreation (NOT /pipeline_work/), so
    app_in_pw is False there and the "/pipeline_work/" marker still fires to keep the
    official reference from ever being scored — preserving commit 99d3cef's intent.
    """
    if app_path:
        for p in candidate_pids:
            if _args_under_app(p, app_path) and not _is_helper_proc(p):
                return p
    app_in_pw = bool(app_path) and "/pipeline_work/" in app_path

    def _is_ref_here(pid):
        a = _get_process_args(pid)
        if ".pipeline_refapp" in a:
            return True
        if not app_in_pw and "/pipeline_work/" in a:
            return True
        return False

    names = (binary_name, app_dir_name, app_name_env)
    for p in candidate_pids:
        if (not _is_helper_proc(p) and not _is_ref_here(p)
                and _name_matches(p, names)):
            return p
    return None


def _get_binary_name(app_path):
    if app_path:
        info_plist = os.path.join(app_path, "Contents", "Info.plist")
        if os.path.exists(info_plist):
            result = subprocess.run(
                ["defaults", "read", info_plist, "CFBundleExecutable"],
                capture_output=True, text=True, timeout=5)
            if result.returncode == 0:
                return result.stdout.strip()
    return os.environ.get("APP_BINARY") or os.environ.get("APP_NAME") or None


def _get_bundle_id(app_path):
    info_plist = os.path.join(app_path, "Contents", "Info.plist")
    if os.path.exists(info_plist):
        result = subprocess.run(
            ["defaults", "read", info_plist, "CFBundleIdentifier"],
            capture_output=True, text=True, timeout=5)
        if result.returncode == 0:
            return result.stdout.strip()
    return None


def _grant_tcc_permissions(bundle_id):
    """Grant all common TCC permissions to the app so system dialogs don't block tests."""
    if not bundle_id:
        return
    tcc_db = os.path.expanduser(
        "~/Library/Application Support/com.apple.TCC/TCC.db")
    if not os.path.exists(tcc_db):
        return
    services = [
        "kTCCServiceAccessibility", "kTCCServiceScreenCapture",
        "kTCCServiceAppleEvents", "kTCCServicePostEvent",
        "kTCCServiceListenEvent", "kTCCServiceSystemPolicyAllFiles",
        "kTCCServiceDeveloperTool",
        "kTCCServiceCalendar", "kTCCServiceAddressBook",
        "kTCCServiceContactsFull", "kTCCServiceContactsLimited",
        "kTCCServiceReminders", "kTCCServicePhotos",
        "kTCCServicePhotosAdd",
        "kTCCServiceCamera", "kTCCServiceMicrophone",
        "kTCCServiceBluetoothAlways", "kTCCServiceMediaLibrary",
        "kTCCServiceSpeechRecognition", "kTCCServiceMotion",
        "kTCCServiceLocation", "kTCCServiceFocusStatus",
        "kTCCServiceSystemPolicyDesktopFolder",
        "kTCCServiceSystemPolicyDocumentsFolder",
        "kTCCServiceSystemPolicyDownloadsFolder",
        "kTCCServiceSystemPolicyNetworkVolumes",
        "kTCCServiceSystemPolicyRemovableVolumes",
        "kTCCServiceFileProviderDomain",
        "kTCCServiceFileProviderPresence",
    ]
    now = str(int(time.time()))
    for svc in services:
        subprocess.run(
            ["sqlite3", tcc_db,
             f"INSERT OR REPLACE INTO access"
             f" (service, client, client_type, auth_value, auth_reason, auth_version,"
             f"  csreq, policy_id, indirect_object_identifier_type,"
             f"  indirect_object_identifier, indirect_object_code_identity,"
             f"  flags, last_modified, pid, pid_version, boot_uuid, last_reminded)"
             f" VALUES ('{svc}', '{bundle_id}', 0, 2, 0, 1,"
             f"  NULL, NULL, NULL, 'UNUSED', NULL, NULL, {now}, NULL, NULL, 'UNUSED', {now});"],
            capture_output=True, timeout=5)


def _clear_autosaved_documents(app_path, bundle_id=""):
    """Drop the app's UNSAVED documents from ~/Library/Autosave Information/.

    macOS restores an unsaved document of a document-based app on the NEXT launch, and
    neither `defaults delete` nor removing the .savedState touches that directory. A test
    that types into the editor therefore leaks its content into the FOLLOWING test's
    launch state. Measured on MaciASL: after one test set the editor text, every later
    test came up with an 'Untitled' window still holding that text (OEM ID "RBTEST")
    instead of the app opening the machine's System DSDT, which failed 4 of its own
    baseline tests. Clearing this directory restored window 'System DSDT', a 92 KB editor
    and OEM ID "BOCHS ".

    Scoped to entries naming the app under test (bundle name / bundle id), so an
    unrelated app's autosave is never touched.
    """
    base = os.path.expanduser("~/Library/Autosave Information")
    if not os.path.isdir(base):
        return
    names = set()
    stem = os.path.basename(app_path or "").replace(".app", "").strip()
    if stem:
        names.add(stem.lower())
    if bundle_id:
        names.add(bundle_id.lower())
        names.add(bundle_id.rsplit(".", 1)[-1].lower())
    if not names:
        return
    try:
        entries = os.listdir(base)
    except OSError:
        return
    for entry in entries:
        low = entry.lower()
        if any(n in low for n in names):
            subprocess.run(["rm", "-rf", os.path.join(base, entry)],
                           capture_output=True, timeout=5)


def _reset_app_state(app_path):
    bundle_id = _get_bundle_id(app_path)
    # Autosaved documents survive an app with no readable bundle id too, so clear first.
    _clear_autosaved_documents(app_path, bundle_id or "")
    if not bundle_id:
        return
    subprocess.run(["defaults", "delete", bundle_id],
                   capture_output=True, timeout=5)
    saved_state = os.path.expanduser(
        f"~/Library/Saved Application State/{bundle_id}.savedState")
    if os.path.isdir(saved_state):
        subprocess.run(["rm", "-rf", saved_state], capture_output=True, timeout=5)


def _activate_app(pid):
    """Bring the launched app frontmost (by pid) so interaction/menu tests hit the
    RIGHT app. Tests that open menus, send System Events keystrokes, or drive the
    frontmost app fail spuriously when it is merely launched-but-background (the case
    under automated per-test relaunch — nothing foregrounds it).

    Uses NSRunningApplication.activateWithOptions_ (robust, by pid) — verified on a
    sandbox VM to return True and set frontmost. NOT osascript: the System Events
    'process whose unix id is N' selector is unreliable (errors -1719 on Electron
    helper pids etc.). AX reads via the app_ref work regardless, so best-effort."""
    try:
        from AppKit import NSRunningApplication
        app = NSRunningApplication.runningApplicationWithProcessIdentifier_(int(pid))
        if app is not None:
            app.activateWithOptions_(1 << 1)  # NSApplicationActivateIgnoringOtherApps
    except Exception:
        pass


def _launch_app(app_path):
    binary_name = _get_binary_name(app_path)
    _kill_existing_app(binary_name)
    if app_path:
        _reset_app_state(app_path)

    before_pids = set(_get_all_pids())

    launch_sh = os.environ.get("LAUNCH_SH", "")
    launch_proc = None
    launch_err_path = None
    if launch_sh and os.path.isfile(launch_sh):
        launch_err_fd, launch_err_path = tempfile.mkstemp(suffix="_launch.log")
        launch_err_file = os.fdopen(launch_err_fd, "w")
        launch_proc = subprocess.Popen(
            ["bash", launch_sh],
            stdout=subprocess.DEVNULL, stderr=launch_err_file)
        launch_err_file.close()
    elif app_path:
        subprocess.run(["open", app_path], check=True)
    else:
        pytest.fail("No APP_PATH and no LAUNCH_SH — cannot launch app")

    pid = None
    app_dir_name = os.path.basename(app_path).replace(".app", "") if app_path else ""
    app_name_env = os.environ.get("APP_NAME", "")
    # Bind to the RECREATION only. When app_path is known we require a process
    # running from inside that bundle (path match) — immune to the reference app
    # sharing the same binary name. Reference processes are always excluded, so a
    # crashed / never-launched recreation resolves to None → the test fails (score
    # 0) instead of silently scoring the still-running reference.
    for _ in range(30):
        new_pids = set(_get_all_pids()) - before_pids
        pid = _resolve_target_pid(new_pids, app_path, binary_name,
                                  app_dir_name, app_name_env)
        if pid:
            break
        time.sleep(0.5)

    # Fallback: launch.sh may have activated a pre-launched instance (no new pid,
    # e.g. `open` without -n). Search ALL pids — still restricted to the recreation
    # bundle (path match) / reference-excluded.
    if pid is None:
        pid = _resolve_target_pid(_get_all_pids(), app_path, binary_name,
                                  app_dir_name, app_name_env)

    if pid is None:
        launch_stderr = ""
        if launch_err_path:
            try:
                if launch_proc:
                    launch_proc.wait(timeout=2)
                with open(launch_err_path) as f:
                    launch_stderr = f.read()[:500]
            except Exception:
                pass
        _dbg = subprocess.run(
            ["ps", "-axo", "pid,comm,args"], capture_output=True, text=True
        ).stdout[:3000]
        assert False, (
            f"Could not find process for {app_path or launch_sh} within 15s.\n"
            f"binary_name={binary_name}, app_dir_name={app_dir_name}, "
            f"app_name_env={app_name_env}\n"
            f"launch stderr: {launch_stderr or '(empty)'}\n"
            f"Active processes (pid,comm,args):\n{_dbg}"
        )

    if launch_err_path:
        try:
            os.unlink(launch_err_path)
        except OSError:
            pass
    # Bring the app frontmost BEFORE settling/AX-ready: menu-bar reads, opened menus,
    # and System Events keystrokes all target the frontmost app; a launched-but-
    # background app makes those tests fail spuriously (root cause of the mass 0%
    # baselines). Best-effort — AX reads via app_ref are unaffected.
    _activate_app(pid)
    # Electron apps are launched (via launch.sh, which build/recreation inject with
    # --force-renderer-accessibility) so their Chromium AXWebArea builds a few seconds
    # after launch; the AXHelper `ax` fixture then waits for it. Give the process a
    # moment to come up first.
    time.sleep(2)
    return pid


@pytest.fixture(scope="session")
def app_path():
    path = os.environ.get("APP_PATH", "")
    launch_sh = os.environ.get("LAUNCH_SH", "")
    if not path or not os.path.isdir(path):
        if launch_sh and os.path.isfile(launch_sh):
            return ""
        assert False, (
            f"APP_PATH not set or invalid: '{path}', and no LAUNCH_SH found. "
            "Set via: export APP_PATH=/path/to/App.app or export LAUNCH_SH=/path/to/launch.sh"
        )
    bundle_id = _get_bundle_id(path)
    if bundle_id:
        _grant_tcc_permissions(bundle_id)
    return path


@pytest.fixture
def app_process(app_path):
    pid = _launch_app(app_path)
    yield pid
    _kill_pid(pid)


@pytest.fixture
def ax(app_process):
    from ax_helpers import AXHelper
    # wait_for_ready=True: AXHelper._wait_until_ready() polls the app's AX tree until
    # it reports AXChildren>0 before the first query (default True, 10s). This was
    # explicitly set to False, so every test queried an app that may not be AX-ready
    # yet — under per-test relaunch + VM load the tree is still empty → element lookups
    # return nothing → `assert False` → the test fails on the REFERENCE app → 0%
    # baseline → the whole suite gets pruned to 0. Same fixture is used by stage2
    # baseline (over-prune) AND stage5 eval (recreated app scored spuriously low), so
    # this one flag corrupted both. Restore the wait (the _launch_app comment already
    # states the fixture "waits for it").
    # ready_timeout=45 (was default 10): heavy apps (Qt video editors like olive,
    # large Electron) need >10s for AXChildren>0 after a per-test relaunch under VM
    # load. At 10s the wait warned-and-proceeded on a still-empty tree → element
    # lookups returned nothing → assert False → ALL tests fail baseline on the
    # OFFICIAL app → the whole suite is pruned to empty (observed: olive 53 real
    # tests all pruned). A working app reaches AXChildren>0 in <10s so this only
    # costs time on genuinely-slow apps; it never false-fails a working one.
    return AXHelper(app_process, wait_for_ready=True, ready_timeout=45)


@pytest.fixture
def ax_with_reset(ax):
    import verifier_helpers as helpers
    helpers.ensure_panel_open(ax)
    yield ax
    helpers.dismiss_menus(ax)


@pytest.fixture(autouse=True)
def check_app_alive(app_process):
    yield
    try:
        os.kill(app_process, 0)
    except ProcessLookupError:
        pytest.fail(f"App process {app_process} crashed during test")


@pytest.fixture(scope="session", autouse=True)
def check_ax_permission():
    try:
        import ApplicationServices
        trusted = ApplicationServices.AXIsProcessTrusted()
        if not trusted:
            pytest.exit("Process does not have Accessibility permission")
    except ImportError:
        pass


@pytest.fixture(scope="session")
def official_screenshots_dir():
    """Path to the directory containing official app screenshots (ground truth).
    Set via OFFICIAL_SCREENSHOTS_DIR env var; defaults to ./official_screenshots/"""
    d = os.environ.get("OFFICIAL_SCREENSHOTS_DIR",
                       os.path.join(os.path.dirname(__file__), "official_screenshots"))
    if not os.path.isdir(d):
        # A-ii: FAIL, don't skip. A missing official-screenshot baseline means this
        # visual test has no ground truth → it must be pruned (counted as failed), never
        # silently skipped. The runner treats skip as fail anyway; failing here is explicit
        # and keeps the "no skip — unimplemented/missing == fail" invariant.
        pytest.fail(f"Official screenshots dir not found: {d}")
    return d


@pytest.fixture(scope="session")
def recreated_screenshots_dir(tmp_path_factory):
    """Temporary directory for recreated app screenshots during test run."""
    return str(tmp_path_factory.mktemp("recreated_screenshots"))