File size: 40,615 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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
"""AX STRUCTURE tests for CodeEdit (app.codeedit.CodeEdit).

Generated ONLY from verifier/recon.md (## APP / ## PRIMITIVES / ## AX_TREE / ## STRUCTURE).

Lane contract
-------------
* 4 pure-existence GATE tests (jump_kind="none", depth=0): the fresh-launch surfaces that
  must exist — the welcome window + its 3 named action buttons, the recent-projects
  AXOutline + role diversity, the AXMenuBar with its 10 named menus, and the welcome
  window's interactive-widget inventory + AX tree depth.
* 11 shape-delta REACH tests (jump_kind="reach"), one per row of recon's
  `Shape-delta pairs` table, each proved with kit.rb_showing() before/after ONE navigation
  chain and kit.rb_reach() as the assertion, plus the SPECIFIC named widgets recon recorded.
* 4 of the reach tests are depth>=2 (workspace -> editor text area, workspace -> inspector
  pane, workspace -> navigator hide/restore, Settings -> "Text Editing" pane detail).

Environment constraints honoured (recon "ENVIRONMENT CONSTRAINTS")
------------------------------------------------------------------
* no plain keystrokes / Escape anywhere — sheets and panels are dismissed with their own
  "Cancel" button (dismiss_panel_or_sheet),
* CG clicks (never AXPress) for SwiftUI list rows, Settings sidebar panes and workspace
  toolbar buttons,
* none of the forbidden controls is ever pressed (Quit, Close Workspace, Check for
  updates.../Check Now, Install, Contributors, Help items, Locations path buttons,
  Discard All Changes...).
"""

# ── PRIMITIVES (copied VERBATIM from recon.md ## PRIMITIVES) ─────────────────
import json
import os
import shutil
import subprocess
import time

import pytest

import rb_testgen_kit as kit
import verifier_helpers as helpers

RESULTS_DIR = os.environ.get("RESULTS_DIR", os.path.join(os.path.dirname(__file__), "results"))
FIXTURES_DIR = os.environ.get("FIXTURES_DIR") or os.path.join(os.path.dirname(__file__), "fixtures")


def screenshot_assert(test_name, description, results_dir=None):
    results_dir = results_dir or RESULTS_DIR
    ss_dir = os.path.join(results_dir, "screenshots")
    os.makedirs(ss_dir, exist_ok=True)
    ss_path = os.path.join(ss_dir, f"{test_name}.png")
    try:
        subprocess.run(["screencapture", "-x", ss_path], timeout=5)
    except Exception:
        pass
    af = os.path.join(ss_dir, "assertions.json")
    data = {}
    if os.path.exists(af):
        try:
            with open(af) as f:
                data = json.load(f)
        except Exception:
            data = {}
    data[f"{test_name}.png"] = description
    with open(af, "w") as f:
        json.dump(data, f, indent=2)


def win_id(ax, w):
    return ax.get(w.id, ["AXIdentifier"]).get("AXIdentifier")


def all_windows(ax):
    return ax.find(role="window", max_depth=1, max_results=20)


def find_window(ax, ident=None, title=None, timeout=8.0):
    end = time.time() + timeout
    while True:
        for w in all_windows(ax):
            if ident is not None and win_id(ax, w) == ident:
                return w
            if title is not None and (w.name or "") == title:
                return w
        if time.time() >= end:
            return None
        time.sleep(0.25)


def close_window(ax, w):
    if w is None:
        return False
    for b in ax.find(role="button", root_id=w.id, max_results=200, max_depth=3):
        if ax.get(b.id, ["AXSubrole"]).get("AXSubrole") == "AXCloseButton":
            ax.action(b.id, "AXPress")
            time.sleep(0.8)
            return True
    return False


def values_in(ax, root_id, max_results=400, max_depth=18):
    """Every non-empty AXValue string under root (labels, fields, popups)."""
    out = []
    for e in ax.find(root_id=root_id, max_results=max_results, max_depth=max_depth):
        v = ax.get(e.id, ["AXValue"]).get("AXValue")
        if isinstance(v, str) and v.strip():
            out.append(v)
    return out


def names_in(ax, root_id, role=None, max_results=400, max_depth=18):
    return [e.name for e in ax.find(role=role, root_id=root_id,
                                    max_results=max_results, max_depth=max_depth) if e.name]


def buttons_named(ax, root_id, name):
    return [b for b in ax.find(role="button", root_id=root_id, max_results=300, max_depth=16)
            if (b.name or "") == name]


def menu_item(ax, *path):
    mbi = [m for m in ax.find(role="menu_bar_item", max_results=20, max_depth=3)
           if (m.name or "") == path[0]]
    if not mbi:
        return None
    cur = mbi[0].id
    for label in path[1:]:
        items = ax.find(role="menu_item", root_id=cur, max_results=300, max_depth=2)
        hit = [i for i in items if (i.name or "") == label]
        if not hit:
            return None
        cur = hit[0].id
    return cur


def menu_items(ax, *path):
    """Item NAMES directly under a menu-bar item (or a submenu item)."""
    root = menu_item(ax, *path) if len(path) > 1 else None
    if root is None:
        mbi = [m for m in ax.find(role="menu_bar_item", max_results=20, max_depth=3)
               if (m.name or "") == path[0]]
        if not mbi:
            return []
        menus = ax.find(role="menu", root_id=mbi[0].id, max_results=2, max_depth=1)
        if not menus:
            return []
        root = menus[0].id
    else:
        menus = ax.find(role="menu", root_id=root, max_results=2, max_depth=1)
        if not menus:
            return []
        root = menus[0].id
    return [i.name for i in ax.find(role="menu_item", root_id=root, max_results=100, max_depth=1)
            if (i.name or "")]


def rb_enter_menu_item(ax, *path, wait=1.6):
    mid = menu_item(ax, *path)
    if mid is None:
        return False
    ax.action(mid, "AXPress")
    time.sleep(wait)
    return True


def rb_enter_welcome(ax):
    w = find_window(ax, ident="welcome", timeout=3)
    if w is None:
        rb_enter_menu_item(ax, "Window", "Welcome to CodeEdit")
        w = find_window(ax, ident="welcome", timeout=6)
    return w


def rb_enter_settings_window(ax):
    w = find_window(ax, ident="settings", timeout=1)
    if w is None:
        rb_enter_menu_item(ax, "CodeEdit", "Settings...", wait=2.0)
        w = find_window(ax, ident="settings", timeout=8)
    return w


def rb_reach_settings_pane(ax, pane):
    """Select a Settings sidebar pane. MUST be a CG click (AXPress does NOT select)."""
    w = rb_enter_settings_window(ax)
    if w is None:
        return None
    bs = buttons_named(ax, w.id, pane)
    if not bs:
        return None
    ax.click_element_cg(bs[-1].id)
    time.sleep(1.0)
    return find_window(ax, ident="settings", timeout=3)


def rb_enter_about_window(ax):
    rb_enter_menu_item(ax, "CodeEdit", "About CodeEdit", wait=2.0)
    return find_window(ax, ident="about", timeout=6)


def rb_enter_extensions_window(ax):
    rb_enter_menu_item(ax, "Extensions", "Open Extensions Window", wait=2.0)
    return find_window(ax, ident="extensions", timeout=6)


def rb_enter_clone_sheet(ax):
    w = rb_enter_welcome(ax)
    bs = buttons_named(ax, w.id, "Clone Git Repository...")
    if not bs:
        return None
    ax.action(bs[0].id, "AXPress")
    end = time.time() + 6
    while time.time() < end:
        s = ax.find(role="sheet", max_results=3, max_depth=6)
        if s:
            return s[0]
        time.sleep(0.25)
    return None


def rb_enter_save_panel(ax):
    w = rb_enter_welcome(ax)
    bs = buttons_named(ax, w.id, "Create New File...")
    if bs:
        ax.action(bs[0].id, "AXPress")
    return find_window(ax, title="Save", timeout=8)


def rb_enter_open_panel(ax):
    w = rb_enter_welcome(ax)
    bs = buttons_named(ax, w.id, "Open File or Folder...")
    if bs:
        ax.action(bs[0].id, "AXPress")
    return find_window(ax, title="Open Workspace or File", timeout=8)


def dismiss_panel_or_sheet(ax):
    """Escape does not work here — press the panel/sheet's own Cancel button."""
    for b in ax.find(role="button", max_results=120, max_depth=10):
        if (b.name or "") == "Cancel":
            ax.action(b.id, "AXPress")
            time.sleep(1.0)
            return True
    return False


def rb_enter_workspace(ax, folder_name="sample_project", timeout=20.0):
    """Open the fixture folder as a workspace the way Finder does: hand the folder to the
    RUNNING app's own bundle (discovered from its pid at runtime — portable)."""
    from AppKit import NSWorkspace, NSRunningApplication, NSWorkspaceOpenConfiguration
    from Foundation import NSURL
    src = os.path.join(FIXTURES_DIR, folder_name)
    base = os.path.join("/tmp", "rb_codeedit_ws")
    dst = os.path.join(base, folder_name)
    if os.path.isdir(base):
        shutil.rmtree(base, ignore_errors=True)
    os.makedirs(base, exist_ok=True)
    shutil.copytree(src, dst)
    ra = NSRunningApplication.runningApplicationWithProcessIdentifier_(int(ax._pid))
    cfg = NSWorkspaceOpenConfiguration.configuration()
    cfg.setActivates_(True)
    NSWorkspace.sharedWorkspace().openURLs_withApplicationAtURL_configuration_completionHandler_(
        [NSURL.fileURLWithPath_(dst)], ra.bundleURL(), cfg, None)
    return find_window(ax, ident="workspace", timeout=timeout)


def project_navigator(ax, ws):
    for o in ax.find(role="outline", root_id=ws.id, max_results=10, max_depth=14):
        if (o.name or "") == "Project Navigator":
            return o
    return None


def navigator_rows(ax, ws):
    nav = project_navigator(ax, ws)
    if nav is None:
        return []
    return [ax.get(t.id, ["AXValue"]).get("AXValue")
            for t in ax.find(role="text_field", root_id=nav.id, max_results=60, max_depth=8)]


def rb_reach_editor(ax, ws, filename):
    """Click a file row in the Project Navigator; returns the editor AXTextArea (or None)."""
    nav = project_navigator(ax, ws)
    if nav is None:
        return None
    rows = ax.find(role="text_field", root_id=nav.id, max_results=60, max_depth=8)
    tgt = [t for t in rows if ax.get(t.id, ["AXValue"]).get("AXValue") == filename]
    if not tgt:
        return None
    ax.click_element_cg(tgt[0].id)
    end = time.time() + 8
    while time.time() < end:
        ta = ax.find(role="text_area", root_id=ws.id, max_results=5, max_depth=18)
        if ta:
            return ta[0]
        time.sleep(0.3)
    return None


def rb_enter_command_palette(ax, ws):
    """Command Palette / Open Quickly only exist while a WORKSPACE window is open."""
    ax.action(ws.id, "AXRaise")
    time.sleep(0.5)
    rb_enter_menu_item(ax, "View", "Show Command Palette", wait=1.6)
    return _overlay_window(ax)


def rb_enter_open_quickly(ax, ws):
    ax.action(ws.id, "AXRaise")
    time.sleep(0.5)
    rb_enter_menu_item(ax, "File", "Open Quickly", wait=1.6)
    return _overlay_window(ax)


def _overlay_window(ax):
    """The palette/quick-open overlay is a borderless AXWindow: no title, no AXIdentifier."""
    for w in all_windows(ax):
        if win_id(ax, w) is None and not (w.name or ""):
            return w
    return None


def overlay_rows(ax, pal):
    return [v for v in (ax.get(t.id, ["AXValue"]).get("AXValue")
                        for t in ax.find(role="label", root_id=pal.id,
                                         max_results=60, max_depth=14)) if v]


def overlay_type(ax, pal, text):
    tf = ax.find(role="text_field", root_id=pal.id, max_results=5, max_depth=8)
    if not tf:
        return False
    ax.set_value(tf[0].id, text)
    time.sleep(1.3)
    return True


def switch_for_label(ax, root_id, label):
    """The AXCheckBox(AXSwitch) that follows the AXStaticText whose AXValue == label."""
    seq = ax.find(root_id=root_id, max_results=400, max_depth=18)
    idx = None
    for i, e in enumerate(seq):
        if e.role == "label" and ax.get(e.id, ["AXValue"]).get("AXValue") == label:
            idx = i
            break
    if idx is None:
        return None
    for e in seq[idx + 1:idx + 4]:
        if e.role == "checkbox":
            return e
    return None


def popup_for_label(ax, root_id, label):
    seq = ax.find(root_id=root_id, max_results=400, max_depth=18)
    idx = None
    for i, e in enumerate(seq):
        if e.role == "label" and ax.get(e.id, ["AXValue"]).get("AXValue") == label:
            idx = i
            break
    if idx is None:
        return None
    for e in seq[idx + 1:idx + 4]:
        if e.role == "popup":
            return e
    return None


def popup_options(ax, popup):
    ax.action(popup.id, "AXPress")
    time.sleep(0.8)
    menus = ax.find(role="menu", root_id=popup.id, max_results=3, max_depth=2)
    out = []
    if menus:
        for i in ax.find(role="menu_item", root_id=menus[0].id, max_results=40, max_depth=2):
            out.append(i.name or ax.get(i.id, ["AXValue"]).get("AXValue"))
        ax.action(menus[0].id, "AXCancel")
        time.sleep(0.4)
    return [o for o in out if o]


def popup_pick(ax, popup, option):
    ax.action(popup.id, "AXPress")
    time.sleep(0.8)
    menus = ax.find(role="menu", root_id=popup.id, max_results=3, max_depth=2)
    if not menus:
        return False
    for i in ax.find(role="menu_item", root_id=menus[0].id, max_results=40, max_depth=2):
        if (i.name or ax.get(i.id, ["AXValue"]).get("AXValue")) == option:
            ax.action(i.id, "AXPick")
            time.sleep(1.0)
            return True
    ax.action(menus[0].id, "AXCancel")
    return False


# ── STRUCTURE-lane constants + local navigation helpers ──────────────────────
# Every window below is located by a SEMANTIC key (visible title / a named widget it
# contains) with the recon AXIdentifier accepted as an equally valid match — never by
# child index or tree path, so a recreation built on a different hierarchy still matches.

WELCOME_TITLE = "Welcome To CodeEdit"
WELCOME_BUTTONS = ("Create New File...", "Clone Git Repository...", "Open File or Folder...")
MENU_BAR_ITEMS = ["CodeEdit", "File", "Edit", "View", "Find", "Navigate",
                  "Source Control", "Extensions", "Window", "Help"]
SETTINGS_PANES = ["General", "Accounts", "Navigation", "Themes", "Text Editing",
                  "Terminal", "Search", "Source Control", "Locations"]
WELCOME_ROLES = ("button", "label", "image", "scroll_area", "outline", "column", "group")
NAV_ROWS = ("sample_project", "src", "README.md", "hello.py", "notes.txt")
# Snapshot depth used for EVERY kit.rb_showing() call below. recon observed the "role|name"
# keys of its shape deltas at the kit default (12); DEEP is deeper still, and a deeper snapshot
# is a strict SUPERSET of a shallower one — so no key recon recorded can be missed.
DEEP = 16


def tree_depth(node, d=0):
    """Max AX nesting depth of an ax.tree() dict (0 == the root node itself)."""
    kids = (node or {}).get("children") or []
    if not kids:
        return d
    return max(tree_depth(k, d + 1) for k in kids)


def node_count(node):
    return 1 + sum(node_count(k) for k in ((node or {}).get("children") or []))


def roles_under(ax, root_id, max_depth=10, max_results=300):
    return {e.role for e in ax.find(root_id=root_id, max_results=max_results,
                                    max_depth=max_depth)}


def shows(ax, snapshot, role, name, root_id=None, max_depth=DEEP):
    """True iff a widget with this short ROLE and this visible NAME is present — either as a
    'role|name' key in the rb_showing() snapshot, or (depth-proof fallback) by a scoped
    ax.find that also accepts the label carried in AXValue instead of AXTitle. Locating by
    role + visible label keeps the check framework-agnostic (no child index, no tree path)."""
    if f"{role}|{name}" in snapshot:
        return True
    for e in ax.find(role=role, root_id=root_id, max_results=400, max_depth=max_depth):
        if (e.name or "") == name:
            return True
        if str(ax.get(e.id, ["AXValue"]).get("AXValue") or "") == name:
            return True
    return False


def window_containing(ax, role, name, max_depth=8):
    """The AXWindow holding a descendant with this ROLE + visible NAME (semantic locator,
    used for the About window whose own title is the empty string)."""
    for w in all_windows(ax):
        for e in ax.find(role=role, root_id=w.id, max_results=200, max_depth=max_depth):
            if (e.name or "") == name:
                return w
    return None


def rb_enter_welcome_surface(ax):
    """The fresh-launch welcome window: AXIdentifier 'welcome' OR title 'Welcome To CodeEdit'."""
    w = find_window(ax, ident="welcome", title=WELCOME_TITLE, timeout=3)
    if w is None:
        rb_enter_welcome(ax)
        w = find_window(ax, ident="welcome", title=WELCOME_TITLE, timeout=6)
    return w


def rb_enter_settings_surface(ax, pane_title="General"):
    """CodeEdit > Settings...  -> the settings window (id 'settings' OR title == the pane)."""
    w = find_window(ax, ident="settings", title=pane_title, timeout=0.2)
    if w is not None:
        return w
    rb_enter_menu_item(ax, "CodeEdit", "Settings...", wait=2.0)
    return find_window(ax, ident="settings", title=pane_title, timeout=8)


def rb_reach_settings_pane_surface(ax, pane):
    """Select a Settings sidebar pane with a REAL CG click (AXPress does NOT select a
    SwiftUI List row). Takes buttons_named(...)[-1] because 'Search' names two buttons."""
    w = rb_enter_settings_surface(ax)
    if w is None:
        return None
    bs = buttons_named(ax, w.id, pane)
    if not bs:
        return None
    ax.click_element_cg(bs[-1].id)
    time.sleep(1.2)
    return find_window(ax, ident="settings", title=pane, timeout=4)


def rb_enter_about_surface(ax):
    """CodeEdit > About CodeEdit -> the about window (title is ''; id 'about' or content)."""
    rb_enter_menu_item(ax, "CodeEdit", "About CodeEdit", wait=2.0)
    w = find_window(ax, ident="about", timeout=4)
    if w is None:
        w = window_containing(ax, "button", "Acknowledgements")
    return w


def rb_enter_extensions_surface(ax):
    """Extensions > Open Extensions Window -> window id 'extensions' / title 'Extensions'."""
    rb_enter_menu_item(ax, "Extensions", "Open Extensions Window", wait=2.0)
    return find_window(ax, ident="extensions", title="Extensions", timeout=6)


def rb_enter_workspace_surface(ax, folder_name="sample_project"):
    """Open FIXTURES_DIR/<folder_name> as a workspace; accept id 'workspace' OR the folder
    name as the window title."""
    ws = rb_enter_workspace(ax, folder_name=folder_name, timeout=3.0)
    if ws is None:
        ws = find_window(ax, ident="workspace", title=folder_name, timeout=15)
    return ws


def rb_reach_workspace_toolbar(ax, ws, name, wait=1.8):
    """Toggle a workspace toolbar button by its visible NAME (Navigator Sidebar / Inspector
    Sidebar). Workspace toolbar buttons need a REAL CG click (recon ENVIRONMENT CONSTRAINT 3).
    Searched in the AXToolbar first (cheap) and only then window-wide, so a recreation that
    puts the control elsewhere in the hierarchy still matches."""
    ax.action(ws.id, "AXRaise")
    time.sleep(0.4)
    bs = []
    for tb in ax.find(role="toolbar", root_id=ws.id, max_results=3, max_depth=5):
        bs = [b for b in ax.find(role="button", root_id=tb.id, max_results=60, max_depth=6)
              if (b.name or "") == name]
        if bs:
            break
    if not bs:
        bs = buttons_named(ax, ws.id, name)
    if not bs:
        return False
    ax.click_element_cg(bs[0].id)
    time.sleep(wait)
    return True


# ── GATE: the surfaces that must exist on a fresh launch (existence only) ────

class TestStructureGate:
    """The <=30% existence gate — no trigger, just the fresh-launch skeleton."""

    @pytest.mark.rb(depth=0, jump_kind="none")
    def test_gate_welcome_window_and_named_buttons(self, ax):
        """Exactly ONE welcome AXWindow (AXIdentifier 'welcome', title 'Welcome To CodeEdit')
        holding the 3 named push buttons plus 'Close', all exposing AXPress."""
        cands = [w for w in all_windows(ax)
                 if win_id(ax, w) == "welcome" or "welcome" in (w.name or "").lower()]
        assert len(cands) == 1, (
            "expected exactly 1 welcome AXWindow (AXIdentifier 'welcome' / title "
            f"'{WELCOME_TITLE}'), got {[(win_id(ax, w), w.name) for w in all_windows(ax)]}")
        w = cands[0]
        assert (w.name or "") == WELCOME_TITLE, (
            f"welcome window title = {w.name!r}, expected {WELCOME_TITLE!r}")

        btn_names = set(names_in(ax, w.id, role="button", max_depth=8))
        for label in WELCOME_BUTTONS:
            assert label in btn_names, (
                f"welcome window is missing the push button {label!r} (buttons={sorted(btn_names)})")
        assert "Close" in btn_names, "welcome window is missing its 'Close' button"

        for label in WELCOME_BUTTONS:
            bs = buttons_named(ax, w.id, label)
            assert bs, f"button {label!r} vanished between lookups"
            assert "AXPress" in (bs[0].actions or []), (
                f"button {label!r} exposes no AXPress action")

        screenshot_assert(
            "structure_test_welcome_window",
            "CodeEdit 'Welcome To CodeEdit' window, a centred panel about 740x460: a large "
            "CodeEdit app icon at the top with the title 'CodeEdit' and 'Version 0.3.1 (42)' "
            "under it, then three full-width rows with SF-Symbol icons on the left half "
            "reading 'Create New File...', 'Clone Git Repository...' and "
            "'Open File or Folder...'; the right column is an empty recent-projects list "
            "showing 'No Recent Projects'. A small close button sits at the window's top-left.",
            RESULTS_DIR)

    @pytest.mark.rb(depth=0, jump_kind="none")
    def test_gate_welcome_recent_projects_outline_and_role_diversity(self, ax):
        """The welcome window contains AXScrollArea > AXOutline 'Sidebar' > AXColumn (the
        recent-projects list) and exposes at least the 7 recon roles."""
        w = rb_enter_welcome_surface(ax)
        assert w is not None, "no welcome window (AXIdentifier 'welcome' / title 'Welcome To CodeEdit')"

        scrolls = ax.find(role="scroll_area", root_id=w.id, max_results=5, max_depth=6)
        assert scrolls, "welcome window has no AXScrollArea for the recent-projects list"
        sidebars = [o for o in ax.find(role="outline", root_id=scrolls[0].id,
                                       max_results=5, max_depth=4)
                    if (o.name or "") == "Sidebar"]
        assert sidebars, "no AXOutline named 'Sidebar' inside the welcome AXScrollArea"
        assert ax.find(role="column", root_id=sidebars[0].id, max_results=5, max_depth=3), \
            "the recent-projects AXOutline 'Sidebar' exposes no AXColumn"

        roles = roles_under(ax, w.id, max_depth=8)
        for expected in WELCOME_ROLES:
            assert expected in roles, (
                f"welcome window exposes no {expected!r} role (roles={sorted(roles)})")
        assert len(roles) >= 7, f"role diversity too low: {sorted(roles)}"

    @pytest.mark.rb(depth=0, jump_kind="none")
    def test_gate_menu_bar_named_menus(self, ax):
        """The AXMenuBar exposes exactly the 10 named app menus (besides the system 'Apple'
        item); CodeEdit owns 'Settings...' + 'About CodeEdit' and Extensions owns exactly
        'Open Extensions Window'."""
        assert ax.find(role="menu_bar", max_results=3, max_depth=2), \
            "application exposes no AXMenuBar"

        names = [m.name for m in ax.find(role="menu_bar_item", max_results=20, max_depth=3)
                 if (m.name or "")]
        app_menus = [n for n in names if n != "Apple"]
        assert app_menus == MENU_BAR_ITEMS, (
            f"menu-bar items = {app_menus!r}, expected {MENU_BAR_ITEMS!r}")

        code_edit_items = menu_items(ax, "CodeEdit")
        assert "Settings..." in code_edit_items, f"CodeEdit menu = {code_edit_items!r}"
        assert "About CodeEdit" in code_edit_items, f"CodeEdit menu = {code_edit_items!r}"
        ext_items = menu_items(ax, "Extensions")
        assert ext_items == ["Open Extensions Window"], f"Extensions menu = {ext_items!r}"

    @pytest.mark.rb(depth=0, jump_kind="none")
    def test_gate_welcome_interactive_inventory_and_tree_depth(self, ax):
        """Interactive inventory of the welcome window: >=4 AXPress-able widgets whose names
        are the 3 actions + 'Close', a single 'Version …' AXStaticText, >=8 AX nodes total
        and a subtree at least 4 levels deep (window > group > scroll area > outline > column)."""
        w = rb_enter_welcome_surface(ax)
        assert w is not None, "no welcome window (AXIdentifier 'welcome' / title 'Welcome To CodeEdit')"

        els = ax.find(root_id=w.id, max_results=300, max_depth=10)
        pressable = [e for e in els if "AXPress" in (e.actions or [])]
        assert len(pressable) >= 4, (
            f"only {len(pressable)} AXPress-able widgets in the welcome window, expected >=4")
        pressable_names = {e.name for e in pressable if e.name}
        for label in WELCOME_BUTTONS + ("Close",):
            assert label in pressable_names, (
                f"{label!r} is not an AXPress-able widget (pressable={sorted(pressable_names)})")

        version_labels = [e for e in els if e.role == "label"
                          and str(ax.get(e.id, ["AXValue"]).get("AXValue") or "").startswith("Version")]
        assert len(version_labels) == 1, (
            f"expected exactly 1 'Version …' AXStaticText in the welcome window, "
            f"got {len(version_labels)}")

        subtree = ax.tree(max_depth=10, root_id=w.id)
        assert node_count(subtree) >= 8, (
            f"welcome window subtree has only {node_count(subtree)} AX nodes")
        depth = tree_depth(subtree)
        assert depth >= 4, (
            f"welcome window AX subtree is only {depth} levels deep, expected >=4 "
            "(window > hosting group > scroll area > outline > column)")


# ── Shape deltas: stand-alone windows opened from the menu bar ───────────────

class TestWindowSurfaceReach:

    @pytest.mark.rb(depth=1, jump_kind="reach",
                    expect="CodeEdit > Settings... adds window|General (id 'settings') holding "
                           "an AXSplitGroup 'settings, SidebarNavigationSplitView', 2 AXOutline "
                           "'Sidebar', an AXToolbar and the 9 sidebar pane buttons General, "
                           "Accounts, Navigation, Themes, Text Editing, Terminal, Search, "
                           "Source Control, Locations (recon +59 nodes; >=30 asserted)")
    def test_settings_window_reach(self, ax):
        before = kit.rb_showing(ax, max_depth=DEEP)
        w = rb_enter_settings_surface(ax)
        after = kit.rb_showing(ax, max_depth=DEEP)
        assert kit.rb_reach(before, after, target="window|General", source=None), (
            "no 'General' settings window appeared after CodeEdit > Settings... "
            f"(new nodes: {sorted(list(after - before))[:12]})")

        assert w is not None, "no settings window (AXIdentifier 'settings' / title 'General')"
        assert (w.name or "") == "General", (
            f"settings window title = {w.name!r}, expected the selected pane name 'General'")
        assert len(after - before) >= 30, (
            f"the settings window only added {len(after - before)} AX nodes (recon: +59)")

        split = ax.find(role="split_group", root_id=w.id, max_results=10, max_depth=8)
        assert split, "settings window contains no AXSplitGroup"
        split_ids = [ax.get(s.id, ["AXIdentifier"]).get("AXIdentifier") for s in split]
        assert any(sid and "SidebarNavigationSplitView" in str(sid) for sid in split_ids), (
            "settings window has no AXSplitGroup identified as the sidebar navigation split "
            f"view (identifiers = {split_ids!r}, recon: 'settings, SidebarNavigationSplitView')")

        outlines = [o for o in ax.find(role="outline", root_id=w.id, max_results=10, max_depth=12)
                    if (o.name or "") == "Sidebar"]
        assert len(outlines) >= 2, (
            f"expected 2 AXOutline 'Sidebar' in the Settings sidebar, got {len(outlines)}")
        assert ax.find(role="toolbar", root_id=w.id, max_results=3, max_depth=5), \
            "settings window has no AXToolbar"

        btn_names = set(names_in(ax, w.id, role="button", max_depth=16))
        for pane in SETTINGS_PANES:
            assert pane in btn_names, (
                f"Settings sidebar is missing the {pane!r} pane button "
                f"(buttons={sorted(btn_names)})")

        screenshot_assert(
            "structure_test_settings_window",
            "CodeEdit Settings window titled 'General' floating over the welcome window: a "
            "left sidebar with a search field and 9 colour-icon rows (General, Accounts, "
            "Navigation, Themes, Text Editing, Terminal, Search, Source Control, Locations) "
            "with 'General' highlighted, and a right detail pane of grouped rows containing "
            "popup menus (Appearance, Show Issues, Reopen Behavior, File Extensions), several "
            "toggle switches and two radio pairs (Color/Monochrome and Top/Side).",
            RESULTS_DIR)

    @pytest.mark.rb(depth=1, jump_kind="reach",
                    expect="CodeEdit > About CodeEdit adds the about window (id 'about', empty "
                           "title) with button|Contributors, button|Acknowledgements, "
                           "link|MIT License and label|Copyright © 2022-2024 CodeEdit "
                           "(recon +6 nodes; >=4 asserted)")
    def test_about_window_reach(self, ax):
        before = kit.rb_showing(ax, max_depth=DEEP)
        w = rb_enter_about_surface(ax)
        after = kit.rb_showing(ax, max_depth=DEEP)
        assert kit.rb_reach(before, after, target="button|Acknowledgements", source=None), (
            "no About window with an 'Acknowledgements' button appeared "
            f"(new nodes: {sorted(list(after - before))[:12]})")

        assert w is not None, "no About window (AXIdentifier 'about' / 'Acknowledgements' button)"
        assert len(after - before) >= 4, (
            f"the About window only added {len(after - before)} AX nodes (recon: +6)")

        for role, name in (("button", "Contributors"), ("button", "Acknowledgements"),
                           ("link", "MIT License"),
                           ("label", "Copyright © 2022-2024 CodeEdit")):
            assert shows(ax, after, role, name, root_id=w.id), (
                f"About window is missing the {role} {name!r}")

        links = [ln.name for ln in ax.find(role="link", root_id=w.id,
                                           max_results=5, max_depth=10)]
        assert links == ["MIT License"], f"About window AXLinks = {links!r}, expected ['MIT License']"

    @pytest.mark.rb(depth=1, jump_kind="reach",
                    expect="Extensions > Open Extensions Window adds window|Extensions "
                           "(id 'extensions') with button|Hide Sidebar, label|Select an "
                           "extension, popup|more toolbar items, an AXToolbar, an AXSplitter "
                           "and one empty AXOutline 'Sidebar' (recon +9 nodes; >=5 asserted)")
    def test_extensions_window_reach(self, ax):
        before = kit.rb_showing(ax, max_depth=DEEP)
        w = rb_enter_extensions_surface(ax)
        after = kit.rb_showing(ax, max_depth=DEEP)
        assert kit.rb_reach(before, after, target="window|Extensions", source=None), (
            "no 'Extensions' window appeared after Extensions > Open Extensions Window "
            f"(new nodes: {sorted(list(after - before))[:12]})")

        assert w is not None, "no Extensions window (AXIdentifier 'extensions' / title 'Extensions')"
        assert (w.name or "") == "Extensions", f"Extensions window title = {w.name!r}"
        assert len(after - before) >= 5, (
            f"the Extensions window only added {len(after - before)} AX nodes (recon: +9)")

        for role, name in (("button", "Hide Sidebar"), ("label", "Select an extension"),
                           ("popup", "more toolbar items")):
            assert shows(ax, after, role, name, root_id=w.id), (
                f"Extensions window is missing the {role} {name!r}")
        assert ax.find(role="toolbar", root_id=w.id, max_results=3, max_depth=5), \
            "Extensions window has no AXToolbar"
        assert ax.find(role="splitter", root_id=w.id, max_results=3, max_depth=10), \
            "Extensions window has no AXSplitter"
        outlines = [o.name for o in ax.find(role="outline", root_id=w.id,
                                            max_results=5, max_depth=12)]
        assert "Sidebar" in outlines, (
            f"Extensions window outlines = {outlines!r}, expected the extension-list "
            "AXOutline 'Sidebar'")


# ── Shape deltas: modal sheet / file panels raised from the welcome window ───

class TestModalSurfaceReach:

    @pytest.mark.rb(depth=1, jump_kind="reach",
                    expect="welcome 'Clone Git Repository...' raises exactly 1 AXSheet with "
                           "label|Clone a repository, label|Enter a git repository URL:, one "
                           "AXTextField, button|Cancel and a DISABLED button|Clone, while the "
                           "welcome window stays the only AXWindow")
    def test_clone_sheet_reach(self, ax):
        before = kit.rb_showing(ax, max_depth=DEEP)
        sheet = rb_enter_clone_sheet(ax)
        after = kit.rb_showing(ax, max_depth=DEEP)
        assert kit.rb_reach(before, after, target="label|Clone a repository", source=None), (
            "'Clone Git Repository...' raised no sheet titled 'Clone a repository' "
            f"(new nodes: {sorted(list(after - before))[:12]})")

        assert sheet is not None, "'Clone Git Repository...' raised no AXSheet"
        sheets = ax.find(role="sheet", max_results=5, max_depth=6)
        assert len(sheets) == 1, f"expected exactly 1 AXSheet, got {len(sheets)}"
        hosts = [w for w in all_windows(ax)
                 if win_id(ax, w) == "welcome" or (w.name or "") == WELCOME_TITLE]
        assert len(hosts) == 1, "the clone sheet must sit on the single welcome window"

        for role, name in (("label", "Clone a repository"),
                           ("label", "Enter a git repository URL:"),
                           ("button", "Cancel"), ("button", "Clone")):
            assert shows(ax, after, role, name, root_id=sheet.id), (
                f"clone sheet is missing the {role} {name!r}")
        fields = ax.find(role="text_field", root_id=sheet.id, max_results=5, max_depth=8)
        assert len(fields) == 1, (
            f"expected exactly 1 AXTextField (the git URL) in the clone sheet, got {len(fields)}")
        clone_btn = buttons_named(ax, sheet.id, "Clone")
        assert clone_btn, "clone sheet has no 'Clone' button"
        assert clone_btn[0].enabled is False, \
            "'Clone' must be AXEnabled == False while the URL field is empty"

        dismiss_panel_or_sheet(ax)

    @pytest.mark.rb(depth=1, jump_kind="reach",
                    expect="welcome 'Open File or Folder...' swaps the window list: "
                           "window|Welcome To CodeEdit LEAVES it and window|Open Workspace or "
                           "File (id 'open-panel') with button|Open + button|Cancel appears "
                           "(recon +47 nodes; >=20 asserted)")
    def test_open_panel_reach(self, ax):
        before = kit.rb_showing(ax, max_depth=DEEP)
        panel = rb_enter_open_panel(ax)
        after = kit.rb_showing(ax, max_depth=DEEP)
        assert kit.rb_reach(before, after,
                            target="window|Open Workspace or File",
                            source="window|Welcome To CodeEdit"), (
            "'Open File or Folder...' did not replace the welcome window with the "
            f"'Open Workspace or File' panel (new nodes: {sorted(list(after - before))[:12]})")

        assert panel is not None, "no window titled 'Open Workspace or File'"
        assert len(after - before) >= 20, (
            f"the open panel only added {len(after - before)} AX nodes (recon: +47)")

        titles = [(w.name or "") for w in all_windows(ax)]
        assert WELCOME_TITLE not in titles, (
            "the welcome window must leave the AX window list while the modal open panel "
            f"is up; window list = {titles!r}")
        for name in ("Open", "Cancel"):
            assert shows(ax, after, "button", name, root_id=panel.id), (
                f"the open panel is missing the {name!r} button")

        dismiss_panel_or_sheet(ax)

    @pytest.mark.rb(depth=1, jump_kind="reach",
                    expect="welcome 'Create New File...' adds window|Save (id 'save-panel') "
                           "with label|Save As:, text_field|Untitled, a 'Where:' AXPopUpButton, "
                           "button|Save and button|Cancel (recon +13 nodes; >=6 asserted)")
    def test_save_panel_reach(self, ax):
        before = kit.rb_showing(ax, max_depth=DEEP)
        panel = rb_enter_save_panel(ax)
        after = kit.rb_showing(ax, max_depth=DEEP)
        assert kit.rb_reach(before, after, target="window|Save", source=None), (
            "'Create New File...' raised no 'Save' panel window "
            f"(new nodes: {sorted(list(after - before))[:12]})")

        assert panel is not None, "no window titled 'Save'"
        assert len(after - before) >= 6, (
            f"the save panel only added {len(after - before)} AX nodes (recon: +13)")

        for role, name in (("label", "Save As:"), ("text_field", "Untitled"),
                           ("button", "Save"), ("button", "Cancel")):
            assert shows(ax, after, role, name, root_id=panel.id), (
                f"the save panel is missing the {role} {name!r}")
        assert ax.find(role="popup", root_id=panel.id, max_results=5, max_depth=12), \
            "the save panel has no 'Where:' AXPopUpButton"

        dismiss_panel_or_sheet(ax)


# ── Shape deltas: the workspace window and its panes ─────────────────────────

# ── Shape delta: a Settings pane and its own detail widgets (depth 2) ────────

class TestSettingsPaneStructureReach:

    @pytest.mark.rb(depth=2, jump_kind="reach",
                    expect="Settings (General) -> CG-click the sidebar pane 'Text Editing': the "
                           "window title becomes 'Text Editing', the General row "
                           "label|Reopen Behavior DISAPPEARS and label|Prefer Indent Using, "
                           "label|Indent Width, label|Tab Width, label|Font Size, "
                           "label|Bracket Pair Highlight APPEAR")
    def test_settings_text_editing_pane_reach(self, ax):
        w = rb_enter_settings_surface(ax)
        assert w is not None, "no settings window (AXIdentifier 'settings' / title 'General')"
        assert (w.name or "") == "General", (
            f"Settings must open on the 'General' pane, window title = {w.name!r}")

        before = kit.rb_showing(ax, max_depth=DEEP)
        w2 = rb_reach_settings_pane_surface(ax, "Text Editing")
        after = kit.rb_showing(ax, max_depth=DEEP)
        assert kit.rb_reach(before, after, target="label|Prefer Indent Using",
                            source="label|Reopen Behavior"), (
            "selecting the 'Text Editing' pane did not swap the General detail rows for the "
            f"Text Editing ones (new nodes: {sorted(list(after - before))[:12]})")

        assert w2 is not None, "the settings window vanished after selecting a pane"
        assert (w2.name or "") == "Text Editing", (
            f"the settings window title should equal the selected pane, got {w2.name!r}")
        for name in ("Indent Width", "Tab Width", "Font Size", "Bracket Pair Highlight",
                     "Wrap lines to editor width"):
            assert shows(ax, after, "label", name, root_id=w2.id), (
                f"the Text Editing pane is missing the label {name!r}")

        btn_names = set(names_in(ax, w2.id, role="button", max_depth=16))
        for pane in SETTINGS_PANES:
            assert pane in btn_names, (
                f"the Settings sidebar lost the {pane!r} pane button after switching panes "
                f"(buttons={sorted(btn_names)})")