summaryrefslogtreecommitdiff
path: root/test/macos_e2e.swift
blob: 5f172f9d8e1d46c4a927b0d9c8eba227afa186d1 (plain) (blame)
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
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
// pardes-macos-e2e: drive the real AppKit shell offscreen with the same kind of
// .snap script the tty backend uses, and diff the captures against goldens.
//
//   zig build macos-e2e -Dplatform=macos                     run every script
//   zig build macos-e2e -Dplatform=macos -- --update         regenerate goldens
//   zig build macos-e2e -Dplatform=macos -- test/macos-snapshots/boot.snap
//
// This is the only test the Swift half has. src/macos.zig's ABI guard proves
// the header and the Zig side agree, and it runs on Linux; nothing there ever
// constructs a PardesView, translates a gesture, or asks CoreText to paint a
// glyph. So the harness links the SHIPPING view — not a stub, and with no test
// hook bolted onto the app — into an offscreen window and calls the same public
// entry points the NSEvent overrides call. What a script exercises is what a
// hand exercises.
//
// The output format is test/snapshot.zig's header and row spelling (`== snap
// <label> grid=CxR cursor=X,Y` then one `|`-prefixed row each, right-trimmed),
// and the shared command spellings — wait, stable, text, key, resize, snap —
// are its as well. Every capture here is a WHOLE frame: the tty runner emits
// later captures as row deltas (`|<n>: <row>`, see its Prev), which this suite
// does not, so the goldens are comparable row for row but not file for file.
// Three shells render one core; a capture that
// cannot be read beside the other two backends' captures is worth much less.
//
// The hermetic world under /tmp/pardes-macos-e2e is not optional. A golden
// taken against the developer's $HOME records the developer's prompt, their
// fish greeting and their config's builtins, and is then a golden for one
// machine. Everything a shell reads is rebuilt per script before pardes_init.

import AppKit
import Darwin
import Foundation

/// Where each script's fake world is built. Fixed, not mkdtemp: the pane tag
/// prints this path, so it lands in the goldens verbatim and must not move.
private let workBase = "/tmp/pardes-macos-e2e"
private let defaultScriptDir = "test/macos-snapshots"

/// pardes_tick drains one round of pty output plus the effects it produced, and
/// a shell writing steadily can keep it returning true for as long as it has
/// something to say. The cap turns "pump until quiet" into a bounded loop;
/// `wait` and `stable` are what actually wait.
private let maxTicksPerPump = 64

/// Poll granularity for the two waiting commands. Small enough that a
/// `stable 400` has room to see several quiet slices, large enough not to spin.
private let pollInterval: TimeInterval = 0.01

private struct ScriptError: Error {
    let message: String
}

/// What the three C callbacks reach through `userdata`. A class, because a C
/// function pointer cannot capture: a pointer the runtime struct carries is the
/// only way back into Swift state.
private final class Host {
    /// Set by `wakeup`, which runs on a pty reader thread. Nothing else in the
    /// ABI may be touched from there, so this flag is the entire body — the
    /// waiting loops read it to know output is still arriving, and that a quiet
    /// slice does not yet mean the screen has settled.
    var woke = false
    /// The last text the core yanked. The app hands this to NSPasteboard; a
    /// hermetic run must not, or a script would be asserting against — and
    /// clobbering — whatever the developer last copied.
    var clipboard: String?
}

/// One rendered frame, already flattened the way a capture wants it.
private struct Frame {
    let cols: Int
    let rows: Int
    let cursorX: Int
    let cursorY: Int
    /// One entry per row, right-trimmed of spaces.
    let lines: [String]

    var text: String { lines.joined(separator: "\n") }
    var screen: String { lines.map { "|\($0)" }.joined(separator: "\n") }
}

private func trimTrailingSpaces(_ s: String) -> String {
    var out = s
    while out.hasSuffix(" ") { out.removeLast() }
    return out
}

// ---------------------------------------------------------------- the driver

/// Owns the window, the view and the core for the duration of one script.
private final class Driver: PardesViewDelegate {
    private let host = Host()
    private var window: NSWindow?
    private var view: PardesView?
    private var booted = false
    private var nativeMetrics = false
    private let scriptDirectory: String
    private var observer: NSObjectProtocol?
    private var output = ""
    private var nextAnimationFrame: Date?
    /// Where present() puts the pixels nobody reads.
    private var presentationRep: NSBitmapImageRep?

    /// The script's own file name, for error messages.
    private let scriptName: String

    init(scriptName: String, scriptDirectory: String) {
        self.scriptDirectory = scriptDirectory
        self.scriptName = scriptName
        // The app answers this notification with pump(); so does the harness,
        // and for the same reason — the view calls into the core and never
        // ticks it, so an unpumped input is an input that visibly did nothing.
        // Posting is synchronous, so this fires inside the view call, exactly
        // as it does under NSApplication.
        observer = NotificationCenter.default.addObserver(
            forName: pardesDidInputNotification, object: nil, queue: nil
        ) { [weak self] _ in
            self?.pump()
        }
    }

    deinit {
        if let observer { NotificationCenter.default.removeObserver(observer) }
    }

    // MARK: - lifecycle

    private func live() throws -> PardesView {
        guard let view, booted else {
            throw ScriptError(message: "no core yet — the script needs a `start <rows> <cols>` first")
        }
        return view
    }

    private func start(rows: Int, cols: Int) throws {
        // The ABI is a singleton — pardes_init returns 1 while one is up — so a
        // script that restarts must tear the old one down first.
        shutdown()
        // The grid is a pair of u16 all the way down, and CGFloat(cols) *
        // cellWidth is a window someone has to allocate a backing store for. A
        // typo in a script should say so, not trap in a UInt16 conversion.
        guard rows > 0, cols > 0, rows <= 500, cols <= 1000 else {
            throw ScriptError(message: "start wants a sane grid, not \(rows)x\(cols)")
        }

        // 14pt, the size AppDelegate opens the app at: the cell metrics decide
        // the window's pixel size, and `draw` records that size.
        let view = PardesView(fontSize: 14)
        let size = NSSize(
            width: CGFloat(cols) * view.cellWidth,
            height: CGFloat(rows) * view.cellHeight)
        // Borderless, and never ordered front. A titled window spends the rows
        // under its title bar out of the content rect, and the grid the core
        // boots at has to be the grid the script asked for.
        let window = NSWindow(
            contentRect: NSRect(origin: .zero, size: size),
            styleMask: .borderless,
            backing: .buffered,
            defer: false)
        window.isReleasedWhenClosed = false
        window.contentView = view
        view.setFrameSize(size)
        self.window = window
        self.view = view

        let got = view.gridSize
        guard got.cols == UInt16(cols), got.rows == UInt16(rows) else {
            throw ScriptError(
                message: "the view measured \(got.cols)x\(got.rows) cells, not the \(cols)x\(rows) the script asked for")
        }

        var runtime = pardes_runtime_s(
            userdata: Unmanaged.passUnretained(host).toOpaque(),
            wakeup: { ud in
                // A pty reader thread. One flag and out — see Host.woke.
                guard let ud else { return }
                Unmanaged<Host>.fromOpaque(ud).takeUnretainedValue().woke = true
            },
            set_clipboard: { ud, text, len in
                // Main thread, inside pardes_tick, with `text` borrowed for the
                // length of the call, so the String has to be a copy.
                guard let ud else { return }
                let host = Unmanaged<Host>.fromOpaque(ud).takeUnretainedValue()
                var yank = ""
                if let text, len > 0 {
                    let bytes = UnsafeRawBufferPointer(start: UnsafeRawPointer(text), count: len)
                    yank = String(decoding: bytes, as: UTF8.self)
                }
                host.clipboard = yank
            },
            read_clipboard: { ud in
                // Main thread, inside pardes_tick, and answered on the spot:
                // the core asked for the clipboard and pardes_paste hands it
                // back before this returns. `host.clipboard`, never
                // NSPasteboard, for the same reason as set_clipboard above.
                // No pump — the tick that emitted this effect is still
                // draining and will pick up whatever the paste queued.
                guard let ud else { return }
                let host = Unmanaged<Host>.fromOpaque(ud).takeUnretainedValue()
                let text = host.clipboard ?? ""
                text.withCString { pardes_paste($0, text.utf8.count) }
            })

        let rc = pardes_init(&runtime, got.cols, got.rows)
        guard rc == 0 else {
            throw ScriptError(message: "pardes_init returned \(rc) at \(cols)x\(rows)")
        }
        booted = true
        // Only after init, exactly as AppDelegate orders it: a resize arriving
        // before the core exists is a resize that goes nowhere, and the metrics
        // seeded below are the core's only notion of cell size.
        view.delegate = self
        pardesViewDidResize(view)
        // The resize pump adopts a startup-config Font before this report.
        // Match the app's ordering so Config sees the actual initial face.
        view.reportEffectiveFont()
    }

    func shutdown() {
        if booted {
            pardes_deinit()
            booted = false
        }
        view?.delegate = nil
        window?.contentView = nil
        window = nil
        view = nil
        presentationRep = nil
        host.clipboard = nil
        host.woke = false
    }

    // MARK: - PardesViewDelegate

    func pardesViewDidResize(_ view: PardesView) {
        let grid = view.gridSize
        // Points, not backing-store pixels. The app passes physical pixels
        // because the native PDF placement path measures in them; a golden must
        // not change when the same grid script runs on a Retina display. Pixel
        // parity scripts opt into native metrics below, including PDF placement.
        let scale: CGFloat = nativeMetrics ? (window?.backingScaleFactor ?? 1) : 1
        let cellW = UInt16(max(1, min((view.cellWidth * scale).rounded(), CGFloat(UInt16.max))))
        let cellH = UInt16(max(1, min((view.cellHeight * scale).rounded(), CGFloat(UInt16.max))))
        pardes_resize(grid.cols, grid.rows, cellW, cellH)
        if nativeMetrics {
            pardes_row_metrics(cellW, cellH,
                UInt16(max(1, (view.taglineCellWidth * scale).rounded())),
                UInt16(max(1, (view.taglineBandHeight * scale).rounded())))
        }
        pump()
    }

    func pardesViewRequestsPaste(_ view: PardesView) {
        // The core's own yank register, never NSPasteboard: reading the system
        // clipboard would let whatever the developer last copied into a golden.
        let text = host.clipboard ?? ""
        text.withCString { pardes_paste($0, text.utf8.count) }
        pump()
    }

    // MARK: - pumping

    /// Every path into the core ends here. See the ordering contract in
    /// docs/macos.md: the input functions only advance the state machine, and
    /// the writes, the spawns and the saves all happen in the drain.
    ///
    /// Deliberately does NOT take the haptic pulse the way the app's pump does.
    /// The `haptic` command is its only reader, because a pulse consumed by a
    /// background tick is a pulse no script could ever assert.
    private func pump() {
        var spins = 0
        while pardes_tick() {
            spins += 1
            if spins >= maxTicksPerPump { break }
        }
        // The app does exactly this on every pump (AppDelegate.pump). Without
        // it the `Font` builtin would set a path nobody ever collects, and a
        // script asserting the new face would be asserting the old one.
        var fontSize: UInt16 = 0
        if let view, let wanted = pardes_font_take(&fontSize) {
            view.adoptFont(path: String(cString: wanted), sizeHundredths: fontSize)
        }
        // The app reads both of these every pump too (AppDelegate.applyTheme).
        // There is no window here to dress, but the VIEW half is the same and
        // the drawing depends on it: without this a `Theme` or a
        // `WindowOpacity` in a script would move the core's settings and never
        // reach a pixel, and the capture would record the old ground forever.
        if let view {
            view.adoptThemeBG(pardes_theme_bg())
            view.adoptWindowOpacity(pardes_window_opacity())
        }
    }

    /// Hand the run loop a slice. Main-queue work (anything the view defers)
    /// runs here, and so does the sleep — see the keep-alive timer in main(),
    /// without which run(until:) returns instantly and this becomes a spin.
    private func idle() {
        RunLoop.current.run(until: Date().addingTimeInterval(pollInterval))
        let now = Date()
        guard pardes_animating() else {
            nextAnimationFrame = nil
            return
        }
        guard let due = nextAnimationFrame else {
            nextAnimationFrame = now.addingTimeInterval(1.0 / 60.0)
            return
        }
        guard now >= due else { return }
        _ = pardes_animation_tick()
        nextAnimationFrame = now.addingTimeInterval(1.0 / 60.0)
        pump()
    }

    // MARK: - waiting

    private func waitFor(ms: Int, needle: String) throws {
        let deadline = Date().addingTimeInterval(Double(ms) / 1000)
        while true {
            pump()
            let frame = readFrame()
            if frame.text.contains(needle) { return }
            if Date() >= deadline {
                throw ScriptError(
                    message: "waited \(ms)ms for \(needle.debugDescription) and never saw it; the screen was:\n"
                        + frame.screen)
            }
            idle()
        }
    }

    private func waitStable(quietMs: Int, timeoutMs: Int) {
        let deadline = Date().addingTimeInterval(Double(timeoutMs) / 1000)
        var key = stateKey()
        var quietSince = Date()
        while Date() < deadline {
            idle()
            pump()
            let now = stateKey()
            // A reader thread that woke us has bytes the next tick has not fed
            // in yet, so the screen being unchanged this instant proves nothing.
            if now != key || host.woke {
                host.woke = false
                key = now
                quietSince = Date()
                continue
            }
            if Date().timeIntervalSince(quietSince) * 1000 >= Double(quietMs) { return }
        }
    }

    /// What `stable` compares. The cursor is in it because a caret crossing an
    /// otherwise still screen is still the app doing something.
    private func stateKey() -> String {
        let frame = readFrame()
        return "\(frame.cursorX),\(frame.cursorY)\n\(frame.text)"
    }

    // MARK: - reading the grid

    private func readFrame() -> Frame {
        let count = pardes_frame()
        // The core has produced a frame; presenting it is this harness's half of
        // the contract, and it has to happen AFTER the render rather than before
        // — see present().
        defer { present() }
        let cols = Int(pardes_frame_cols())
        let rows = Int(pardes_frame_rows())
        // -1 means hidden. Clamped to 0 rather than printed, which is what
        // test/web_snapshot.mjs does, so the backends' headers stay comparable.
        let cursorX = max(0, Int(pardes_cursor_x()))
        let cursorY = max(0, Int(pardes_cursor_y()))
        guard cols > 0, rows > 0, Int(count) == cols * rows, let cells = pardes_frame_cells() else {
            return Frame(cols: cols, rows: rows, cursorX: cursorX, cursorY: cursorY, lines: [])
        }

        var grid = [[String]](repeating: [String](repeating: " ", count: cols), count: rows)
        for row in 0..<rows {
            for col in 0..<cols {
                let cell = cells[row * cols + col]
                // A never-painted cell is background only, and a zero-length one
                // is the tail half of a wide glyph. Both read as a space, which
                // is what the tty oracle's emulator hands back for them too.
                if cell.flags & UInt8(PARDES_CELL_DEFAULT) != 0 || cell.len == 0 { continue }
                grid[row][col] = cellText(cell)
            }
        }
        compositeTagLayers(into: &grid, cols: cols, rows: rows)
        let lines = grid.map { trimTrailingSpaces($0.joined()) }
        return Frame(cols: cols, rows: rows, cursorX: cursorX, cursorY: cursorY, lines: lines)
    }

    /// prefix clamps, so a bogus len cannot walk off the eight bytes, and
    /// String(decoding:) substitutes U+FFFD rather than trapping on invalid
    /// UTF-8 — a capture has to be able to RECORD garbage, not die of it.
    private func cellText(_ cell: pardes_cell_s) -> String {
        let text = withUnsafeBytes(of: cell.text) { raw in
            String(decoding: raw.prefix(Int(cell.len)), as: UTF8.self)
        }
        return text.isEmpty ? " " : text
    }

    /// Tag text is not in the frame grid any more. The core paints the topbar,
    /// the column bar and every pane tag into tag layers of their own so a GUI
    /// shell can set them at the smaller tagline pitch (Pardes.renderTagLayers);
    /// the grid keeps only the chrome under them and the physical grips. A
    /// capture that reads the grid alone therefore records blank header rows.
    ///
    /// Flatten the layers back over the grid at ONE cell per column. That is
    /// the tty backend's spelling, and these goldens exist to stay comparable
    /// with the tty ones row for row — the sub-cell pitch the layers carry is a
    /// pixel concern with nowhere to live in a character grid.
    private func compositeTagLayers(into grid: inout [[String]], cols: Int, rows: Int) {
        for index in 0..<pardes_tag_layer_limit() {
            let layerCols = Int(pardes_tag_layer_value(index, 0))
            guard layerCols > 0, let cells = pardes_tag_layer_cells(index) else { continue }
            let x = Int(pardes_tag_layer_value(index, 4))
            let y = Int(pardes_tag_layer_value(index, 5))
            // A layer is allocated wide enough for text the viewport may crop,
            // so the viewport — not the cell count — decides what is on screen.
            let width = Int(pardes_tag_layer_value(index, 6))
            guard y >= 0, y < rows else { continue }
            for col in 0..<min(layerCols, width) {
                let at = x + col
                if at < 0 { continue }
                if at >= cols { break }
                let cell = cells[col]
                if cell.flags & UInt8(PARDES_CELL_DEFAULT) != 0 || cell.len == 0 { continue }
                grid[y][at] = cellText(cell)
            }
        }
    }

    // MARK: - captures

    private func snap(_ label: String) {
        let frame = readFrame()
        output += "== snap \(label) grid=\(frame.cols)x\(frame.rows) cursor=\(frame.cursorX),\(frame.cursorY)\n"
        for line in frame.lines { output += "|\(line)\n" }
    }

    /// Put the frame readFrame() just produced on screen — for a window that has
    /// no screen, into a bitmap. draw(_:) is the only caller of
    /// pardes_frame_presented, and this window is deliberately never ordered
    /// front, so without this nothing here would ever present anything: the core
    /// would owe a presentation for the rest of the script and correctly hold
    /// every pointer gesture after the first layout change inert, addressing
    /// pixels no backend had shown. The app pays the same debt on every pump
    /// (AppDelegate.pump marks the view, AppKit's display cycle draws it).
    ///
    /// The rep is kept and reused rather than allocated per frame: this runs on
    /// every poll slice, and cacheDisplay only needs somewhere to put pixels
    /// nobody reads. `draw` makes its own, because it reads them.
    private func present() {
        guard let view, view.bounds.width >= 1, view.bounds.height >= 1 else { return }
        let bounds = view.bounds
        if presentationRep?.size != bounds.size {
            presentationRep = view.bitmapImageRepForCachingDisplay(in: bounds)
        }
        guard let rep = presentationRep else { return }
        view.cacheDisplay(in: bounds, to: rep)
    }

    /// Render the view the way AppKit would and prove the CoreText pass put
    /// something on the screen. `snap` reads the core's cell buffer and would be
    /// perfectly happy with a draw(_:) that returned on its first line; this is
    /// the only command that touches the drawing code at all.
    ///
    /// "Not blank" is spelled "not every pixel identical" rather than "not equal
    /// to the background colour": it needs no agreement with the view about what
    /// that colour is or what channel order the bitmap uses, and a view that
    /// painted one flat rect of anything is just as broken as one that painted
    /// nothing.
    private func draw(_ label: String) throws {
        let view = try live()
        let bounds = view.bounds
        guard let rep = view.bitmapImageRepForCachingDisplay(in: bounds) else {
            throw ScriptError(message: "draw \(label): the view would not make a bitmap for \(bounds.size)")
        }
        view.cacheDisplay(in: bounds, to: rep)
        guard let data = rep.bitmapData, rep.pixelsWide > 0, rep.pixelsHigh > 0 else {
            throw ScriptError(message: "draw \(label): cacheDisplay produced no pixels")
        }

        let bytesPerPixel = max(1, rep.bitsPerPixel / 8)
        // Not `stride`, which is a standard-library function this would shadow.
        // Rows can be padded, so only the first pixelsWide of each are pixels.
        let rowBytes = rep.bytesPerRow
        var uniform = true
        scan: for y in 0..<rep.pixelsHigh {
            let row = data + y * rowBytes
            for x in 0..<rep.pixelsWide {
                let pixel = row + x * bytesPerPixel
                for byte in 0..<bytesPerPixel where pixel[byte] != data[byte] {
                    uniform = false
                    break scan
                }
            }
        }
        // The size recorded is the view's in POINTS, not the bitmap's in device
        // pixels: the same script on a Retina machine caches a 2x rep, and a
        // golden must not know which display the developer used.
        let w = Int(bounds.width.rounded())
        let h = Int(bounds.height.rounded())
        if uniform {
            throw ScriptError(
                message: "draw \(label): every pixel of the \(w)x\(h) view is identical — the CoreText pass drew nothing")
        }
        output += "== draw \(label) \(w)x\(h) nonblank\n"
    }

    /// Forge's topbar must contain light ink, not CoreText's default black.
    /// Restrict the sample to text, excluding grips, pane bodies and cursors.
    private func drawTagInk(_ label: String) throws {
        let view = try live()
        let bounds = view.bounds
        guard let rep = view.bitmapImageRepForCachingDisplay(in: bounds) else {
            throw ScriptError(message: "draw-tag-ink: no bitmap")
        }
        view.cacheDisplay(in: bounds, to: rep)
        let scale = CGFloat(rep.pixelsWide) / bounds.width
        var brightest: CGFloat = 0
        for y in 0..<Int(view.cellHeight * scale) {
            for x in Int(3 * view.cellWidth * scale)..<Int(25 * view.cellWidth * scale) {
                if let color = rep.colorAt(x: x, y: y)?.usingColorSpace(.sRGB) {
                    brightest = max(brightest, min(color.redComponent, color.greenComponent, color.blueComponent))
                }
            }
        }
        guard brightest > 0.5 else {
            throw ScriptError(message: "draw-tag-ink: Forge topbar has no light foreground ink")
        }
        if let directory = ProcessInfo.processInfo.environment["PARDES_TEST_CAPTURE_DIR"],
           let png = rep.representation(using: .png, properties: [:]) {
            try png.write(to: URL(fileURLWithPath: directory).appendingPathComponent(label + ".png"))
        }
        output += "== tag-ink \(label) visible\n"
    }

    /// The alpha range of a drawn frame, recorded into the golden.
    ///
    /// The contract WindowOpacity states (shaders/ui.frag.glsl, and
    /// PardesView.backgroundAlpha for this shell) is two-sided, so one number
    /// could not express it: BACKGROUNDS take the setting, and glyph ink stays
    /// opaque. A minimum below 255 is the ground letting the desktop through;
    /// a maximum of 255 is the ink still sitting on top of it. At
    /// `WindowOpacity 100` both ends are 255 and the view is opaque again.
    private func drawOpacity(_ label: String) throws {
        let view = try live()
        let bounds = view.bounds
        guard let rep = view.bitmapImageRepForCachingDisplay(in: bounds) else {
            throw ScriptError(message: "draw-opacity \(label): the view would not make a bitmap for \(bounds.size)")
        }
        view.cacheDisplay(in: bounds, to: rep)
        guard let data = rep.bitmapData, rep.pixelsWide > 0, rep.pixelsHigh > 0 else {
            throw ScriptError(message: "draw-opacity \(label): cacheDisplay produced no pixels")
        }
        guard rep.hasAlpha, rep.bitsPerPixel == 32 else {
            // An opaque view caches into a rep with no alpha at all, which is
            // itself the answer at WindowOpacity 100 — say so rather than
            // reporting a range read out of the wrong byte.
            output += "== draw-opacity \(label) \(Int(bounds.width.rounded()))x\(Int(bounds.height.rounded())) opaque\n"
            return
        }
        // Where alpha sits depends on the rep's format, and only the two
        // AppKit actually hands back here are worth decoding.
        let alphaFirst = rep.bitmapFormat.contains(.alphaFirst)
        let offset = alphaFirst ? 0 : 3
        let rowBytes = rep.bytesPerRow
        var lowest: UInt8 = 255
        var highest: UInt8 = 0
        for y in 0..<rep.pixelsHigh {
            let row = data + y * rowBytes
            for x in 0..<rep.pixelsWide {
                let alpha = row[x * 4 + offset]
                if alpha < lowest { lowest = alpha }
                if alpha > highest { highest = alpha }
            }
        }
        let w = Int(bounds.width.rounded())
        let h = Int(bounds.height.rounded())
        output += "== draw-opacity \(label) \(w)x\(h) alpha \(lowest)..\(highest)\n"
    }

    private func renderedCapture(_ label: String) throws -> NSBitmapImageRep {
        let view = try live()
        guard let rep = view.bitmapImageRepForCachingDisplay(in: view.bounds) else {
            throw ScriptError(message: "capture: no bitmap")
        }
        view.cacheDisplay(in: view.bounds, to: rep)
        if let directory = ProcessInfo.processInfo.environment["PARDES_TEST_CAPTURE_DIR"],
           let png = rep.representation(using: .png, properties: [:]) {
            try png.write(to: URL(fileURLWithPath: directory).appendingPathComponent(label + ".png"))
        }
        return rep
    }

    // colorAt labels components as calibrated RGB even for a Display P3
    // bitmap. Reattach the bitmap's actual profile before comparing sRGB.
    private func sample(_ rep: NSBitmapImageRep, x: Int, y: Int) -> NSColor? {
        guard let raw = rep.colorAt(x: x, y: y) else { return nil }
        let components = [raw.redComponent, raw.greenComponent, raw.blueComponent, raw.alphaComponent]
        return NSColor(colorSpace: rep.colorSpace, components: components, count: 4).usingColorSpace(.sRGB)
    }

    private func checkBackgrounds(_ label: String) throws {
        let view = try live(), rep = try renderedCapture(label)
        let scale = CGFloat(rep.pixelsWide) / view.bounds.width
        func check(x: CGFloat, y: CGFloat, rgb: UInt32, name: String) throws {
            guard let c = sample(rep, x: Int(x * scale), y: Int(y * scale)) else {
                throw ScriptError(message: "\(name): no pixel")
            }
            guard abs(c.alphaComponent - view.backgroundAlpha) < 2.0 / 255 else {
                throw ScriptError(message: "\(name): background alpha \(c.alphaComponent), expected \(view.backgroundAlpha)")
            }
            if view.backgroundAlpha > 0 {
                let actual = [c.redComponent, c.greenComponent, c.blueComponent]
                let expected = [CGFloat((rgb >> 16) & 255), CGFloat((rgb >> 8) & 255), CGFloat(rgb & 255)]
                guard zip(actual, expected).allSatisfy({ abs($0 * 255 - $1) < 4 }) else {
                    throw ScriptError(message: "\(name): tag background does not cover the full row: \(actual) vs \(expected)")
                }
            }
        }
        for i in 0..<pardes_tag_layer_limit() {
            guard pardes_tag_layer_value(i, 0) > 0 else { continue }
            let x = CGFloat(pardes_tag_layer_value(i, 4) + pardes_tag_layer_value(i, 6)) * view.cellWidth - 2 / scale
            let top = CGFloat(pardes_tag_layer_value(i, 5)) * view.cellHeight
            let height = Int(view.cellHeight * scale)
            let kind = pardes_tag_layer_value(i, 1)
            let bottom = kind == 2 && pardes_tag_layer_value(i, 11) != 0
            for pixel in 0..<height {
                var rgb = pardes_tag_layer_value(i, 10)
                if kind != 0 && (bottom ? pixel <= 1 : pixel >= height - 2) { rgb = 0x606f86 }
                if pardes_tag_layer_value(i, 5) == UInt32(PARDES_TOPBAR_H) && pixel == 0 { rgb = 0x606f86 }
                try check(x: x, y: top + (CGFloat(pixel) + 0.5) / scale,
                    rgb: rgb, name: "tag \(i), pixel \(pixel)")
            }
        }
        try check(x: view.bounds.width - 2 * view.cellWidth,
                  y: view.bounds.height - 2 * view.cellHeight,
                  rgb: view.themeBG ?? pardesDefaultBG, name: "body")
        output += "== backgrounds \(label) uniform\n"
    }

    private func checkContext(_ label: String) throws {
        let view = try live(), rep = try renderedCapture(label)
        let scale = CGFloat(rep.pixelsWide) / view.bounds.width
        var headers = 0, separators = 0
        for i in 0..<pardes_body_layer_limit() {
            let count = Int(pardes_body_layer_value(i, 2))
            guard count > 0 else { continue }
            headers += count
            let x = CGFloat(pardes_body_layer_value(i, 3) + pardes_body_layer_value(i, 5)) * view.cellWidth - 2 / scale
            let top = CGFloat(pardes_body_layer_value(i, 4)) * view.cellHeight
            for row in 0..<count where pardes_body_layer_value(i, UInt32(11 + row)) != 0 {
                separators += 1
                let y = top + CGFloat(row + 1) * view.taglineBandHeight - 0.5 / scale
                guard let c = sample(rep, x: Int(x * scale), y: Int(y * scale)) else {
                    throw ScriptError(message: "context: no separator pixel")
                }
                let rgb: UInt32 = 0x606f86 // Forge border, also used by the Linux chrome overlay.
                guard abs(c.redComponent * 255 - CGFloat((rgb >> 16) & 255)) < 4,
                      abs(c.greenComponent * 255 - CGFloat((rgb >> 8) & 255)) < 4,
                      abs(c.blueComponent * 255 - CGFloat(rgb & 255)) < 4,
                      abs(c.alphaComponent - view.backgroundAlpha) < 2.0 / 255 else {
                    throw ScriptError(message: "context: separator is misplaced or has accumulated opacity")
                }
            }
        }
        guard headers >= 2, separators > 0 else {
            throw ScriptError(message: "context: expected nested compact declarations, got \(headers) rows")
        }
        output += "== context \(label) compact separators verified\n"
    }

    private func checkPDF(_ label: String) throws {
        let view = try live(), rep = try renderedCapture(label)
        guard nativeMetrics, pardes_frame_images() > 0, let images = pardes_frame_image_list() else {
            throw ScriptError(message: "PDF: no native image placements")
        }
        let scale = window?.backingScaleFactor ?? 1
        let image = images[0]
        let x = CGFloat(image.cell_x) * view.cellWidth + CGFloat(image.dst_x) / scale
        let y = CGFloat(image.cell_y) * view.cellHeight + (CGFloat(image.dst_y) + CGFloat(image.offset_y)) / scale
        let width = CGFloat(image.dst_w) / scale, height = CGFloat(image.dst_h) / scale
        guard width > view.cellWidth * 4, height > view.cellHeight * 2,
              y >= CGFloat(image.cell_y) * view.cellHeight - 1,
              x + width <= view.bounds.width + 1, y + height <= view.bounds.height + 1 else {
            throw ScriptError(message: "PDF: placement is outside its physical-pixel viewport")
        }
        let backing = CGFloat(rep.pixelsWide) / view.bounds.width
        guard image.paper_bg != UInt32(PARDES_COLOR_DEFAULT) else {
            throw ScriptError(message: "PDF: missing separate paper background")
        }
        var lowest: CGFloat = 1, highest: CGFloat = 0
        for py in stride(from: Int(y * backing) + 2, to: Int((y + height) * backing) - 2, by: 2) {
            for px in stride(from: Int(x * backing) + 2, to: Int((x + width) * backing) - 2, by: 2) {
                if let c = rep.colorAt(x: px, y: py) {
                    lowest = min(lowest, c.alphaComponent)
                    highest = max(highest, c.alphaComponent)
                }
            }
        }
        guard abs(lowest - view.backgroundAlpha) < 2.0 / 255, highest > 0.98 else {
            throw ScriptError(message: "PDF: expected translucent paper and opaque ink, got alpha \(lowest)...\(highest)")
        }
        output += "== pdf \(label) paper opacity and opaque ink verified\n"
    }

    // MARK: - the script

    func run(source: String) throws -> String {
        var lineno = 0
        for raw in source.split(separator: "\n", omittingEmptySubsequences: false) {
            lineno += 1
            let line = String(raw).trimmingCharacters(in: CharacterSet(charactersIn: " \t\r"))
            if line.isEmpty || line.hasPrefix("#") { continue }
            do {
                try step(line)
            } catch let error as ScriptError {
                throw ScriptError(message: "\(scriptName):\(lineno): \(line)\n  \(error.message)")
            }
        }
        return output
    }

    private func step(_ line: String) throws {
        let split = line.firstIndex(of: " ")
        let cmd = String(split.map { line[..<$0] } ?? Substring(line))
        // Kept verbatim for `text`, `clipboard` and the labels, where the spaces
        // are part of the payload.
        let rest = split.map { String(line[line.index(after: $0)...]) } ?? ""
        let args = rest.split(separator: " ").map(String.init)

        switch cmd {
        case "native-metrics":
            nativeMetrics = true
            pardesViewDidResize(try live())
        case "open-fixture":
            _ = try live()
            let path = URL(fileURLWithPath: scriptDirectory).appendingPathComponent(rest).standardized.path
            let command = "Look " + path
            pardes_command(command, command.utf8.count)
            pump()
        case "check-backgrounds":
            try checkBackgrounds(rest)
        case "check-context":
            try checkContext(rest)
        case "check-pdf":
            try checkPDF(rest)
        case "capture":
            _ = try renderedCapture(rest)
        case "start":
            let rows = try int(args, 0, "start rows")
            let cols = try int(args, 1, "start cols")
            try start(rows: rows, cols: cols)

        case "wait":
            let ms = try int(args, 0, "wait timeout")
            let needle = rest.drop(while: { $0 != " " }).dropFirst()
            guard !needle.isEmpty else { throw ScriptError(message: "wait needs text to look for") }
            try waitFor(ms: ms, needle: String(needle))

        case "stable":
            _ = try live()
            let quiet = try int(args, 0, "stable quiet")
            let timeout = try int(args, 1, "stable timeout")
            waitStable(quietMs: quiet, timeoutMs: timeout)

        case "text":
            let view = try live()
            guard !rest.isEmpty else { throw ScriptError(message: "text needs something to type") }
            // Per SCALAR, not per Character: pardes_key takes one codepoint, and
            // a grapheme cluster is not one.
            for scalar in rest.unicodeScalars {
                view.typeKey(scalar.value, text: String(scalar), mods: 0)
            }
            pump()

        // A builtin command line, the way the menu and the nested-Look socket
        // both deliver one. The only way a script can reach a builtin that has
        // no key of its own, `Font` among them.
        case "command":
            _ = try live()
            guard !rest.isEmpty else { throw ScriptError(message: "command needs a command") }
            pardes_command(rest, rest.utf8.count)
            pump()

        // The face actually worn, by PostScript name. Asserted rather than
        // snapshotted because a snapshot is the core's cell buffer and the
        // core has no font: everything about which face is on screen lives on
        // this side of the ABI, so this is the only place it can be checked.
        case "font":
            let view = try live()
            guard view.faceName == rest else {
                throw ScriptError(message: "wearing \(view.faceName.debugDescription), wanted \(rest.debugDescription)")
            }

        // The host-owned half of Config's font tuple. Unlike a grid snapshot,
        // this observes the point size CoreText is actually wearing and catches
        // a zoom which resized cells but forgot to acknowledge runtime state.
        case "font-size":
            let view = try live()
            let want = try double(args, 0, "font-size points")
            guard abs(Double(view.effectivePointSize) - want) < 0.005 else {
                throw ScriptError(message: "wearing \(view.effectivePointSize)pt, wanted \(want)pt")
            }

        // Cmd+ / Cmd- / Cmd+0, minus the menu. What the grid does afterwards
        // is the assertion: a bigger cell fits fewer columns in the same
        // window, so a zoom that changed nothing shows up as a golden that
        // did not move.
        case "zoom":
            let view = try live()
            if rest == "reset" {
                view.zoomReset()
            } else {
                guard let step = Double(rest) else {
                    throw ScriptError(message: "zoom takes a point delta or `reset`, got \(rest.debugDescription)")
                }
                view.zoom(by: CGFloat(step))
            }
            pump()

        case "key":
            let view = try live()
            guard !args.isEmpty else { throw ScriptError(message: "key needs a name") }
            for name in args {
                let stroke = try keyStroke(name)
                view.typeKey(stroke.cp, text: "", mods: stroke.mods)
            }
            pump()

        case "mouse":
            let view = try live()
            let button = try mouseButton(try token(args, 0, "mouse button"))
            let phase = try token(args, 1, "mouse phase")
            let cell = try gridPoint(args, 2, "mouse")
            switch phase {
            case "press": view.press(button, at: cell)
            case "release": view.release(button, at: cell)
            case "drag": view.drag(button, to: cell)
            // The view's hover entry point carries no button, because a
            // button-less move is the only motion AppKit reports as its own
            // event. The token is accepted and ignored so that all four phases
            // stay spelled the same way.
            case "motion": view.motion(to: cell)
            default:
                throw ScriptError(message: "mouse phase must be press, release, drag or motion, not \(phase)")
            }
            pump()

        case "click":
            let view = try live()
            let button = try mouseButton(try token(args, 0, "click button"))
            let cell = try gridPoint(args, 1, "click")
            view.click(button, at: cell)
            pump()

        // A click driven through the NSEvent override rather than the decoded
        // entry point, i.e. the AppKit adapter itself.
        //
        // This exists because a bug lived exactly here and every other test
        // walked past it: `click` calls view.click(_:at:), which is downstream
        // of mouseDown(with:), so an adapter that dropped every event on the
        // floor still passed the whole suite. It dropped them because it asked
        // a mouse event for its touch set, which raises; AppKit caught the
        // throw inside its own dispatch and abandoned the handler, so nothing
        // crashed and nothing logged and no click did anything.
        //
        // NSEvent.mouseEvent can build the real thing, so the adapter is no
        // longer the untestable part. Anything the override does to the event
        // that a mouse event does not support now fails here.
        case "nsclick":
            let view = try live()
            guard let window = self.window else {
                throw ScriptError(message: "nsclick before start")
            }
            let kind = try token(args, 0, "nsclick button")
            let cell = try gridPoint(args, 1, "nsclick")
            // Cell centre, in the flipped view's coordinates, back into the
            // window's bottom-left origin that NSEvent wants.
            let inView = CGPoint(x: CGFloat(cell.col) * view.cellWidth + view.cellWidth / 2,
                                 y: CGFloat(cell.row) * view.cellHeight + view.cellHeight / 2)
            let inWindow = view.convert(inView, to: nil)
            let phases: [(NSEvent.EventType, NSEvent.EventType)] = switch kind {
            case "right": [(.rightMouseDown, .rightMouseUp)]
            case "middle", "other": [(.otherMouseDown, .otherMouseUp)]
            default: [(.leftMouseDown, .leftMouseUp)]
            }
            for (down, up) in phases {
                for type in [down, up] {
                    guard let event = NSEvent.mouseEvent(
                        with: type, location: inWindow, modifierFlags: [], timestamp: 0,
                        windowNumber: window.windowNumber, context: nil,
                        eventNumber: 0, clickCount: 1, pressure: type == down ? 1 : 0)
                    else { throw ScriptError(message: "nsclick: could not build a \(type) event") }
                    switch type {
                    case .rightMouseDown: view.rightMouseDown(with: event)
                    case .rightMouseUp: view.rightMouseUp(with: event)
                    case .otherMouseDown: view.otherMouseDown(with: event)
                    case .otherMouseUp: view.otherMouseUp(with: event)
                    case .leftMouseDown: view.mouseDown(with: event)
                    default: view.mouseUp(with: event)
                    }
                }
            }
            pump()

        case "fingers":
            let view = try live()
            // The whole finger-count feature, asserted without a trackpad: the
            // policy is pure and lives in Trackpad, so a script names the
            // finger count and gets the button a hand gets.
            //
            // The stream is the one macOS actually uses for a multi-finger
            // click when its own secondary click is on, which is the default
            // and which is what real hardware was observed doing for BOTH two
            // and three fingers. Passing RIGHT here is therefore the harder
            // case: it is the one where a view that trusted the stream would
            // call every multi-finger click a Look instead of an Exec.
            let count = try int(args, 0, "fingers count")
            let cell = try gridPoint(args, 1, "fingers")
            let stream = count >= 2 ? PARDES_MOUSE_RIGHT : PARDES_MOUSE_LEFT
            view.click(Trackpad.button(stream: stream, fingers: count), at: cell)
            pump()

        case "force":
            let view = try live()
            let cell = try gridPoint(args, 0, "force")
            view.click(Trackpad.forceClickButton, at: cell)
            pump()

        // `rotate <degrees> [gap_ms]`. The optional gap is a real sleep BEFORE
        // the event, and it is the only way a script can say how FAST the dial
        // is being turned: libpardes measures the release speed off the
        // monotonic clock between events, so back-to-back script calls read as
        // an impossibly hard flick. Pace them and a slow twist is genuinely
        // slow — which is the half of the momentum contract worth asserting,
        // because "no fling" is not something a fling test can show.
        case "rotate":
            let view = try live()
            let degrees = try double(args, 0, "rotate degrees")
            if args.count > 1 {
                Thread.sleep(forTimeInterval: try double(args, 1, "rotate gap_ms") / 1000)
            }
            view.rotate(degrees: CGFloat(degrees))
            pump()

        // The fingers coming off. Its own command because the fling is decided
        // by the RELEASE SPEED, and a script that could only turn the dial
        // could never throw it — NSEvent phases have no public constructor, so
        // this entry point is the only way the momentum path is reachable at
        // all. The coast is then spent by idle's display clock, at one fixed
        // step per animation frame; ordinary pumps do not move it.
        case "rotate_end":
            let view = try live()
            view.rotateEnd()
            pump()

        // `drop <path> <col> <row>`: a file dropped ON the grid at that cell.
        // Same reason as the two above — `NSDraggingInfo` is a protocol with a
        // dozen members and no public conformer, so the entry point below the
        // event is the only honest way in. What it must prove is the WHERE: a
        // drop is a click plus Look, so the document lands beside the pane
        // pointed at rather than beside whichever one had focus.
        case "drop":
            let view = try live()
            let path = try token(args, 0, "drop path")
            let cell = try gridPoint(args, 1, "drop")
            view.drop([path], at: cell)
            pump()

        // `scroll <rows> <col> <row> [cols] [gap_ms]`. The optional gap is a
        // real sleep BEFORE the event and means what it does for `rotate`:
        // libpardes measures the release speed off the monotonic clock between
        // calls, so back-to-back script lines read as an impossibly fast swipe.
        // Pacing them is the only way a script can say a swipe was SLOW, which
        // is the half of the momentum contract a fling test cannot show.
        case "scroll":
            let view = try live()
            let rows = try double(args, 0, "scroll rows")
            let cell = try gridPoint(args, 1, "scroll")
            // The horizontal delta is an OPTIONAL FOURTH token, appended rather
            // than inserted, so the three-token form still reads the way the
            // other suites' scroll commands do.
            var cols = 0.0
            if args.count > 3 { cols = try double(args, 3, "scroll cols") }
            if args.count > 4 {
                Thread.sleep(forTimeInterval: try double(args, 4, "scroll gap_ms") / 1000)
            }
            view.scroll(rows: CGFloat(rows), cols: CGFloat(cols), at: cell)
            pump()

        // Fingers down and fingers up. Their own commands for the reason
        // rotate_end is one: the fling is decided by the RELEASE SPEED, and
        // NSEvent phases have no public constructor, so these entry points are
        // the only way the momentum path is reachable from a script at all.
        // The coast is then spent by idle's display clock, one step per
        // animation frame; ordinary pumps do not move it.
        case "scroll_begin":
            let view = try live()
            view.scrollBegin()
            pump()

        case "scroll_end":
            let view = try live()
            view.scrollEnd()
            pump()

        case "wheel":
            let view = try live()
            let button = try mouseButton(try token(args, 0, "wheel button"))
            let cell = try gridPoint(args, 1, "wheel")
            view.wheel(button, at: cell)
            pump()

        case "resize":
            let view = try live()
            let rows = try int(args, 0, "resize rows")
            let cols = try int(args, 1, "resize cols")
            guard rows > 0, cols > 0, rows <= 500, cols <= 1000 else {
                throw ScriptError(message: "resize wants a sane grid, not \(rows)x\(cols)")
            }
            let size = NSSize(
                width: CGFloat(cols) * view.cellWidth,
                height: CGFloat(rows) * view.cellHeight)
            window?.setContentSize(size)
            view.setFrameSize(size)
            // Pushed by hand rather than trusted to fall out of setFrameSize:
            // whether AppKit calls back depends on how the view watches its own
            // bounds, and a duplicate resize is a no-op by design (the core
            // compares the effective viewport, not the event).
            pardesViewDidResize(view)

        case "haptic":
            _ = try live()
            let want = try hapticPulse(try token(args, 0, "haptic pulse"))
            let got = pardes_take_haptic()
            guard got == want else {
                throw ScriptError(message: "expected the \(hapticName(want)) pulse, got \(hapticName(got))")
            }

        case "clipboard":
            _ = try live()
            guard let yank = host.clipboard else {
                throw ScriptError(message: "the core never set the clipboard, wanted \(rest.debugDescription)")
            }
            guard yank == rest else {
                throw ScriptError(message: "clipboard holds \(yank.debugDescription), wanted \(rest.debugDescription)")
            }

        case "snap":
            _ = try live()
            guard !rest.isEmpty else { throw ScriptError(message: "snap needs a label") }
            snap(rest)

        case "draw":
            guard !rest.isEmpty else { throw ScriptError(message: "draw needs a label") }
            try draw(rest)

        // What WindowOpacity actually did to the pixels, which is the only
        // place it can be checked: the core's cell buffer says nothing about
        // alpha, and `draw` deliberately compares channels without knowing
        // which one is which.
        case "draw-tag-ink":
            try drawTagInk(rest)

        case "draw-opacity":
            guard !rest.isEmpty else { throw ScriptError(message: "draw-opacity needs a label") }
            try drawOpacity(rest)

        case "draw-effect":
            let view = try live()
            guard !rest.isEmpty else { throw ScriptError(message: "draw-effect needs a label") }
            try draw(rest)
            guard view.lastFrameUsedPostprocessor else {
                throw ScriptError(message: "draw-effect \(rest): runtime Metal postprocess was bypassed or failed")
            }

        // Snapshot and validate the plain panel-track ABI. A subsequent draw
        // drives those exact records through the runtime-compiled Metal kernel.
        case "tracks":
            _ = try live()
            _ = pardes_frame()
            let count = Int(pardes_frame_panel_tracks())
            guard count == args.count else {
                throw ScriptError(message: "got \(count) panel tracks, wanted \(args.count): \(rest)")
            }
            guard count == 0 || pardes_frame_panel_track_list() != nil else {
                throw ScriptError(message: "panel track count is \(count), but its list is nil")
            }
            if let list = pardes_frame_panel_track_list() {
                for i in 0..<count {
                    let track = list[i]
                    let phase = track.phase == UInt8(PARDES_PANEL_MOVING) ? "moving" :
                        track.phase == UInt8(PARDES_PANEL_OPENING) ? "opening" : "unknown"
                    let effect: String = switch track.effect {
                    case UInt8(PARDES_PANEL_SLIDE): "slide"
                    case UInt8(PARDES_PANEL_ZOOM): "zoom"
                    case UInt8(PARDES_PANEL_DISSOLVE): "dissolve"
                    case UInt8(PARDES_PANEL_ASCII): "ascii"
                    case UInt8(PARDES_PANEL_VERTICAL): "vertical"
                    case UInt8(PARDES_PANEL_EDGES): "edges"
                    case UInt8(PARDES_PANEL_FALL): "fall"
                    case UInt8(PARDES_PANEL_WAVE): "wave"
                    case UInt8(PARDES_PANEL_CURTAIN): "curtain"
                    case UInt8(PARDES_PANEL_SCRAMBLE): "scramble"
                    case UInt8(PARDES_PANEL_TYPEWRITER): "typewriter"
                    default: "off"
                    }
                    let got = "\(phase):\(effect)"
                    guard got == args[i] else {
                        throw ScriptError(message: "track \(i) is \(got), wanted \(args[i])")
                    }
                }
            }

        default:
            throw ScriptError(message: "unknown command \(cmd)")
        }
    }
}

// ---------------------------------------------------------------- vocabulary

/// The keys that carry no text: the four ASCII controls and the private-use
/// navigation block, plus test/snapshot.zig's `c-<ch>`/`a-<ch>` chord spelling.
/// Both name sets are accepted (`esc`/`escape`, `bs`/`backspace`,
/// `pgup`/`pageup`) so a script reads the same in either suite.
private func keyStroke(_ name: String) throws -> (cp: UInt32, mods: UInt32) {
    switch name {
    case "enter", "ret": return (UInt32(PARDES_KEY_ENTER), 0)
    case "escape", "esc": return (UInt32(PARDES_KEY_ESCAPE), 0)
    case "tab": return (UInt32(PARDES_KEY_TAB), 0)
    case "backspace", "bs": return (UInt32(PARDES_KEY_BACKSPACE), 0)
    case "up": return (UInt32(PARDES_KEY_UP), 0)
    case "down": return (UInt32(PARDES_KEY_DOWN), 0)
    case "left": return (UInt32(PARDES_KEY_LEFT), 0)
    case "right": return (UInt32(PARDES_KEY_RIGHT), 0)
    case "home": return (UInt32(PARDES_KEY_HOME), 0)
    case "end": return (UInt32(PARDES_KEY_END), 0)
    case "pageup", "pgup": return (UInt32(PARDES_KEY_PAGE_UP), 0)
    case "pagedown", "pgdn": return (UInt32(PARDES_KEY_PAGE_DOWN), 0)
    case "delete", "del": return (UInt32(PARDES_KEY_DELETE), 0)
    default: break
    }
    // A chord is the only way to reach the core's Ctrl bindings, and one of them
    // — Ctrl-b — is how a terminal pane leaves raw tty mode, which every script
    // that clicks on a word first has to do. The text is deliberately empty: the
    // core reads the codepoint and the modifier, never a control character.
    let scalars = Array(name.unicodeScalars)
    if scalars.count == 3, scalars[1] == "-" {
        switch scalars[0] {
        case "c": return (scalars[2].value, UInt32(PARDES_MOD_CTRL))
        case "a": return (scalars[2].value, UInt32(PARDES_MOD_ALT))
        default: break
        }
    }
    throw ScriptError(message: "unknown key \(name)")
}

private func mouseButton(_ name: String) throws -> pardes_mouse_button_e {
    switch name {
    // The honest token for a button-less move. The view's motion(to:) carries
    // no button at all, so this only ever reaches `mouse none motion`.
    case "none": return PARDES_MOUSE_NONE
    case "left": return PARDES_MOUSE_LEFT
    case "middle": return PARDES_MOUSE_MIDDLE
    case "right": return PARDES_MOUSE_RIGHT
    case "wheelup": return PARDES_MOUSE_WHEEL_UP
    case "wheeldown": return PARDES_MOUSE_WHEEL_DOWN
    case "wheelleft": return PARDES_MOUSE_WHEEL_LEFT
    case "wheelright": return PARDES_MOUSE_WHEEL_RIGHT
    default: throw ScriptError(message: "unknown mouse button \(name)")
    }
}

private func hapticPulse(_ name: String) throws -> pardes_haptic_e {
    switch name {
    case "none": return PARDES_HAPTIC_NONE
    case "exec": return PARDES_HAPTIC_EXEC
    case "look": return PARDES_HAPTIC_LOOK
    default: throw ScriptError(message: "unknown haptic pulse \(name)")
    }
}

private func hapticName(_ pulse: pardes_haptic_e) -> String {
    if pulse == PARDES_HAPTIC_EXEC { return "exec" }
    if pulse == PARDES_HAPTIC_LOOK { return "look" }
    return "none"
}

private func token(_ args: [String], _ index: Int, _ what: String) throws -> String {
    guard index < args.count else { throw ScriptError(message: "missing \(what)") }
    return args[index]
}

private func int(_ args: [String], _ index: Int, _ what: String) throws -> Int {
    let raw = try token(args, index, what)
    guard let value = Int(raw) else {
        throw ScriptError(message: "\(what) is not a number: \(raw)")
    }
    return value
}

private func uint16(_ args: [String], _ index: Int, _ what: String) throws -> UInt16 {
    let raw = try token(args, index, what)
    guard let value = UInt16(raw) else {
        throw ScriptError(message: "\(what) is not a cell coordinate: \(raw)")
    }
    return value
}

/// A `<col> <row>` pair, always in that order and always 0-based — the cell
/// coordinates pardes_mouse takes. The tty suite's SGR commands are 1-based and
/// so read one higher for the same cell.
private func gridPoint(_ args: [String], _ index: Int, _ what: String) throws -> GridPoint {
    let col = try uint16(args, index, "\(what) col")
    let row = try uint16(args, index + 1, "\(what) row")
    return GridPoint(col: col, row: row)
}

private func double(_ args: [String], _ index: Int, _ what: String) throws -> Double {
    let raw = try token(args, index, what)
    guard let value = Double(raw) else {
        throw ScriptError(message: "\(what) is not a number: \(raw)")
    }
    return value
}

// ----------------------------------------------------------- hermetic world

/// Rebuild the world one script sees, before pardes_init reads any of it. This
/// is test/snapshot.zig's per-script setup spelled in Swift: same fake HOME,
/// same pinned bash prompt, same config, same frozen clock.
private func buildWorld(stem: String) throws -> String {
    let fm = FileManager.default
    let base = "\(workBase)/\(stem)"
    // Recreated, not reused: a file left by a previous run is a file the pane
    // tag or an `ls` would show.
    try? fm.removeItem(atPath: base)
    let home = "\(base)/home"
    let work = "\(base)/cwd"
    let configHome = "\(home)/.config"
    let pardesConfig = "\(configHome)/pardes"
    let tmp = "\(base)/tmp"
    for dir in [base, home, work, configHome, pardesConfig, tmp] {
        try fm.createDirectory(atPath: dir, withIntermediateDirectories: true)
    }

    // The shells are started with `--rcfile /tmp/pardes-osc133.bash`, which
    // sources $HOME/.bashrc (host_io.Shell) — so this is what pins the
    // prompt to `$ ` and keeps the developer's history out of the capture.
    try "PS1='$ '\nHISTFILE=\n".write(toFile: "\(home)/.bashrc", atomically: true, encoding: .utf8)
    // ...and the config is not empty, because the DEFAULT shell is fish, whose
    // prompt carries a hostname and whose greeting carries a version. A golden
    // taken against that is a golden for one machine.
    try "Shell bash\n".write(toFile: "\(pardesConfig)/init", atomically: true, encoding: .utf8)

    // The return value is the failure of a memory allocation and nothing else;
    // there is no recovery worth writing, and a golden taken in a world that
    // half-built would be nonsense anyway.
    _ = setenv("HOME", home, 1)
    // Set even though it now points inside the fake HOME: a developer who
    // exports XDG_CONFIG_HOME somewhere else would otherwise boot the core with
    // their own startup builtins.
    _ = setenv("XDG_CONFIG_HOME", configHome, 1)
    _ = setenv("TERM", "xterm-256color", 1)
    _ = setenv("LC_ALL", "C", 1)
    _ = setenv("TMPDIR", tmp, 1)
    // A wall clock cannot live in a golden. Everything that would print one
    // prints fixed characters instead when this is set.
    _ = setenv("PARDES_NOTIME", "1", 1)
    // The scripts speak to a grid that HAS the workspace tag row: the app
    // hands that row to its native menu bar, but this harness is the
    // topbar's test bench, so opt back in before pardes_init reads it.
    _ = setenv("PARDES_WORKSPACE_TAG", "1", 1)
    guard fm.changeCurrentDirectoryPath(work) else {
        throw ScriptError(message: "could not chdir into \(work)")
    }
    return work
}

// ---------------------------------------------------------------- the runner

private func firstDiff(_ golden: String, _ actual: String) -> String {
    let g = golden.split(separator: "\n", omittingEmptySubsequences: false)
    let a = actual.split(separator: "\n", omittingEmptySubsequences: false)
    for n in 0..<max(g.count, a.count) {
        let left = n < g.count ? String(g[n]) : "<eof>"
        let right = n < a.count ? String(a[n]) : "<eof>"
        if left == right { continue }
        return "  first diff at golden line \(n + 1):\n  -\(left)\n  +\(right)\n"
    }
    return ""
}

private func absolute(_ path: String) -> String {
    if path.hasPrefix("/") { return path }
    return FileManager.default.currentDirectoryPath + "/" + path
}

private func snapScripts(in dir: String) -> [String] {
    let entries = (try? FileManager.default.contentsOfDirectory(atPath: dir)) ?? []
    return entries.filter { $0.hasSuffix(".snap") }.sorted().map { "\(dir)/\($0)" }
}

/// One script end to end. Returns true if it passed.
private func runOne(scriptPath: String, update: Bool) -> Bool {
    let name = (scriptPath as NSString).lastPathComponent
    let stem = (name as NSString).deletingPathExtension
    let goldenPath = String(scriptPath.dropLast(".snap".count)) + ".golden"
    let actualPath = String(scriptPath.dropLast(".snap".count)) + ".actual"

    let driver = Driver(scriptName: name, scriptDirectory: (scriptPath as NSString).deletingLastPathComponent)
    // pardes_deinit is mandatory, not tidiness: the ABI is a singleton, so a
    // core left standing makes the NEXT script's pardes_init return 1.
    defer { driver.shutdown() }

    let started = Date()
    let out: String
    do {
        let source = try String(contentsOfFile: scriptPath, encoding: .utf8)
        _ = try buildWorld(stem: stem)
        out = try driver.run(source: source)
    } catch let error as ScriptError {
        print("FAIL \(stem): \(error.message)")
        return false
    } catch {
        print("FAIL \(stem): \(error)")
        return false
    }
    let took = Int(Date().timeIntervalSince(started) * 1000)

    if update {
        do {
            try out.write(toFile: goldenPath, atomically: true, encoding: .utf8)
            print("UPDATED \(goldenPath) (\(out.utf8.count) bytes)")
            return true
        } catch {
            print("FAIL \(stem): could not write \(goldenPath): \(error)")
            return false
        }
    }

    guard let golden = try? String(contentsOfFile: goldenPath, encoding: .utf8) else {
        print("FAIL \(stem): no golden (run with -- --update)")
        return false
    }
    if golden == out {
        print("PASS \(stem) (\(took)ms)")
        return true
    }
    try? out.write(toFile: actualPath, atomically: true, encoding: .utf8)
    print("FAIL \(stem): differs from golden (actual written to \(actualPath))")
    print(firstDiff(golden, out), terminator: "")
    return false
}

@main
struct MacosE2E {
    static func main() {
        // Before any NSWindow exists: AppKit will not make one without an
        // application object, and the policy has to be in place before the first
        // window so that nothing ever asks the window server for focus. This has
        // to be able to run inside a build, over ssh, beside a developer who is
        // typing in another app.
        //
        // UNVERIFIED: .prohibited is documented as "may not create windows", and
        // an offscreen window is nevertheless the standard way to run AppKit
        // headless. If `draw` ever reports a blank view on a machine where the
        // app itself renders, .accessory is the one-word fallback — it also
        // keeps the process out of the Dock, it merely permits activation.
        NSApplication.shared.setActivationPolicy(.prohibited)

        // A run loop with no sources attached returns from run(until:)
        // immediately, which would turn every poll into a busy spin. This timer
        // never does anything; it exists so the deadline is honoured as a sleep.
        let keepAlive = Timer(timeInterval: 3600, repeats: true) { _ in }
        RunLoop.current.add(keepAlive, forMode: .default)

        var update = false
        var positional: [String] = []
        for arg in CommandLine.arguments.dropFirst() {
            if arg == "--update" { update = true } else { positional.append(arg) }
        }

        // Every path is made absolute up front, because each script chdirs into
        // its own hermetic cwd before it runs and the goldens live back here.
        var scripts: [String] = []
        for arg in positional.isEmpty ? [defaultScriptDir] : positional {
            let path = absolute(arg)
            var isDir: ObjCBool = false
            if FileManager.default.fileExists(atPath: path, isDirectory: &isDir), isDir.boolValue {
                scripts.append(contentsOf: snapScripts(in: path))
            } else {
                scripts.append(path)
            }
        }
        if scripts.isEmpty {
            print("no .snap scripts found")
            exit(1)
        }

        var failed = 0
        // Serial, unlike the tty suite's fork-per-script fan-out: the ABI is a
        // singleton and the hermetic world is process-global environment plus a
        // chdir, so two scripts at once in one process would be two scripts in
        // each other's world.
        for script in scripts {
            if !runOne(scriptPath: script, update: update) { failed += 1 }
        }
        keepAlive.invalidate()
        if failed > 0 {
            print("\(failed)/\(scripts.count) macos e2e scripts FAILED")
            exit(1)
        }
        print("all \(scripts.count) macos e2e scripts ok")
        exit(0)
    }
}