File size: 56,012 Bytes
fde6d9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28dcfe5
9add092
 
28dcfe5
 
 
 
fde6d9a
28dcfe5
fde6d9a
 
 
bc7aec1
f8dbc23
437dfe5
bc7aec1
 
9add092
 
 
 
bc7aec1
 
9add092
 
 
 
 
 
 
 
28dcfe5
 
437dfe5
9add092
28dcfe5
 
9add092
 
 
28dcfe5
 
 
9add092
a1a9eef
f8dbc23
9add092
 
 
 
a1a9eef
9add092
bc7aec1
9add092
 
fde6d9a
 
28dcfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
455dd9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc7aec1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f8dbc23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
437dfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fde6d9a
 
 
0918516
fde6d9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3f41c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fde6d9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c34f317
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0918516
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
906d8c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9add092
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34052ec
 
 
 
9add092
34052ec
 
9add092
 
 
 
 
34052ec
9add092
 
 
 
 
 
 
 
 
 
 
 
 
34052ec
 
 
 
 
 
9add092
 
 
 
34052ec
9add092
34052ec
 
 
 
 
9add092
34052ec
9add092
34052ec
9add092
34052ec
9add092
 
 
 
 
 
34052ec
 
 
 
 
 
9add092
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79f9849
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fde6d9a
 
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
import marimo

__generated_with = "0.25.2"
app = marimo.App(width="medium", auto_download=["html"])


@app.cell
def _():
    import marimo as mo

    return (mo,)


@app.cell
def winclaw_setup():
    # Single import surface. Everything below reads from here; nothing below re-imports.
    # /marimo/winclaw is sandbox-local and dies with the session; Continuum restores it from
    # the Hub before this cell runs. The HF token is never referenced in source.
    import json
    import os
    import pathlib
    import subprocess
    import sys
    import time

    sys.path.insert(0, "/marimo")

    from winclaw import (actlang, apps, appsuite, audit, boundary, capabilities, continuum,
                        perf, train_gpu,
                        corpus, design, glyphforge, harness, jobs, kb, knowledge, modelspec, policy, rasteron,
                        roadmap, supervisor, tokenizer, toyenv, training, transfer, uialite,
                        verdict, verify, vertical, vfs, winsim)


    return (
        actlang,
        apps,
        appsuite,
        audit,
        boundary,
        capabilities,
        continuum,
        corpus,
        design,
        glyphforge,
        harness,
        jobs,
        json,
        knowledge,
        modelspec,
        os,
        pathlib,
        policy,
        rasteron,
        roadmap,
        subprocess,
        sys,
        time,
        tokenizer,
        toyenv,
        train_gpu,
        training,
        transfer,
        uialite,
        verdict,
        verify,
        vertical,
        vfs,
        winsim,
    )


@app.cell
def bootstrap(continuum, mo, pathlib):

    # Bootstrap: what this notebook cannot continue without. Runs first, always.
    import shutil
    import torch

    _root = pathlib.Path("/marimo")
    try:
        _ctx = continuum.Continuum("hkblockchaintechnology", stage="pretrain")
        _token, _who = "present", _ctx.api.whoami().get("name")
    except Exception as _e:
        _token, _who = f"MISSING ({type(_e).__name__})", "-"
    _dl = continuum.Deadline()
    _gpu = torch.cuda.get_device_name(0) if torch.cuda.is_available() else "none"
    _free_gb = shutil.disk_usage("/marimo").free / 1e9
    _units = sorted(p.stem for p in (_root / "winclaw").glob("*.py"))

    mo.md(f"""
    # Session bootstrap

    | check | state |
    |---|---|
    | HF token | **{_token}** |
    | HF account | `{_who}` |
    | GPU | {_gpu} |
    | sandbox free disk | {_free_gb:,.1f} GB - ephemeral, dies with the session |
    | package modules | {len(_units)} |
    | session budget | 12 h wall clock, soft stop 30 min before the end |
    | deadline now | {_dl.report()} |

    **The token is re-supplied every session** via `HF_TOKEN` or `~/.config/winclaw/token`
    (0600). It is deliberately absent from all notebook source.

    Units loaded: {", ".join(f"`{u}`" for u in _units)}
    """)

    return


@app.cell
def job_board(jobs, mo):

    # The job board, read live from the Hub so progress survives the sandbox.
    _j_state = jobs.load()
    _j_next = jobs.ready(_j_state)
    mo.md(f"""
    # Job board

    {jobs.markdown(_j_state)}

    ## Ready to start

    {chr(10).join(f"- `{j['id']}` {j['hours']:g}h - {j['title']}" for j in _j_next[:8]) or "- nothing ready"}

    *Human-owned jobs are listed and never started by the agent.*
    """)

    return


@app.cell
def supervisor_launch(mo, pathlib):

    # Launch controls. Two marimo rules shape this cell:
    #   * a cell may not read a widget value in the cell that creates it
    #   * underscore-prefixed names are cell-local, so anything shared crosses without one
    run_dir = pathlib.Path("/marimo/run")
    run_dir.mkdir(exist_ok=True)
    launch_armed = mo.ui.checkbox(label="armed - tick this, then re-run the launcher cell below")
    launch_cfg = mo.ui.dictionary({
        "objective": mo.ui.text(value="J07 checkpoint, kill, resume", label="objective", full_width=True),
        "stage": mo.ui.text(value="stub", label="stage (real stage names are guarded)"),
        "steps": mo.ui.number(value=200000, start=1, stop=10**9, label="step cap"),
        "minutes": mo.ui.number(value=11.5, start=0.1, stop=12, label="budget (minutes)"),
        "tier_a_s": mo.ui.number(value=900, start=5, stop=7200, label="tier A every (s)"),
        "tier_b_s": mo.ui.number(value=3600, start=5, stop=7200, label="tier B every (s)"),
    })
    mo.hstack([launch_armed, launch_cfg], justify="start")

    return launch_armed, launch_cfg, run_dir


@app.cell
def supervisor_launch_run(
    launch_armed,
    launch_cfg,
    mo,
    os,
    run_dir,
    subprocess,
    sys,
    time,
):

    # The launcher. Detached via start_new_session, which is why a kernel restart cannot stop it.
    _log = run_dir / "supervisor.log"
    if not launch_armed.value:
        _verdict = ("**Not armed** - nothing is running. When armed, this cell launches "
                    "`python -m winclaw.supervisor` detached, so it survives this cell, this "
                    "kernel, and me.")
    else:
        _c = launch_cfg.value
        _cmd = [sys.executable, "-m", "winclaw.supervisor",
                "--objective", str(_c["objective"]), "--stage", str(_c["stage"]),
                "--steps", str(int(_c["steps"])), "--minutes", str(_c["minutes"]),
                "--tier-a", str(int(_c["tier_a_s"])), "--tier-b", str(int(_c["tier_b_s"])),
                "--heartbeat", "300"]
        with open(_log, "w") as _fh:
            _proc = subprocess.Popen(_cmd, cwd="/marimo",
                                     env=dict(os.environ, PYTHONPATH="/marimo",
                                              WINCLAW_SESSION_START=str(time.time())),
                                     stdout=_fh, stderr=subprocess.STDOUT, start_new_session=True)
        _verdict = (f"**Launched detached.** pid `{_proc.pid}`, stage `{_c['stage']}`, budget "
                    f"{_c['minutes']} min, log `{_log}`.")
    mo.md(f"# Supervisor launch\n\n{_verdict}")

    return


@app.cell
def supervisor_monitor(continuum, json, mo, pathlib):

    # Monitor: tail the newest session log and the Hub pointer. Read-only, never mutates.
    _run_files = sorted(pathlib.Path("/marimo/run").glob("*.jsonl"), key=lambda p: p.stat().st_mtime)
    _events = ([json.loads(l) for l in _run_files[-1].read_text().splitlines()
                if l.startswith("{") and '"event"' in l] if _run_files else [])
    _losses = [e["loss"] for e in _events if e["event"] == "step"]
    _blocks = "▁▂▃▄▅▆▇█"
    if _losses:
        _lo, _hi = min(_losses), max(_losses)
        _span = max(_hi - _lo, 1e-9)
        _spark = "".join(_blocks[min(int((v - _lo) / _span * 7), 7)] for v in _losses[-60:])
    else:
        _spark = "(no steps logged yet)"
    _gates = [e for e in _events if e["event"] == "smoke_gate"]
    _cks = [e for e in _events if e["event"] == "checkpoint"]
    _res = [e for e in _events if e["event"] in ("resumed", "cold_start", "resume_gave_up")]
    _ptr = continuum.Continuum("hkblockchaintechnology").latest("pretrain") or {}

    mo.md(f"""
    # Supervisor monitor

    **Newest log:** `{_run_files[-1].name if _run_files else "none"}` - {len(_events)} events

    | signal | value |
    |---|---|
    | steps logged | {len(_losses)} |
    | first / latest loss | {_losses[0] if _losses else "-"} / {_losses[-1] if _losses else "-"} |
    | resume decisions | {", ".join(e["event"] for e in _res) or "-"} |
    | smoke gates | {", ".join(f"{e['tier']}@{e['tried_step']} drift {e['drift_pct']}% " + ("PASS" if e["passed"] else "FAIL") for e in _gates) or "-"} |
    | checkpoints taken | {", ".join(f"{e['tier']}@{e['step']}" for e in _cks) or "-"} |
    | model-repo pointer | {_ptr.get("stage", "-")} / {_ptr.get("tier", "-")} @ step {_ptr.get("step", "-")} |

    **Loss trend** (last {min(len(_losses), 60)} logged points)

    ```
    {_spark}
    ```

    *Mechanism runs use a stage outside the real ones, so a toy checkpoint can never be
    mistaken for a trained model.*
    """)

    return


@app.cell
def checkpoint_integrity(mo):

    # Which stage to audit. Separate cell from its consumer, and public so it can cross.
    inspect_stage = mo.ui.dropdown(options=["pretrain", "sft", "dpo", "grpo", "gateproof", "stub"],
                                   value="pretrain", label="stage to inspect")
    inspect_stage

    return (inspect_stage,)


@app.cell
def checkpoint_integrity_check(continuum, inspect_stage, json, mo, pathlib):

    # Checkpoint integrity: pull whatever the Hub claims and verify every byte. Trust nothing.
    from huggingface_hub import hf_hub_download

    _c = continuum.Continuum("hkblockchaintechnology")
    _ptr = _c.latest(inspect_stage.value) or {}
    if not _ptr.get("manifest"):
        _out = f"Stage **{inspect_stage.value}** has no checkpoint - {_ptr.get('status', 'no pointer')}"
    else:
        _man = json.loads(pathlib.Path(hf_hub_download(
            _c.rid(continuum.MODEL_REPO), _ptr["manifest"], repo_type="model",
            token=_c.token)).read_text())
        _rows, _ok = [], True
        for _rel, _rec in _man["files"].items():
            _lp = hf_hub_download(_c.rid(continuum.MODEL_REPO), _rel, repo_type="model",
                                  token=_c.token, force_download=True)
            _same = continuum.sha256_file(_lp) == _rec["sha256"]
            _ok &= _same
            _rows.append(f"| `{_rel.split('/')[-1]}` | {_rec['size']:,} | {_rec['sha256'][:12]} "
                         f"| {'OK' if _same else '**MISMATCH**'} |")
        _out = (f"**Tier {_ptr.get('tier')} at step {_ptr.get('step')}** "
                f"(exact resume: {_ptr.get('exact')}), {len(_man['files'])} files, "
                f"**all sha256 verified: {_ok}**\n\n"
                f"| file | bytes | sha256 | check |\n|---|---|---|---|\n" + "\n".join(_rows))
    mo.md(f"# Checkpoint integrity\n\n{_out}")

    return


@app.cell
def periodic_verification(continuum, mo, toyenv, verify):

    # Periodic verification: does it actually work? The loss does not answer that question.
    # This cell runs the same battery the supervisor runs mid-training, including the negative
    # controls, so the battery is exercised on the notebook's side too.
    _rec = verify.run(policy=toyenv.expert_policy, name="expert reference (notebook side)")
    _c = continuum.Continuum("hkblockchaintechnology")
    _ptrs = {_s: (_c.latest(_s) or {}) for _s in
             ("pretrain", "finaldemo", "gateproof", "rollback3")}
    _ptr_rows = "\n".join(
        f"| `{_s}` | {v.get('tier', '-')} | {v.get('step', '-')} | "
        f"{v.get('rolled_back_from', '') or ''} -> {v.get('rolled_back_to', '') or ''} | "
        f"{v.get('reason', v.get('status', '')) or ''} |"
        for _s, v in _ptrs.items())
    _lease = _c._read_json("locks/finaldemo.json", continuum.MODEL_REPO, "model") or {}

    mo.md(f"""
    # Periodic verification

    Three questions, asked on a cadence, and the battery must be able to answer *no* to each:

    1. **Is it alive?** liveness, heartbeat freshness
    2. **Is it learning?** loss falling, gradients finite
    3. **Does it work?** the policy solves canary tasks whose checker reads real state

    The loss answers only the second. A run can lose gracefully while the agent does nothing
    useful, which is why the third question is asked separately and on a timer.

    {verify.markdown([_rec])}

    ## Rollback state across the stages we ran

    | stage | tier | step | rolled back | reason |
    |---|---|---|---|---|
    {_ptr_rows}

    Lease on `finaldemo`: `{_lease.get('owner', 'none')}` - a single-writer lease exists
    because **two supervisors on one stage do not race, they hang**: both block on the
    repository's commit lock, and the run silently stops making progress.

    ## What the negative controls cost us

    Every control is a deliberate breakage that the battery must notice. Two of them found
    real defects in this very mechanism:

    | defect | how it was found |
    |---|---|
    | integrity gate blind at the loss floor | a 15% weight perturbation moved the loss 0.7%, inside a 3% tolerance: loss continuity is a *semantic* check, not an integrity one. Fixed with a parameter fingerprint. |
    | detection that changed nothing | the first regression run only logged `rollback_skipped`; with no earlier checkpoint the system still has to act, so it now marks the checkpoint untrusted. |
    | checkpointing starved training | a 1-second tier cadence dropped throughput from 200 to 20 steps/s; uploads are now budgeted to 10% of wall time. |
    | two writers hung the repo | found by `ps`: two supervisors alive, one stuck 30s in a tier C upload. Fixed with a lease. |
    """)

    return


@app.cell
def app_suite(appsuite, mo):

    # The application suite and the operations matrix, measured rather than asserted.
    _a = appsuite.audit()
    _cov = appsuite.coverage()
    _rows = "\n".join(
        f"| {_d} | {_r['total']} | {_r['expressible']} | {_r['verifiable']} | **{_r['covered']}** |"
        for _d, _r in _cov["per_domain"].items())
    _apps = "\n".join(f"| **{_x.name}** | {_x.kind} | {_x.owns} | {_x.effort_hours:g} | "
                       f"{_x.status} |" for _x in appsuite.APPS)
    _hard = ", ".join(f"`{_o.id}`" for _o in appsuite.OPERATIONS if _o.difficulty >= 4)
    _daily = [f"`{_o.id}` {_o.title}" for _o in appsuite.OPERATIONS if _o.frequency == "daily"]

    mo.md(f"""
    # Application suite and operations matrix

    "Serious enough for daily operations" is only meaningful when it is enumerable. So it is:

    **{_a['operations']} operations** across **{_a['domains']} domains** -
    {_a['daily_operations']} of them daily work - served by **{_a['apps']} applications**.
    Every operation declares which apps it uses, which capability verbs it needs, which
    checker verifies the outcome, its difficulty and its frequency.

    **Expressible and verifiable: {_a['coverage_pct']}%.** An operation counts as covered only
    if every verb it needs exists in the capability matrix and its checker predicate exists in
    Verdict. Otherwise it is listed as a gap, not averaged away. Gaps right now:
    **{len(_cov['gaps'])}**.

    ## Depth by domain

    | domain | operations | expressible | verifiable | covered |
    |---|---|---|---|---|
    {_rows}

    ## Applications

    | application | kind | owns | hours | status |
    |---|---|---|---|---|
    {_apps}

    Total application effort: **{sum(_x.effort_hours for _x in appsuite.APPS):g} hours**.

    ## What "daily" means here

    {", ".join(_daily[:14])} - and {len(_daily) - 14} more.

    ## The long-horizon ones

    {_hard}

    *Files is built. The other fifteen are specified, budgeted and unaudited by the battery
    until they exist - which is the same standard the rest of this project is held to.*
    """)

    return


@app.cell
def files_app(apps, mo, uialite, vfs):

    # The first real application: Files. Real VFS, real render, real UiaLite tree, and daily
    # operations completed end to end with the outcome checked.
    from PIL import Image as _Image

    _fs = vfs.VFS()
    _fs.mkdir(f"{vfs.SPECIAL['documents']}/Invoices")
    _fs.write(f"{vfs.SPECIAL['documents']}/memo.txt", "shopping list")
    _fs.write(f"{vfs.SPECIAL['documents']}/report.csv", "id,val")
    _fs.write(f"{vfs.SPECIAL['documents']}/budget.xlsx", "PK")
    _create = apps.FilesApp(_fs)

    # operation f01: create a folder and name it
    _f01 = [{"verb": "ui.invoke", "label": "New folder"},
            {"verb": "keyboard.type", "text": "Archive 2026"},
            {"verb": "keyboard.key", "name": "Enter"}]
    for _a in _f01:
        _r = apps.dispatch(_create, _a)
    _f01_ok = _fs.exists(f"{vfs.SPECIAL['documents']}/Archive 2026")

    # operation f05: delete to the Recycle Bin, and confirm that the dialog GATES it
    _create.selection = [r["name"] for r in _create.items()].index("memo.txt")
    apps.dispatch(_create, {"verb": "keyboard.key", "name": "Delete"})
    _gated = _fs.exists(f"{vfs.SPECIAL['documents']}/memo.txt")
    _refuse = apps.dispatch(_create, {"verb": "ui.dialog_respond", "accept": False})
    _kept = _fs.exists(f"{vfs.SPECIAL['documents']}/memo.txt")
    apps.dispatch(_create, {"verb": "keyboard.key", "name": "Delete"})
    _accept = apps.dispatch(_create, {"verb": "ui.dialog_respond", "accept": True})
    _intact = all(_fs.exists(f"{vfs.SPECIAL['documents']}/{n}")
                  for n in ("report.csv", "budget.xlsx"))
    _recycled = len(_fs.recycle) == 1

    # index -> element -> action, which is how ActLang refers to things
    _k = _create.element_index("View")
    apps.dispatch(_create, {"verb": "ui.invoke", "elem": _k})

    _est = uialite.estimate_tokens(_create.frame(), history_diffs=0)
    _dg = uialite.render(uialite.digest(_create.frame(), max_nodes=12))
    _img = _Image.fromarray(_create.render().to_uint8())

    mo.md(f"""
    # Files, working

    | operation | action sequence | outcome | checker |
    |---|---|---|---|
    | `f01` create a folder and name it | New folder, type, Enter | created | `dir_exists` = **{_f01_ok}** |
    | `f05` delete to the Recycle Bin | select, Delete, respond to the dialog | recycled | `no_side_effects` = **{_intact}** |

    The confirmation **gates** the destructive action, which is the property that matters:
    after Delete and before answering, `memo.txt` is **{_gated}** still present; refusing
    keeps it (**{_kept}**); accepting moves it to the Recycle Bin
    (**{_recycled}**), and the other files are untouched (**{_intact}**).

    Element references resolve the way ActLang says they do: `"View"` is digest index
    **{_k}**, and invoking by index only sets the view mode.

    **Digest cost for the real app: {_est['nodes']} nodes, {_est['total']} tokens.**

    ```
    {_dg}
    ```

    The rendered window follows - drawn by GlyphForge into its own canvas, since Rasteron is
    still a specification and calling it built would be a lie this project does not tell.
    """)
    _img

    return


@app.cell
def hardware_utilisation(json, mo, pathlib, train_gpu):

    # Hardware utilisation: measured, and the design rules that fall out of it.
    _perf = json.loads(pathlib.Path("/marimo/run/perf.json").read_text())
    _perf2 = json.loads(pathlib.Path("/marimo/run/perf2.json").read_text())
    _gpu = json.loads(pathlib.Path("/marimo/run/gpu_train.json").read_text())
    _cfg = train_gpu.RECOMMENDED
    _req = train_gpu.data_rate_requirement(189_087)

    def _row(r, label=None):
        if r.get("error"):
            return (f"| {label or r['cfg']['name']} | | {r['cfg']['batch']}x{r['cfg']['seq']} | "
                    f"| | | | | | {r['error']} |")
        return (f"| {label or r['cfg']['name']} | {r['params_m']}M | {r['cfg']['batch']}x"
                f"{r['cfg']['seq']} | {r['step_s']}s | {r['tokens_s']:,} | {r['tflops']} | "
                f"**{r['mfu_pct']}%** | {r['util_pct']}% | {r['peak_gb']}GB |")

    _rows = "\n".join(_row(r) for r in _perf["results"])
    _rows2 = "\n".join(_row(r, k) for k, r in _perf2.items())

    mo.md(f"""
    # Hardware utilisation

    **{_perf['device']}**, {_perf['vram_gb']} GB. Reference peak is **measured**, not from a
    datasheet: a large bf16 matmul gives **{_perf['peak_tflops']} TFLOP/s** on this device, and
    every percentage below is a fraction of that.

    ## The sweep

    | config | params | batch x seq | step | tokens/s | TFLOP/s | MFU | util | VRAM |
    |---|---|---|---|---|---|---|---|---|
    {_rows}

    ## What each knob is worth

    | case | result |
    |---|---|
    {_rows2}

    ## Design rules that came out of the measurements

    1. **Sequence length beats batch count.** 16x8192 reached **91.3% MFU**; 32x2048 reached
       64.5% with half the tokens per step. Long context is not a cost here, it is the win.
    2. **Never micro-batch.** batch 1 x 2048 with 16 accumulation steps measured **2.7% MFU**
       while the device reported **99.8% utilisation**. Utilisation is not efficiency, and
       quoting it as though it were is a way of lying with a real number.
    3. **Activation checkpointing is a trade, not a free win**: ~9 MFU points for half the
       activation memory, which is what makes the larger batches fit at all.
    4. **A per-step device sync costs nothing** at 0.7 s/step (0.2020 s vs 0.2018 s). The worry
       was unfounded and is recorded as such.
    5. **A CPU producer under the step time is free** - 30 ms per batch changed MFU by 0.2
       points, because CUDA is asynchronous and the CPU side of step N overlaps the device side
       of step N-1. This is why a CPU-side renderer is viable at all.

    ## The number that decides the architecture

    At the measured 189k tokens/s the device can consume, the data pipeline must supply:

    | requirement | value |
    |---|---|
    | tokens/s | {_req['tokens_per_s']:,} |
    | screens/s at ~550 tokens each | **{_req['screens_per_s']}** |
    | screens/hour | {_req['screens_per_hour']:,} |
    | tokens per 12 h session at 80% duty | **{_req['tokens_per_12h_session']:,}** |

    So **the GPU is not the bottleneck - the simulator is.** The rasteriser measured 490
    screens/s naive and memory-bandwidth-bound; the requirement is ~344/s. The margin exists,
    but it is not large, and it is the thing to protect.

    ## The GPU trainer, actually running

    | metric | value |
    |---|---|
    | config | {_gpu['steps']} steps at {_cfg['batch']}x{_cfg['seq']}, d{_cfg['d']}, {_cfg['layers']} layers |
    | tokens | {_gpu['tokens']:,} |
    | tokens/s | {_gpu['tokens_per_s']:,} |
    | TFLOP/s | {_gpu['tflops']} |
    | MFU over the whole run | {_gpu['mfu_pct']}% |
    | peak VRAM | {_gpu['peak_gb']} GB (identical to the standalone bench) |

    The gap between 52.7% here and 91.3% in the sweep is not the model: this run's clock
    includes warmup and two **275 MB checkpoint uploads**. Steady state is 0.693 s/step.
    **Uploads should be asynchronous**, which is named here as the next optimisation and is not
    yet measured.

    ## Three wrong diagnoses, recorded rather than deleted

    The trainer OOMed three times and I blamed, in order: the loss implementation, then a
    "head-memory wall", then chunking. All three were wrong. The cause was a missing
    `.to(torch.bfloat16)` in the trainer's constructor, so the model trained in **fp32** and the
    head's logits cost 17 GB instead of 8.6. The arithmetic in `train_gpu.head_memory_gb()` is
    still worth knowing, at bf16 it is half of what it claimed, and the lesson is about
    ordering: **check the dtype first**, before theorising about memory.

    That sequence is in the file, not just in this cell, because a project that only records
    its correct conclusions is a project that cannot be trusted about them.
    """)

    return


@app.cell
def windows_knowledge(knowledge, mo, vfs):

    # Windows domain knowledge: what is available, what it feeds, and what it just bought us.
    _ka = knowledge.audit()
    _src = "\n".join(
        f"| `{s.repo}` | {s.license} | {s.size_mb:,.1f} | "
        f"{', '.join(s.feeds) if s.feeds else '*skipped*'} | {s.verified} |" for s in knowledge.SOURCES)
    _meas = "\n".join(f"| {k.replace('_', ' ')} | {v:,} |" if isinstance(v, int)
                       else f"| {k.replace('_', ' ')} | {v} |"
                       for k, v in knowledge.MEASURED_FIRST_INGEST.items())
    _fs = vfs.VFS(); _fs.write("C:/a.txt", "1")
    _demos = []
    for _d, _fn in (("a missing file", lambda: _fs.read("C:/a.txt.bak")),
                    ("a missing intermediate folder", lambda: _fs.read("C:/Nowhere/x.txt")),
                    ("copying onto itself", lambda: _fs.copy("C:/a.txt", "C:/a.txt"))):
        try:
            _fn(); _demos.append(f"| {_d} | *no error* |")
        except Exception as _e:
            _demos.append(f"| {_d} | `{getattr(_e, 'symbol', type(_e).__name__)}` "
                          f"({getattr(_e, 'code', '?')}) - {getattr(_e, 'published', '')} |")

    mo.md(f"""
    # Windows domain knowledge

    There is an asymmetry that decides whether this platform is learnable at all:

    > **Nobody has Windows pixels or action labels. Everybody has Windows documentation.**

    My original corpus plan specified language, pixels and task semantics, and **never specified
    domain knowledge** - which is the abundant part. That gap is now closed, with licences
    verified by reading the files rather than trusting an SPDX label.

    **{_ka['ingested_mb']:,} MB** of licence-clean material across {_ka['sources']} sources.

    | source | licence | MB | feeds | verified by |
    |---|---|---|---|---|
    {_src}

    ## Three consumers, and the distinction matters

    - **simulator fidelity** - WinSim stops inventing error codes, dialog text and settings paths.
    - **harness knowledge base** - a *deterministic* lookup: intent to mechanism, error to cause.
      Knowledge that is a table belongs in code, not in weights. This is the boundary doctrine
      applied to documentation.
    - **model corpus** - domain vocabulary for the tokenizer, and grounded instruction text.

    ## What the first ingest bought, measured

    | metric | value |
    |---|---|
    {_meas}

    And the fidelity is real rather than decorative - the filesystem now fails the way Windows
    fails, which matters because the harness's repair step looks causes up by code:

    | case | what the simulator now reports |
    |---|---|
    {chr(10).join(_demos)}

    ## The contamination rule

    {chr(10).join("- " + _r for _r in knowledge.CONTAMINATION_RULE)}

    ## One decision for you

    **{", ".join(_ka['share_alike_flagged']) or "nothing"}** is flagged, not ingested. It is the
    highest-quality procedural knowledge available anywhere, and it is **CC-BY-SA**: share-alike
    would put an obligation on a public release of the model. Either we accept that licence, or
    we take the knowledge structurally (mechanism tables, which are facts) without its prose.
    The audit refuses to let a share-alike source into the corpus silently, which is why it
    shows up here rather than in a footnote.
    """)

    return


@app.cell
def design(mo):
    mo.md(r"""
    # WINCLAW — Design v0.2 (invent-from-scratch)

    **Directive.** No pretrained weights. No third-party model. No external dataset. No borrowed
    agent framework. Everything trains **from random init**, here, on data we generate ourselves.
    Only instruments remain: `torch`, `numpy`, `marimo`. Those are our tools, not our ingredients.

    **Why this is not a handicap.** On a real Windows box we would get pixels and **no supervision**.
    Our own substrate emits *perfect* ground truth for every frame: element bounding boxes, z-order,
    focus, control type, live state, the correct action, and the state transition it caused.
    Owning the substrate means every token we train on is labelled. From-scratch is the *only*
    regime where that label density can be exploited.

    ## Measured facts (this sandbox, not assumptions)

    | Fact | Value | Consequence |
    |---|---|---|
    | Kernel | Linux 4.19 **gVisor** — no KVM/qemu/Wine/X | Real Windows cannot run here; the substrate must be ours |
    | GPU | RTX PRO 6000 Blackwell, **97 GB**, sm_120 | **405 TFLOP/s** measured bf16 matmul |
    | Own GPU rasterizer | 490 screens/s naive full-frame; geometry 220k+/s | bbox-local writes -> est. **2-5k screens/s** |
    | Chromium render | **30 screens/s** (33 ms/frame) | 100x slower -> fidelity checks only, never the corpus engine |
    | HF throughput | **112 MB/s** | A 3 GB checkpoint is ~30 s: aggressive checkpointing is free |
    | Scratchpad | **30 s hard timeout** | **Training must be a detached process**, never a cell |
    | Filesystem | ephemeral 7 TB overlay | The sandbox holds nothing durable; HF is the machine's memory |

    ## The invented stack

    | Module | What we build from nothing |
    |---|---|
    | **GlyphForge** | our own 8x16 bitmap font, 96 ASCII glyphs authored programmatically; our own layout, runs, kerning |
    | **Rasteron** | our own GPU UI rasterizer in torch: rects, rounded rects, borders, gradients, 4x-supersampled AA, own alpha compositing and drop shadow. Emits pixels **and** exact label buffers |
    | **WinSim** | our own window manager and app suite (taskbar, Start, Explorer, Notepad, Settings, dialogs, UAC-ish prompts, toasts) as declarative widget trees, with an event loop, focus and z-order |
    | **UiaLite** | our own accessibility/state schema (versioned): role, name, bbox, enabled, focused, value, parent, window |
    | **ActLang** | our own typed action grammar **and** our own tokenizer (BPE trainer written by us, trained on our own corpus) |
    | **Winclaw-0** | our own architecture, random init — see below |
    | **Harness** | our own planner / observer / actor / safety / executor / verifier / critic / memory |
    | **Verdict** | our own eval suite, tasks and metrics |
    | **Continuum** | our own checkpoint and resume protocol (next cell) |

    ## Winclaw-0 architecture (all ours)

    | Part | Design |
    |---|---|
    | Vision | own ViT-style encoder, 16 px patches on a 640x400 downscale -> 1000 patches -> own two-level token merger -> **~250 visual tokens**, random init |
    | UI state | UiaLite tree serialized in **our BPE** -> UI tokens, interleaved with visual tokens |
    | History | k=4 frames as separate token blocks with a learned recency decay |
    | Fusion | own interleaved cross-attention with learned frame-position embeddings |
    | Action | own **spatial pointing head**: a distribution over a learned anchor grid plus sub-cell refinement, instead of emitting coordinate text (much higher click precision per token) |
    | Auxiliary | own world-model head (predict the state delta an action causes) plus own verifier/reward head; jointly trained multi-task loss |
    | Size | **Winclaw-0-150M ~150M** (d 768, 12 layers, ctx 1024) first; scale to 400M-1B later |

    ## Curriculum (our own objectives, each stage gated)

    | | Objective | Supervision |
    |---|---|---|
    | C0 | corpus generation: Rasteron renders screens plus exact labels | free, unlimited |
    | C1 | **masked UI modelling** — predict masked elements/roles/geometry from pixels | self-supervised on C0 |
    | C2 | **grounding**: instruction or query -> anchor distribution | exact bboxes |
    | C3 | **next-action imitation** from our own WinSim rollouts | exact correct actions |
    | C4 | **world model / inverse dynamics**: (obs, action) -> state delta | exact simulator deltas |
    | C5 | **RL from our own verifier reward** (our own PPO-lite plus RFT/DPO) | task checkers |

    Compute reconciliation (measured): ~120 TFLOP/s sustained at ~30% MFU, 150M params, ctx 1024
    -> **~4B tokens per 12 h session**, ~40B tokens by session 8 = 266 tokens/param. That is a
    genuinely pretrained small model, not a fine-tune.
    ## 6b. Capability surface (after the full-control requirement)

    The requirement is: see, click, type, know all input and output, and write and run
    code. The action grammar is therefore not 11 verbs but an enumerable surface, in
    `winclaw/capabilities.py`: **30 perception channels x 95 action verbs**. Every verb
    declares its arguments, its WinSim mechanism, its real-Windows mechanism, a risk
    class with an enforcement rule, and the channels that verify its effect. The audit
    refuses any verb it cannot verify: an unverifiable capability is a wish, not a
    capability.

    Two architectural consequences:

    1. **Observation is partly pull, not only push.** Full OS state is megabytes
       (registry, event log, process table, file trees). A fixed screenshot-plus-tree
       observation cannot carry it, and a model that tried to ingest it would spend its
       entire context on a single step. So a compact digest rides along and 10 channels
       are queryable on demand through `meta.observe`.
    2. **Typed slot decoding, not free text.** Arguments decode into typed slots
       (`elem_id | path | pid | key | script`) so the model emits valid actions by
       construction and spends capacity on intent rather than syntax. The spatial
       pointing head covers the one argument that cannot be discretised cleanly: the
       click target.

    Risk is not decoration. 33 verbs run free, 38 are audited, 18 take a state snapshot
    and are revertible, and 6 are denied unless explicitly confirmed.

    **Transfer note - two real-Windows problems this exposes and does not solve here.**
    (a) *Elevation*: controlling UAC-protected state requires the executor to run as a
    service or scheduled task at highest privilege, or a consent flow. (b) *Real
    observation*: every channel above must be re-implemented against Win32/UIA/WMI when
    `RemoteWinEnv` lands, and that needs a real Windows box reachable over WinRM/RDP.
    """)
    return


@app.cell
def resume(mo):
    mo.md(r"""
    # 12-Hour Session Protocol — Continuum

    Molab gives **12 h per session**, and every session is a fresh, empty sandbox. A session is
    therefore a *resumable job*, not a script. Any session may be killed at any instant and the
    next one must continue as if nothing happened.

    ## Budget (12 h wall clock, enforced by the supervisor, not by a human)

    | Phase | Window | Work |
    |---|---|---|
    | bootstrap | 0:00-0:15 | deps, HF auth, fetch manifest and code, verify sha256 |
    | resume | 0:15-0:25 | pull latest checkpoint (~3 GB, ~30 s) plus corpus cursor |
    | smoke gate | 0:25-0:35 | 100 steps; loss must match recorded loss within 3%, else fall back one checkpoint |
    | **train** | 0:35-10:30 | gradient steps; hourly micro-eval |
    | eval | 10:30-11:15 | held-out suite, per-skill breakdown, samples |
    | export | 11:15-11:40 | bf16 and fp16, model card, dataset shards, manifest |
    | buffer | 11:40-12:00 | final push and integrity verify |

    `deadline = t0 + 11.5h`. Soft-stop 30 min before it. SIGTERM -> immediate checkpoint, then upload.

    ## Resume reads three files

    1. `latest.json` — the pointer (tiny, written **last**)
    2. `manifest.json` — authoritative state: step, tokens, corpus cursor, lr, seed, sha256 per file
    3. `trainer_state.json` — loss history, eval, RNG states, sampler position

    ## Checkpoint tiers (sized by the measured 112 MB/s)

    | Tier | Cadence | Payload | Cost |
    |---|---|---|---|
    | **A** | 15 min | bf16 weights plus trainer_state | ~10 s |
    | **B** | 60 min | plus optimizer moments (fp32) -> exact resume | ~30-40 s |
    | **C** | session end | plus eval, card, samples, RNG, corpus cursor | minutes |
    | **heartbeat** | 5 min | `heartbeat.json` (step, loss, elapsed) | <1 s — for hard-kill forensics |

    Retention: keep last 3 plus best-by-eval. Tier A is cheap enough that worst-case loss is 15 min.

    ## Integrity and atomicity

    Stage into `_tmp/`, sha256 every file, upload **data before manifest, manifest before pointer**.
    A crash mid-upload can never corrupt a good pointer. The next session verifies hashes; a
    mismatch falls back exactly one checkpoint rather than resuming from poison.

    ## Determinism (exact resume, cheaply)

    - seed tree: `seed = f(base_seed, stage, step)`
    - the corpus is **materialized once** as packed token shards in fixed order, so resume is a
      **cursor offset** — no re-rendering, no sampling drift
    - RNG states and sampler position ride in the checkpoint
    - the smoke gate does not demand bitwise reproducibility; it demands *loss continuity*

    ## Process architecture (forced by the measured 30 s scratchpad limit)

    Training runs as a **detached supervisor process**: `setsid nohup python -m wino.train`.
    It owns the deadline, the checkpoint loop and the upload loop. The notebook only launches,
    tails logs, plots loss and can resume — so a kernel restart, a closed tab, or the agent going
    away cannot kill training. The supervisor can push a full checkpoint with no notebook alive.

    ## Cross-session plan

    | Session | Objective | HF deliverable |
    |---|---|---|
    | S1 | GlyphForge, Rasteron, WinSim, ActLang, tokenizer, corpus v1 | code, corpus shards, ckpt |
    | S2 | C1 masked UI modelling | weights, loss curve |
    | S3 | C2 grounding plus harness skeleton and interactive rollouts | weights, grounding eval |
    | S4 | C3 imitation on own rollouts | weights, task suite v1 |
    | S5 | C4 world model plus verifier head | weights, reward-model eval |
    | S6 | C5 RL from verifier reward | weights, per-skill eval |
    | S7 | scale to 400M plus robustness (dialogs, popups, DPI, themes) | scaled ckpts |
    | S8 | real-Windows bridge (if a box exists) plus release | model card, demo |

    ## Failure modes and recovery

    | Failure | Detection | Response |
    |---|---|---|
    | CUDA OOM | exception in step | halve micro-batch, resume last tier-B |
    | NaN or divergence | loss monitor | roll back to last good, lower LR |
    | sandbox killed hard | missing heartbeat | resume from last tier-A (at most 15 min lost) |
    | HF write error | upload retry loop | keep training, flush the local queue when back |
    | corrupted upload | sha256 on next resume | fall back one checkpoint |
    | kernel restart | irrelevant | the training process is unaffected |

    ## Repo layout (pushed to HF, since the sandbox is not storage)

    ```
    winclaw/  glyphforge.py rasteron.py winsim.py uialite.py actlang.py tokenizer.py
           model.py  heads.py  harness/  tasks/  verdict.py  train.py  continuum.py
    ```

    ## Open decisions

    1. HF account plus a **fine-grained write-scoped token** (never pasted into a cell; env/secret only).
    2. Start at **Winclaw-0-150M 150M** (fast iteration, recommended) or jump straight to ~400M?
    3. Checkpoint retention: last-3 plus best, or keep everything (~3 GB per tier-B)?
    4. Session 1 spends its first ~4 h on the substrate with **zero** training — accept that, or
       do you want a crude-model-first path that has something training by hour 3?
    """)
    return


@app.cell
def font_specimen(glyphforge):
    # GlyphForge specimen: every glyph below is drawn by our own rasterizer from
    # GlyphScript outlines - no font file, no atlas, no third-party text engine.
    from PIL import Image

    _fg = glyphforge.GlyphForge(ss=8)
    _cv = glyphforge.Canvas(760, 420, bg=(0.118, 0.122, 0.137))

    # window chrome: a preview of the WinSim widget layer
    _cv.fill_rect(20, 20, 720, 380, (0.961, 0.961, 0.969))
    _cv.stroke_rect(20, 20, 720, 380, (0.02, 0.02, 0.03), 1.0)
    _cv.fill_rect(21, 21, 718, 30, (0.914, 0.914, 0.929))
    _fg.draw_text(_cv, 32, 41, "report.txt - Notepad", 13, (0.10, 0.10, 0.12))
    for _x in (688, 706, 724):
        _cv.fill_rect(_x, 30, 10, 10, (0.80, 0.80, 0.82))
    _cv.fill_rect(21, 51, 718, 24, (0.949, 0.949, 0.957))
    for _i, _item in enumerate(("File", "Edit", "View", "Help")):
        _fg.draw_text(_cv, 36 + _i * 46, 67, _item, 12, (0.18, 0.18, 0.20))
    _cv.fill_rect(33, 83, 694, 264, (1.0, 1.0, 1.0))
    _cv.stroke_rect(33, 83, 694, 264, (0.72, 0.72, 0.75), 1.0)

    for _i, _row in enumerate(["ABCDEFGHIJKLMNOPQRSTUVWXYZ",
                               "abcdefghijklmnopqrstuvwxyz",
                               "0123456789  !?.,:;()[]{}<>",
                               "/+-=_@#$%&*|~^'\"`"]):
        _fg.draw_text(_cv, 48, 112 + _i * 24, _row, 16, (0.10, 0.10, 0.13))

    _cv.fill_rect(48, 216, 663, 1, (0.85, 0.85, 0.88))
    _fg.draw_text(_cv, 48, 240, "UI text renders at 13 px with antialiasing from one", 13, (0.15, 0.15, 0.18))
    _fg.draw_text(_cv, 48, 258, "outline definition - no bitmap atlas, no third-party font.", 13, (0.15, 0.15, 0.18))
    _fg.draw_text(_cv, 48, 280, "GlyphForge: 95 glyphs, GlyphScript outlines, own rasterizer.", 12, (0.45, 0.45, 0.50))
    _cv.fill_rect(620, 300, 76, 28, (0.882, 0.882, 0.898))
    _cv.stroke_rect(620, 300, 76, 28, (0.60, 0.60, 0.63), 1.0)
    _fg.draw_text(_cv, 642, 319, "Save", 13, (0.10, 0.10, 0.12))

    specimen_img = Image.fromarray(_cv.to_uint8())
    specimen_img

    return


@app.cell
def corpus_plan(corpus, mo):

    # The corpus plan is COMPUTED from winclaw/corpus.py, so the documented mixture
    # cannot drift away from the code that defines it.
    _gen = sum(s.tokens_b for s in corpus.REGISTRY if s.doctrine == corpus.GENERATE)
    _imp = sum(s.tokens_b for s in corpus.REGISTRY if s.doctrine == corpus.IMPORT)
    _never = [s.key for s in corpus.REGISTRY if s.doctrine == corpus.NEVER]
    _share = "\n".join(
        f"- `{k}` - {lic}" + (" - **share-alike: decide before a public release**" if sa else "")
        for k, lic, sa in corpus.ledger())
    _notes = "\n".join(
        f"- `{s.key}` ({s.stage}) - {s.note}"
        for s in corpus.REGISTRY if s.note and s.doctrine != corpus.NEVER)

    mo.md(f"""
    # Corpus plan: generate vs import

    **The asymmetry that decides it.** Searching Hugging Face for Windows UI corpora
    returns *nothing*: no `windows screenshot`, no `windows accessibility tree`, no
    Windows trajectory set worth the name. Language, by contrast, is abundant and
    ungated. So: **we cannot borrow Windows, we must build it; we cannot invent
    English, we must import it.** The doctrine splits three ways, not two.

    | category | tokens | share | why |
    |---|---|---|---|
    | **generate** (ours) | {_gen:.1f}B | {_gen / corpus.TOTAL_TARGET_B * 100:.1f}% | we own the environment, so we own exact labels nobody else has |
    | **import** (the world) | {_imp:.1f}B | {_imp / corpus.TOTAL_TARGET_B * 100:.1f}% | language, real pixels and real task semantics are properties of the world, not of a model |
    | **never** | 0 | - | weights, other agents' labels, and anything we evaluate on |

    Planned total: **{corpus.TOTAL_TARGET_B:.1f}B tokens**.

    {corpus.table()}

    ## Consequences that are easy to miss

    - **The tokenizer must see English.** `TOKENIZER_SOURCES` includes the language
      slice; a BPE trained only on our own grammar plus synthetic text
      byte-fragments real English at inference and burns context on it.
    - **The mixture forces the stage order.** Language-only stage A1 comes first to
      build semantics, then multimodal A2. A1 needs no simulator at all, so it can
      run while the substrate is still being built instead of waiting on it.
    - **Contamination is enforced, not promised.** `corpus.guard()` refuses to train
      on anything sharing a repo or org with an eval set. Never-import:
      {", ".join("`" + k + "`" for k in _never)}
    - **Tokenizer trained on:** {", ".join("`" + k + "`" for k in corpus.TOKENIZER_SOURCES)}

    ## Licence exposure for a public release

    {_share}

    ## Source notes

    {_notes}
    """)

    return


@app.cell
def continuum_status(continuum, mo):

    # Continuum status: the notebook reading the machine's own memory on the Hub.
    import json as _json

    _con = continuum.Continuum("hkblockchaintechnology")
    _rows, _err = [], ""
    _tot = 0
    _created = _sess_id = _gpu = "?"
    try:
        _sync = _json.loads(open(_con.api.hf_hub_download(
            _con.rid(continuum.CODE_REPO), "SYNC.json", repo_type="dataset",
            token=_con.token)).read())
        _meta = _sync.get("meta", {})
        _created, _sess_id = _sync.get("created", "?"), _meta.get("session_id", "?")
        _gpu = _meta.get("gpu", "?")
        _tot = sum(v["size"] for v in _sync["files"].values())
        _rows = [f"| `{_k}` | `{_v['sha256'][:12]}` | {_v['size']:,} |"
                 for _k, _v in _sync["files"].items()]
    except Exception as _e:
        _err = f"SYNC read failed: {type(_e).__name__}: {_e}"

    _stage_rows = []
    for _st in ("pretrain", "sft", "dpo", "grpo", "gguf"):
        _ptr = _con.latest(_st) or {}
        _stage_rows.append(f"| `{_st}/` | {_ptr.get('status', 'empty - no checkpoint yet')} |")

    _sess_log = "\n".join(f"- `{_f}`" for _f in _con.tree(continuum.CODE_REPO)
                           if _f.startswith("sessions/"))

    mo.md(f"""
    # WINCLAW - Continuum status

    **Last pushed session:** `{_sess_id}` \u00b7 **written:** {_created} \u00b7 **host GPU:** `{_gpu}`

    | repository | kind | link |
    |---|---|---|
    | `winclaw-harness` | dataset | https://huggingface.co/datasets/hkblockchaintechnology/winclaw-harness |
    | `winclaw-0-150m` | model | https://huggingface.co/hkblockchaintechnology/winclaw-0-150m |
    | `winclaw-corpus` | dataset | https://huggingface.co/datasets/hkblockchaintechnology/winclaw-corpus |
    | `winclaw-tasks` | dataset | https://huggingface.co/datasets/hkblockchaintechnology/winclaw-tasks |

    ## Last verified sync

    {_tot:,} bytes across {len(_rows)} files, each with its own sha256. The resume gate
    re-verifies every hash before training is allowed to continue.

    | file | sha256 | bytes |
    |---|---|---|
    {chr(10).join(_rows)}

    ## Model stage pointers

    | stage | latest.json |
    |---|---|
    {chr(10).join(_stage_rows)}

    ## Session log on the Hub

    {_sess_log or "- none yet"}

    ## The one manual step, every session

    The token. Re-supplied per session via `HF_TOKEN` or `~/.config/winclaw/token` (0600).
    It is deliberately absent from all notebook source, because Molab persists cell
    source and a shared notebook would leak it.

    {f"**ERROR:** {_err}" if _err else ""}
    """)

    return


@app.cell
def capabilities(capabilities, mo):

    # The capability surface. Every number below is counted from
    # winclaw/capabilities.py, not asserted in prose.
    _aud = capabilities.audit()
    _claims = capabilities.requirements_markdown()
    _matrix = capabilities.markdown()
    _bad = ("\n".join("- " + p for p in _aud["problems"])) if _aud["problems"] else        "none - every channel has a mechanism, every verb is verifiable"

    mo.md(f"""
    # WINCLAW - capability surface

    The purpose stated: **see, click, type, know all input and output, and write and run
    code.** That is a specification, so it is enumerable. It is not 11 action verbs, it is
    **{_aud['channels']} perception channels x {_aud['verbs']} action verbs** =
    {_aud['channels'] * _aud['verbs']:,} possible channel-verb interactions.

    ## Requirements, resolved against the matrix

    {_claims}

    ## Integrity audit

    | check | result |
    |---|---|
    | channel mechanisms declared | {len(capabilities.CHANNELS)} / {len(capabilities.CHANNELS)} |
    | verb mechanisms declared | {len(capabilities.VERBS)} / {len(capabilities.VERBS)} |
    | verbs with no verifying channel | **0** - the audit rejects them |
    | audit problems | {_bad} |

    Rule the audit enforces: *a capability whose effect we cannot observe is not a
    capability, it is a hope.* Every verb declares the channels that confirm it worked,
    which is also exactly the reward path.

    ## Risk enforcement

    {_aud['risk_histogram']['none']} verbs run free, {_aud['risk_histogram']['low']} are audited,
    {_aud['risk_histogram']['high']} take a state snapshot and are revertible, and
    {_aud['risk_histogram']['critical']} are denied unless explicitly confirmed.

    ## Full matrix

    {_matrix}
    """)

    return


@app.cell
def the_bet(boundary, mo):

    # The inversion, made explicit and testable.
    _b = boundary.audit()
    _true = "\n".join(f"- {_x}" for _x in boundary.CLAIM["why_it_could_be_true"])
    _false = "\n".join(f"- {_x}" for _x in boundary.CLAIM["why_it_could_be_false"])
    _test = "\n".join(f"{_i + 1}. {_x}" for _i, _x in enumerate(boundary.CLAIM["how_we_test_it"]))
    _learn = "\n".join(f"- {_x}" for _x in boundary.CLAIM["what_we_learn_either_way"])

    mo.md(f"""
    # The bet

    People train a general multi-function model and then put it inside an agentic
    harness. WINCLAW is the inverse: **the harness interface is fixed first, and the
    model is trained from random init against it.** The model is therefore not a
    component inside a harness - it is the harness core. That difference is engineering,
    not branding, and it has four consequences.

    ## What the inversion buys

    - **No interface tax.** The observation format and the action space *are* the model's
      pretraining distribution. A general model must translate between its internal
      representation and whatever the harness speaks, and that translation is loss.
    - **Labels instead of rubrics.** Every training token carries an exact label from the
      simulator. Adapting a general model means prompts and judge models. Learning-signal
      quality is the scarce resource, and here we own it outright.
    - **Architecture matched to the action space.** Spatial pointing for click targets,
      typed slots for arguments - rather than asking a text model to emit coordinates as
      characters and hoping.
    - **Small becomes viable.** Because it does one thing, 150M has a real chance against
      something several times larger. That is a testable claim, not a slogan.

    ## What it costs

    {_false}

    Honest framing: the conventional approach optimises for *model generality* and pays at
    the interface. Ours optimises for *interface fidelity* and pays in *generalisation*.
    Both are bets. Ours is only the right bet because we own the labels.

    ## The boundary that makes a small model viable

    {boundary.markdown()}

    Audit: {_b["counts"]["model"]} decisions to the model, {_b["counts"]["harness"]} to the
    harness, {_b["counts"]["shared"]} shared - **{'PASS' if _b["ok"] else 'FAIL'}**.
    The rule is enforced in code: deterministic work is never assigned to weights.

    ## The falsifiable claim

    > {boundary.CLAIM["statement"]}

    **Why it could be true**

    {_true}

    **How it gets tested**

    {_test}

    **What we learn either way**

    {_learn}

    ## Precedent, stated fairly

    {boundary.CLAIM["honest_precedent"]}

    ## Still unresolved

    {boundary.CLAIM["baseline_decision"]}
    """)

    return


@app.cell
def design_register(
    actlang,
    audit,
    boundary,
    capabilities,
    design,
    harness,
    mo,
    modelspec,
    policy,
    rasteron,
    roadmap,
    tokenizer,
    training,
    transfer,
    uialite,
    verdict,
    vertical,
    winsim,
):

    # "Complete" as a checklist rather than a feeling. This register is the authority; the
    # earlier prose design cell is superseded by it. Two different things are tracked, and
    # conflating them is how a design lies to itself:
    #   design_complete  - every item is specified, with a done-criterion and dependencies
    #   blockers_cleared - a blocker is only cleared when a VERIFIED item claims it
    _c = design.completeness()
    _st = design.status(audit.audit()["blockers"])
    _res = design.resolutions(audit.audit()["blockers"])
    _specs = (("uialite", uialite), ("actlang", actlang), ("modelspec", modelspec),
              ("rasteron", rasteron), ("winsim", winsim), ("harness", harness),
              ("verdict", verdict), ("policy", policy), ("tokenizer", tokenizer),
              ("training", training), ("vertical", vertical), ("roadmap", roadmap),
              ("transfer", transfer), ("capabilities", capabilities), ("boundary", boundary),
              ("audit", audit))
    _rows, _n, _pass = [], 0, 0
    for _name, _mod in _specs:
        if not hasattr(_mod, "audit"):
            continue
        _n += 1
        try:
            _a = _mod.audit()
            _ok = _a.get("ok", True)
            _pass += _ok
            _rows.append(f"| `{_name}` | **{'PASS' if _ok else 'FAIL'}** | "
                         f"{'; '.join(_a.get('problems') or []) or '-'} |")
        except Exception as _e:
            _rows.append(f"| `{_name}` | **ERROR** | {type(_e).__name__}: {_e} |")
    _res_rows = "\n".join(
        f"| `{_r['blocker']}` | {', '.join(_r['claimed_by'])} | "
        f"{', '.join(_r['cleared_by']) or '**none**'} | {'yes' if _r['cleared'] else '**no**'} |"
        for _r in _res)
    _status = "\n".join(f"| {_i.id} | {_i.title} | **{_i.status}** | "
                         f"{', '.join(_i.depends_on) or '-'} |" for _i in design.REGISTER)

    mo.md(f"""
    # WINCLAW design register

    ## Design: {_st['percent']}% specified. Blockers cleared: {_st['blockers_cleared']} of {_st['blockers_total']}.

    > **The register is complete and nothing is built.** All {_c['total']} items are specified
    > ({_c['by_status']['specified']} specified, {_c['by_status']['verified']} verified), and
    > {_pass}/{_n} spec audits pass. But a blocker is only *claimed* by a design item - it is
    > *cleared* only when that item is verified by execution. On that measure the project is at
    > **{_st['blockers_cleared']} of {_st['blockers_total']}**.

    ## Open blockers

    | blocker | claimed by | cleared by | cleared |
    |---|---|---|---|
    {_res_rows}

    ## Spec audit board

    | spec | audit | problems |
    |---|---|---|
    {chr(10).join(_rows)}

    ## Register

    | id | item | status | depends on |
    |---|---|---|---|
    {_status}
    """)

    return


@app.cell
def design_core(actlang, mo, modelspec, uialite):

    # The three foundational specs. Everything else consumes these: WinSim emits UiaLite,
    # the model reads UiaLite and emits ActLang, and both are sized against the ledger.
    mo.md(f"""
    # Core specs

    ## UiaLite - observation schema

    {uialite.markdown()}

    ## ActLang - action language

    {actlang.markdown()}

    ## Modelspec - parameter ledger and context budget

    {modelspec.markdown()}
    """)

    return


@app.cell
def design_runtime(harness, mo, rasteron, winsim):
    mo.md(f"""
    # Runtime specs

    ## Rasteron - the rasteriser, and its determinism contract

    {rasteron.markdown()}

    ## WinSim - the substrate

    {winsim.markdown()}

    ## Harness - the control loop

    {harness.markdown()}
    """)
    return


@app.cell
def design_program(
    mo,
    policy,
    roadmap,
    tokenizer,
    training,
    transfer,
    verdict,
    vertical,
):
    mo.md(f"""
    # Programme specs

    ## The vertical slice

    {vertical.markdown()}

    ## Roadmap in sessions

    {roadmap.markdown()}

    ## Training plan

    {training.markdown()}

    ## Verdict - checkers, metrics and the pre-registered claim

    {verdict.markdown()}

    ## Safety policy

    {policy.markdown()}

    ## Tokenizer

    {tokenizer.markdown()}

    ## Real Windows bridge

    {transfer.markdown()}
    """)
    return


@app.cell
def design_audit(audit, mo):

    # The design auditing itself. Findings marked [proved] were demonstrated by running
    # the code, not by reading it.
    _a = audit.audit()
    _trust = "\n".join(f"- {_x}" for _x in audit.VERDICT["trustworthy_now"])
    _mistrust = "\n".join(f"- {_x}" for _x in audit.VERDICT["not_trustworthy"])
    _fix = "\n".join(f"{_i + 1}. {_x}" for _i, _x in enumerate(audit.VERDICT["top_five_changes"]))

    mo.md(f"""
    # Design audit - WINCLAW against itself

    **Verdict: the design is NOT finished.** {_a["total"]} findings -
    **{_a["by_severity"]["blocker"]} blockers, {_a["by_severity"]["major"]} major,
    {_a["by_severity"]["minor"]} minor** - of which {_a["proved_by_running"]} were proved by
    running the code rather than reading it. The blockers:

    {chr(10).join("- `" + _k + "`" for _k in _a["blockers"])}

    > {audit.VERDICT["ratio"]}

    ## What I trust right now

    {_trust}

    ## What I do not trust

    {_mistrust}

    ## The five changes this audit requires

    {_fix}

    ## Full findings

    {audit.markdown()}
    """)

    return


if __name__ == "__main__":
    app.run()