File size: 59,935 Bytes
816fa8a
dec006b
816fa8a
 
dec006b
816fa8a
 
 
 
dec006b
816fa8a
 
 
 
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
 
 
 
 
 
 
 
 
 
 
dec006b
 
816fa8a
dec006b
 
816fa8a
 
 
 
 
 
 
 
dec006b
816fa8a
dec006b
 
 
816fa8a
 
 
 
dec006b
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
816fa8a
 
 
 
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
 
 
 
 
 
 
 
816fa8a
 
 
 
 
 
 
 
 
dec006b
 
 
 
 
 
816fa8a
 
 
 
 
 
dec006b
816fa8a
 
 
 
 
 
 
 
dec006b
816fa8a
dec006b
816fa8a
 
 
 
 
 
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
dec006b
816fa8a
 
dec006b
816fa8a
 
 
 
 
 
 
 
 
dec006b
 
 
 
 
 
 
 
 
816fa8a
 
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
dec006b
816fa8a
 
 
 
 
 
 
 
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
import { Fragment, createElement, useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
import type { FormEvent, ReactNode } from "react";
// @ts-expect-error TS7016: Frozen marked 4.3.0 has no declarations; its consumed API is typed below.
import { marked as untypedMarked } from "marked";
import { BRAIN_BODY_LIMIT_MESSAGE, BRAIN_MAX_BODY_BYTES, fileDate, IntelligenceApiError, intelligenceProblem } from "./intelligenceApi";
import type { IntelligenceApi, IntelligenceFile, IntelligenceProposal } from "./intelligenceApi";
import PromptView from "./PromptView";
import Proposals from "./Proposals";
import History from "./History";
import "../styles/sdlc75/brain-editor.css";

interface MarkdownToken {
  type: string; text?: string; raw?: string; tokens?: MarkdownToken[]; depth?: number;
  href?: string; ordered?: boolean; start?: number; items?: MarkdownToken[];
  header?: MarkdownToken[]; rows?: MarkdownToken[][]; task?: boolean; checked?: boolean; inRawBlock?: boolean;
}
const markdownParser: {
  lexer(source: string): MarkdownToken[]; Lexer: { lexInline(source: string): MarkdownToken[] };
} = untypedMarked;

// HTML Living Standard named references, grouped by Unicode value. No markup parser or DOM sink.
const markdownEntities = new Map(`
  100:Amacr 101:amacr 102:Abreve 103:abreve 104:Aogon 105:aogon 106:Cacute 107:cacute 108:Ccirc 109:ccirc 10a:Cdot
  10b:cdot 10c:Ccaron 10d:ccaron 10e:Dcaron 10f:dcaron 110:Dstrok 111:dstrok 112:Emacr 113:emacr 116:Edot 117:edot
  118:Eogon 119:eogon 11a:Ecaron 11b:ecaron 11c:Gcirc 11d:gcirc 11e:Gbreve 11f:gbreve 120:Gdot 121:gdot 122:Gcedil
  124:Hcirc 125:hcirc 126:Hstrok 127:hstrok 128:Itilde 129:itilde 12a:Imacr 12b:imacr 12e:Iogon 12f:iogon 130:Idot
  131:imath,inodot 132:IJlig 133:ijlig 134:Jcirc 135:jcirc 136:Kcedil 137:kcedil 138:kgreen 139:Lacute 13a:lacute
  13b:Lcedil 13c:lcedil 13d:Lcaron 13e:lcaron 13f:Lmidot 140:lmidot 141:Lstrok 142:lstrok 143:Nacute 144:nacute
  145:Ncedil 146:ncedil 147:Ncaron 148:ncaron 149:napos 14a:ENG 14b:eng 14c:Omacr 14d:omacr 150:Odblac 151:odblac
  152:OElig 153:oelig 154:Racute 155:racute 156:Rcedil 157:rcedil 158:Rcaron 159:rcaron 15a:Sacute 15b:sacute
  15c:Scirc 15d:scirc 15e:Scedil 15f:scedil 160:Scaron 161:scaron 162:Tcedil 163:tcedil 164:Tcaron 165:tcaron
  166:Tstrok 167:tstrok 168:Utilde 169:utilde 16a:Umacr 16b:umacr 16c:Ubreve 16d:ubreve 16e:Uring 16f:uring 170:Udblac
  171:udblac 172:Uogon 173:uogon 174:Wcirc 175:wcirc 176:Ycirc 177:ycirc 178:Yuml 179:Zacute 17a:zacute 17b:Zdot
  17c:zdot 17d:Zcaron 17e:zcaron 192:fnof 1b5:imped 1d49c:Ascr 1d49e:Cscr 1d49f:Dscr 1d4a2:Gscr 1d4a5:Jscr 1d4a6:Kscr
  1d4a9:Nscr 1d4aa:Oscr 1d4ab:Pscr 1d4ac:Qscr 1d4ae:Sscr 1d4af:Tscr 1d4b0:Uscr 1d4b1:Vscr 1d4b2:Wscr 1d4b3:Xscr
  1d4b4:Yscr 1d4b5:Zscr 1d4b6:ascr 1d4b7:bscr 1d4b8:cscr 1d4b9:dscr 1d4bb:fscr 1d4bd:hscr 1d4be:iscr 1d4bf:jscr
  1d4c0:kscr 1d4c1:lscr 1d4c2:mscr 1d4c3:nscr 1d4c5:pscr 1d4c6:qscr 1d4c7:rscr 1d4c8:sscr 1d4c9:tscr 1d4ca:uscr
  1d4cb:vscr 1d4cc:wscr 1d4cd:xscr 1d4ce:yscr 1d4cf:zscr 1d504:Afr 1d505:Bfr 1d507:Dfr 1d508:Efr 1d509:Ffr 1d50a:Gfr
  1d50d:Jfr 1d50e:Kfr 1d50f:Lfr 1d510:Mfr 1d511:Nfr 1d512:Ofr 1d513:Pfr 1d514:Qfr 1d516:Sfr 1d517:Tfr 1d518:Ufr
  1d519:Vfr 1d51a:Wfr 1d51b:Xfr 1d51c:Yfr 1d51e:afr 1d51f:bfr 1d520:cfr 1d521:dfr 1d522:efr 1d523:ffr 1d524:gfr
  1d525:hfr 1d526:ifr 1d527:jfr 1d528:kfr 1d529:lfr 1d52a:mfr 1d52b:nfr 1d52c:ofr 1d52d:pfr 1d52e:qfr 1d52f:rfr
  1d530:sfr 1d531:tfr 1d532:ufr 1d533:vfr 1d534:wfr 1d535:xfr 1d536:yfr 1d537:zfr 1d538:Aopf 1d539:Bopf 1d53b:Dopf
  1d53c:Eopf 1d53d:Fopf 1d53e:Gopf 1d540:Iopf 1d541:Jopf 1d542:Kopf 1d543:Lopf 1d544:Mopf 1d546:Oopf 1d54a:Sopf
  1d54b:Topf 1d54c:Uopf 1d54d:Vopf 1d54e:Wopf 1d54f:Xopf 1d550:Yopf 1d552:aopf 1d553:bopf 1d554:copf 1d555:dopf
  1d556:eopf 1d557:fopf 1d558:gopf 1d559:hopf 1d55a:iopf 1d55b:jopf 1d55c:kopf 1d55d:lopf 1d55e:mopf 1d55f:nopf
  1d560:oopf 1d561:popf 1d562:qopf 1d563:ropf 1d564:sopf 1d565:topf 1d566:uopf 1d567:vopf 1d568:wopf 1d569:xopf
  1d56a:yopf 1d56b:zopf 1f5:gacute 2002:ensp 2003:emsp 2004:emsp13 2005:emsp14 2007:numsp 2008:puncsp
  2009:ThinSpace,thinsp 200a:VeryThinSpace,hairsp
  200b:NegativeMediumSpace,NegativeThickSpace,NegativeThinSpace,NegativeVeryThinSpace,ZeroWidthSpace 200c:zwnj
  200d:zwj 200e:lrm 200f:rlm 2010:dash,hyphen 2013:ndash 2014:mdash 2015:horbar 2016:Verbar,Vert
  2018:OpenCurlyQuote,lsquo 2019:CloseCurlyQuote,rsquo,rsquor 201a:lsquor,sbquo 201c:OpenCurlyDoubleQuote,ldquo
  201d:CloseCurlyDoubleQuote,rdquo,rdquor 201e:bdquo,ldquor 2020:dagger 2021:Dagger,ddagger 2022:bull,bullet 2025:nldr
  2026:hellip,mldr 2030:permil 2031:pertenk 2032:prime 2033:Prime 2034:tprime 2035:backprime,bprime 2039:lsaquo
  203a:rsaquo 203e:OverBar,oline 2041:caret 2043:hybull 2044:frasl 204f:bsemi 2057:qprime 205f,200a:ThickSpace
  205f:MediumSpace 2060:NoBreak 2061:ApplyFunction,af 2062:InvisibleTimes,it 2063:InvisibleComma,ic 20ac:euro
  20db:TripleDot,tdot 20dc:DotDot 2102:Copf,complexes 2105:incare 210a:gscr 210b:HilbertSpace,Hscr,hamilt
  210c:Hfr,Poincareplane 210d:Hopf,quaternions 210e:planckh 210f:hbar,hslash,planck,plankv 2110:Iscr,imagline
  2111:Ifr,Im,image,imagpart 2112:Laplacetrf,Lscr,lagran 2113:ell 2115:Nopf,naturals 2116:numero 2117:copysr
  2118:weierp,wp 2119:Popf,primes 211a:Qopf,rationals 211b:Rscr,realine 211c:Re,Rfr,real,realpart 211d:Ropf,reals
  211e:rx 2122:TRADE,trade 2124:Zopf,integers 2127:mho 2128:Zfr,zeetrf 2129:iiota 212c:Bernoullis,Bscr,bernou
  212d:Cayleys,Cfr 212f:escr 2130:Escr,expectation 2131:Fouriertrf,Fscr 2133:Mellintrf,Mscr,phmmat
  2134:order,orderof,oscr 2135:alefsym,aleph 2136:beth 2137:gimel 2138:daleth 2145:CapitalDifferentialD,DD
  2146:DifferentialD,dd 2147:ExponentialE,ee,exponentiale 2148:ImaginaryI,ii 2153:frac13 2154:frac23 2155:frac15
  2156:frac25 2157:frac35 2158:frac45 2159:frac16 215a:frac56 215b:frac18 215c:frac38 215d:frac58 215e:frac78
  2190:LeftArrow,ShortLeftArrow,larr,leftarrow,slarr 2191:ShortUpArrow,UpArrow,uarr,uparrow
  2192:RightArrow,ShortRightArrow,rarr,rightarrow,srarr 2193:DownArrow,ShortDownArrow,darr,downarrow
  2194:LeftRightArrow,harr,leftrightarrow 2195:UpDownArrow,updownarrow,varr 2196:UpperLeftArrow,nwarr,nwarrow
  2197:UpperRightArrow,nearr,nearrow 2198:LowerRightArrow,searr,searrow 2199:LowerLeftArrow,swarr,swarrow
  219a:nlarr,nleftarrow 219b:nrarr,nrightarrow 219d,338:nrarrw 219d:rarrw,rightsquigarrow 219e:Larr,twoheadleftarrow
  219f:Uarr 21:excl 21a0:Rarr,twoheadrightarrow 21a1:Darr 21a2:larrtl,leftarrowtail 21a3:rarrtl,rightarrowtail
  21a4:LeftTeeArrow,mapstoleft 21a5:UpTeeArrow,mapstoup 21a6:RightTeeArrow,map,mapsto 21a7:DownTeeArrow,mapstodown
  21a9:hookleftarrow,larrhk 21aa:hookrightarrow,rarrhk 21ab:larrlp,looparrowleft 21ac:looparrowright,rarrlp
  21ad:harrw,leftrightsquigarrow 21ae:nharr,nleftrightarrow 21b0:Lsh,lsh 21b1:Rsh,rsh 21b2:ldsh 21b3:rdsh 21b5:crarr
  21b6:cularr,curvearrowleft 21b7:curarr,curvearrowright 21ba:circlearrowleft,olarr 21bb:circlearrowright,orarr
  21bc:LeftVector,leftharpoonup,lharu 21bd:DownLeftVector,leftharpoondown,lhard
  21be:RightUpVector,uharr,upharpoonright 21bf:LeftUpVector,uharl,upharpoonleft 21c0:RightVector,rharu,rightharpoonup
  21c1:DownRightVector,rhard,rightharpoondown 21c2:RightDownVector,dharr,downharpoonright
  21c3:LeftDownVector,dharl,downharpoonleft 21c4:RightArrowLeftArrow,rightleftarrows,rlarr 21c5:UpArrowDownArrow,udarr
  21c6:LeftArrowRightArrow,leftrightarrows,lrarr 21c7:leftleftarrows,llarr 21c8:upuparrows,uuarr
  21c9:rightrightarrows,rrarr 21ca:ddarr,downdownarrows 21cb:ReverseEquilibrium,leftrightharpoons,lrhar
  21cc:Equilibrium,rightleftharpoons,rlhar 21cd:nLeftarrow,nlArr 21ce:nLeftrightarrow,nhArr 21cf:nRightarrow,nrArr
  21d0:DoubleLeftArrow,Leftarrow,lArr 21d1:DoubleUpArrow,Uparrow,uArr 21d2:DoubleRightArrow,Implies,Rightarrow,rArr
  21d3:DoubleDownArrow,Downarrow,dArr 21d4:DoubleLeftRightArrow,Leftrightarrow,hArr,iff
  21d5:DoubleUpDownArrow,Updownarrow,vArr 21d6:nwArr 21d7:neArr 21d8:seArr 21d9:swArr 21da:Lleftarrow,lAarr
  21db:Rrightarrow,rAarr 21dd:zigrarr 21e4:LeftArrowBar,larrb 21e5:RightArrowBar,rarrb 21f5:DownArrowUpArrow,duarr
  21fd:loarr 21fe:roarr 21ff:hoarr 2200:ForAll,forall 2201:comp,complement 2202,338:npart 2202:PartialD,part
  2203:Exists,exist 2204:NotExists,nexist,nexists 2205:empty,emptyset,emptyv,varnothing 2207:Del,nabla
  2208:Element,in,isin,isinv 2209:NotElement,notin,notinva 220b:ReverseElement,SuchThat,ni,niv
  220c:NotReverseElement,notni,notniva 220f:Product,prod 2210:Coproduct,coprod 2211:Sum,sum 2212:minus
  2213:MinusPlus,mnplus,mp 2214:dotplus,plusdo 2216:Backslash,setminus,setmn,smallsetminus,ssetmn 2217:lowast
  2218:SmallCircle,compfn 221a:Sqrt,radic 221d:Proportional,prop,propto,varpropto,vprop 221e:infin 221f:angrt
  2220,20d2:nang 2220:ang,angle 2221:angmsd,measuredangle 2222:angsph 2223:VerticalBar,mid,shortmid,smid
  2224:NotVerticalBar,nmid,nshortmid,nsmid 2225:DoubleVerticalBar,par,parallel,shortparallel,spar
  2226:NotDoubleVerticalBar,npar,nparallel,nshortparallel,nspar 2227:and,wedge 2228:or,vee 2229,fe00:caps 2229:cap
  222a,fe00:cups 222a:cup 222b:Integral,int 222c:Int 222d:iiint,tint 222e:ContourIntegral,conint,oint
  222f:Conint,DoubleContourIntegral 2230:Cconint 2231:cwint 2232:ClockwiseContourIntegral,cwconint
  2233:CounterClockwiseContourIntegral,awconint 2234:Therefore,there4,therefore 2235:Because,becaus,because 2236:ratio
  2237:Colon,Proportion 2238:dotminus,minusd 223a:mDDot 223b:homtht 223c,20d2:nvsim 223c:Tilde,sim,thicksim,thksim
  223d,331:race 223d:backsim,bsim 223e,333:acE 223e:ac,mstpos 223f:acd 2240:VerticalTilde,wr,wreath 2241:NotTilde,nsim
  2242,338:NotEqualTilde,nesim 2242:EqualTilde,eqsim,esim 2243:TildeEqual,sime,simeq 2244:NotTildeEqual,nsime,nsimeq
  2245:TildeFullEqual,cong 2246:simne 2247:NotTildeFullEqual,ncong 2248:TildeTilde,ap,approx,asymp,thickapprox,thkap
  2249:NotTildeTilde,nap,napprox 224a:ape,approxeq 224b,338:napid 224b:apid 224c:backcong,bcong 224d,20d2:nvap
  224d:CupCap,asympeq 224e,338:NotHumpDownHump,nbump 224e:Bumpeq,HumpDownHump,bump 224f,338:NotHumpEqual,nbumpe
  224f:HumpEqual,bumpe,bumpeq 2250,338:nedot 2250:DotEqual,doteq,esdot 2251:doteqdot,eDot 2252:efDot,fallingdotseq
  2253:erDot,risingdotseq 2254:Assign,colone,coloneq 2255:ecolon,eqcolon 2256:ecir,eqcirc 2257:circeq,cire 2259:wedgeq
  225a:veeeq 225c:triangleq,trie 225f:equest,questeq 2260:NotEqual,ne 2261,20e5:bnequiv 2261:Congruent,equiv
  2262:NotCongruent,nequiv 2264,20d2:nvle 2264:le,leq 2265,20d2:nvge 2265:GreaterEqual,ge,geq 2266,338:nlE,nleqq
  2266:LessFullEqual,lE,leqq 2267,338:NotGreaterFullEqual,ngE,ngeqq 2267:GreaterFullEqual,gE,geqq
  2268,fe00:lvertneqq,lvnE 2268:lnE,lneqq 2269,fe00:gvertneqq,gvnE 2269:gnE,gneqq 226a,20d2:nLt
  226a,338:NotLessLess,nLtv 226a:Lt,NestedLessLess,ll 226b,20d2:nGt 226b,338:NotGreaterGreater,nGtv
  226b:Gt,NestedGreaterGreater,gg 226c:between,twixt 226d:NotCupCap 226e:NotLess,nless,nlt 226f:NotGreater,ngt,ngtr
  2270:NotLessEqual,nle,nleq 2271:NotGreaterEqual,nge,ngeq 2272:LessTilde,lesssim,lsim 2273:GreaterTilde,gsim,gtrsim
  2274:NotLessTilde,nlsim 2275:NotGreaterTilde,ngsim 2276:LessGreater,lessgtr,lg 2277:GreaterLess,gl,gtrless
  2278:NotLessGreater,ntlg 2279:NotGreaterLess,ntgl 227a:Precedes,pr,prec 227b:Succeeds,sc,succ
  227c:PrecedesSlantEqual,prcue,preccurlyeq 227d:SucceedsSlantEqual,sccue,succcurlyeq 227e:PrecedesTilde,precsim,prsim
  227f,338:NotSucceedsTilde 227f:SucceedsTilde,scsim,succsim 2280:NotPrecedes,npr,nprec 2281:NotSucceeds,nsc,nsucc
  2282,20d2:NotSubset,nsubset,vnsub 2282:sub,subset 2283,20d2:NotSuperset,nsupset,vnsup 2283:Superset,sup,supset
  2284:nsub 2285:nsup 2286:SubsetEqual,sube,subseteq 2287:SupersetEqual,supe,supseteq
  2288:NotSubsetEqual,nsube,nsubseteq 2289:NotSupersetEqual,nsupe,nsupseteq 228a,fe00:varsubsetneq,vsubne
  228a:subne,subsetneq 228b,fe00:varsupsetneq,vsupne 228b:supne,supsetneq 228d:cupdot 228e:UnionPlus,uplus
  228f,338:NotSquareSubset 228f:SquareSubset,sqsub,sqsubset 2290,338:NotSquareSuperset
  2290:SquareSuperset,sqsup,sqsupset 2291:SquareSubsetEqual,sqsube,sqsubseteq
  2292:SquareSupersetEqual,sqsupe,sqsupseteq 2293,fe00:sqcaps 2293:SquareIntersection,sqcap 2294,fe00:sqcups
  2294:SquareUnion,sqcup 2295:CirclePlus,oplus 2296:CircleMinus,ominus 2297:CircleTimes,otimes 2298:osol
  2299:CircleDot,odot 229a:circledcirc,ocir 229b:circledast,oast 229d:circleddash,odash 229e:boxplus,plusb
  229f:boxminus,minusb 22:QUOT,quot 22a0:boxtimes,timesb 22a1:dotsquare,sdotb 22a2:RightTee,vdash 22a3:LeftTee,dashv
  22a4:DownTee,top 22a5:UpTee,bot,bottom,perp 22a7:models 22a8:DoubleRightTee,vDash 22a9:Vdash 22aa:Vvdash 22ab:VDash
  22ac:nvdash 22ad:nvDash 22ae:nVdash 22af:nVDash 22b0:prurel 22b2:LeftTriangle,vartriangleleft,vltri
  22b3:RightTriangle,vartriangleright,vrtri 22b4,20d2:nvltrie 22b4:LeftTriangleEqual,ltrie,trianglelefteq
  22b5,20d2:nvrtrie 22b5:RightTriangleEqual,rtrie,trianglerighteq 22b6:origof 22b7:imof 22b8:multimap,mumap
  22b9:hercon 22ba:intcal,intercal 22bb:veebar 22bd:barvee 22be:angrtvb 22bf:lrtri 22c0:Wedge,bigwedge,xwedge
  22c1:Vee,bigvee,xvee 22c2:Intersection,bigcap,xcap 22c3:Union,bigcup,xcup 22c4:Diamond,diam,diamond 22c5:sdot
  22c6:Star,sstarf 22c7:divideontimes,divonx 22c8:bowtie 22c9:ltimes 22ca:rtimes 22cb:leftthreetimes,lthree
  22cc:rightthreetimes,rthree 22cd:backsimeq,bsime 22ce:curlyvee,cuvee 22cf:curlywedge,cuwed 22d0:Sub,Subset
  22d1:Sup,Supset 22d2:Cap 22d3:Cup 22d4:fork,pitchfork 22d5:epar 22d6:lessdot,ltdot 22d7:gtdot,gtrdot 22d8,338:nLl
  22d8:Ll 22d9,338:nGg 22d9:Gg,ggg 22da,fe00:lesg 22da:LessEqualGreater,leg,lesseqgtr 22db,fe00:gesl
  22db:GreaterEqualLess,gel,gtreqless 22de:cuepr,curlyeqprec 22df:cuesc,curlyeqsucc 22e0:NotPrecedesSlantEqual,nprcue
  22e1:NotSucceedsSlantEqual,nsccue 22e2:NotSquareSubsetEqual,nsqsube 22e3:NotSquareSupersetEqual,nsqsupe 22e6:lnsim
  22e7:gnsim 22e8:precnsim,prnsim 22e9:scnsim,succnsim 22ea:NotLeftTriangle,nltri,ntriangleleft
  22eb:NotRightTriangle,nrtri,ntriangleright 22ec:NotLeftTriangleEqual,nltrie,ntrianglelefteq
  22ed:NotRightTriangleEqual,nrtrie,ntrianglerighteq 22ee:vellip 22ef:ctdot 22f0:utdot 22f1:dtdot 22f2:disin
  22f3:isinsv 22f4:isins 22f5,338:notindot 22f5:isindot 22f6:notinvc 22f7:notinvb 22f9,338:notinE 22f9:isinE 22fa:nisd
  22fb:xnis 22fc:nis 22fd:notnivc 22fe:notnivb 2305:barwed,barwedge 2306:Barwed,doublebarwedge 2308:LeftCeiling,lceil
  2309:RightCeiling,rceil 230a:LeftFloor,lfloor 230b:RightFloor,rfloor 230c:drcrop 230d:dlcrop 230e:urcrop 230f:ulcrop
  2310:bnot 2312:profline 2313:profsurf 2315:telrec 2316:target 231c:ulcorn,ulcorner 231d:urcorn,urcorner
  231e:dlcorn,llcorner 231f:drcorn,lrcorner 2322:frown,sfrown 2323:smile,ssmile 232d:cylcty 232e:profalar 2336:topbot
  233d:ovbar 233f:solbar 237:jmath 237c:angzarr 23:num 23b0:lmoust,lmoustache 23b1:rmoust,rmoustache
  23b4:OverBracket,tbrk 23b5:UnderBracket,bbrk 23b6:bbrktbrk 23dc:OverParenthesis 23dd:UnderParenthesis 23de:OverBrace
  23df:UnderBrace 23e2:trpezium 23e7:elinters 2423:blank 24:dollar 24c8:circledS,oS 2500:HorizontalLine,boxh 2502:boxv
  250c:boxdr 2510:boxdl 2514:boxur 2518:boxul 251c:boxvr 2524:boxvl 252c:boxhd 2534:boxhu 253c:boxvh 2550:boxH
  2551:boxV 2552:boxdR 2553:boxDr 2554:boxDR 2555:boxdL 2556:boxDl 2557:boxDL 2558:boxuR 2559:boxUr 255a:boxUR
  255b:boxuL 255c:boxUl 255d:boxUL 255e:boxvR 255f:boxVr 2560:boxVR 2561:boxvL 2562:boxVl 2563:boxVL 2564:boxHd
  2565:boxhD 2566:boxHD 2567:boxHu 2568:boxhU 2569:boxHU 256a:boxvH 256b:boxVh 256c:boxVH 2580:uhblk 2584:lhblk
  2588:block 2591:blk14 2592:blk12 2593:blk34 25:percnt 25a1:Square,squ,square
  25aa:FilledVerySmallSquare,blacksquare,squarf,squf 25ab:EmptyVerySmallSquare 25ad:rect 25ae:marker 25b1:fltns
  25b3:bigtriangleup,xutri 25b4:blacktriangle,utrif 25b5:triangle,utri 25b8:blacktriangleright,rtrif
  25b9:rtri,triangleright 25bd:bigtriangledown,xdtri 25be:blacktriangledown,dtrif 25bf:dtri,triangledown
  25c2:blacktriangleleft,ltrif 25c3:ltri,triangleleft 25ca:loz,lozenge 25cb:cir 25ec:tridot 25ef:bigcirc,xcirc
  25f8:ultri 25f9:urtri 25fa:lltri 25fb:EmptySmallSquare 25fc:FilledSmallSquare 2605:bigstar,starf 2606:star
  260e:phone 2640:female 2642:male 2660:spades,spadesuit 2663:clubs,clubsuit 2665:hearts,heartsuit
  2666:diamondsuit,diams 266a:sung 266d:flat 266e:natur,natural 266f:sharp 26:AMP,amp 2713:check,checkmark 2717:cross
  2720:malt,maltese 2736:sext 2758:VerticalSeparator 2772:lbbrk 2773:rbbrk 27:apos 27c8:bsolhsub 27c9:suphsol
  27e6:LeftDoubleBracket,lobrk 27e7:RightDoubleBracket,robrk 27e8:LeftAngleBracket,lang,langle
  27e9:RightAngleBracket,rang,rangle 27ea:Lang 27eb:Rang 27ec:loang 27ed:roang 27f5:LongLeftArrow,longleftarrow,xlarr
  27f6:LongRightArrow,longrightarrow,xrarr 27f7:LongLeftRightArrow,longleftrightarrow,xharr
  27f8:DoubleLongLeftArrow,Longleftarrow,xlArr 27f9:DoubleLongRightArrow,Longrightarrow,xrArr
  27fa:DoubleLongLeftRightArrow,Longleftrightarrow,xhArr 27fc:longmapsto,xmap 27ff:dzigrarr 28:lpar 2902:nvlArr
  2903:nvrArr 2904:nvHarr 2905:Map 290c:lbarr 290d:bkarow,rbarr 290e:lBarr 290f:dbkarow,rBarr 2910:RBarr,drbkarow
  2911:DDotrahd 2912:UpArrowBar 2913:DownArrowBar 2916:Rarrtl 2919:latail 291a:ratail 291b:lAtail 291c:rAtail
  291d:larrfs 291e:rarrfs 291f:larrbfs 2920:rarrbfs 2923:nwarhk 2924:nearhk 2925:hksearow,searhk 2926:hkswarow,swarhk
  2927:nwnear 2928:nesear,toea 2929:seswar,tosa 292a:swnwar 2933,338:nrarrc 2933:rarrc 2935:cudarrr 2936:ldca
  2937:rdca 2938:cudarrl 2939:larrpl 293c:curarrm 293d:cularrp 2945:rarrpl 2948:harrcir 2949:Uarrocir 294a:lurdshar
  294b:ldrushar 294e:LeftRightVector 294f:RightUpDownVector 2950:DownLeftRightVector 2951:LeftUpDownVector
  2952:LeftVectorBar 2953:RightVectorBar 2954:RightUpVectorBar 2955:RightDownVectorBar 2956:DownLeftVectorBar
  2957:DownRightVectorBar 2958:LeftUpVectorBar 2959:LeftDownVectorBar 295a:LeftTeeVector 295b:RightTeeVector
  295c:RightUpTeeVector 295d:RightDownTeeVector 295e:DownLeftTeeVector 295f:DownRightTeeVector 2960:LeftUpTeeVector
  2961:LeftDownTeeVector 2962:lHar 2963:uHar 2964:rHar 2965:dHar 2966:luruhar 2967:ldrdhar 2968:ruluhar 2969:rdldhar
  296a:lharul 296b:llhard 296c:rharul 296d:lrhard 296e:UpEquilibrium,udhar 296f:ReverseUpEquilibrium,duhar
  2970:RoundImplies 2971:erarr 2972:simrarr 2973:larrsim 2974:rarrsim 2975:rarrap 2976:ltlarr 2978:gtrarr 2979:subrarr
  297b:suplarr 297c:lfisht 297d:rfisht 297e:ufisht 297f:dfisht 2985:lopar 2986:ropar 298b:lbrke 298c:rbrke
  298d:lbrkslu 298e:rbrksld 298f:lbrksld 2990:rbrkslu 2991:langd 2992:rangd 2993:lparlt 2994:rpargt 2995:gtlPar
  2996:ltrPar 299a:vzigzag 299c:vangrt 299d:angrtvbd 29:rpar 29a4:ange 29a5:range 29a6:dwangle 29a7:uwangle
  29a8:angmsdaa 29a9:angmsdab 29aa:angmsdac 29ab:angmsdad 29ac:angmsdae 29ad:angmsdaf 29ae:angmsdag 29af:angmsdah
  29b0:bemptyv 29b1:demptyv 29b2:cemptyv 29b3:raemptyv 29b4:laemptyv 29b5:ohbar 29b6:omid 29b7:opar 29b9:operp
  29bb:olcross 29bc:odsold 29be:olcir 29bf:ofcir 29c0:olt 29c1:ogt 29c2:cirscir 29c3:cirE 29c4:solb 29c5:bsolb
  29c9:boxbox 29cd:trisb 29ce:rtriltri 29cf,338:NotLeftTriangleBar 29cf:LeftTriangleBar 29d0,338:NotRightTriangleBar
  29d0:RightTriangleBar 29dc:iinfin 29dd:infintie 29de:nvinfin 29e3:eparsl 29e4:smeparsl 29e5:eqvparsl
  29eb:blacklozenge,lozf 29f4:RuleDelayed 29f6:dsol 2a00:bigodot,xodot 2a01:bigoplus,xoplus 2a02:bigotimes,xotime
  2a04:biguplus,xuplus 2a06:bigsqcup,xsqcup 2a0c:iiiint,qint 2a0d:fpartint 2a10:cirfnint 2a11:awint 2a12:rppolint
  2a13:scpolint 2a14:npolint 2a15:pointint 2a16:quatint 2a17:intlarhk 2a22:pluscir 2a23:plusacir 2a24:simplus
  2a25:plusdu 2a26:plussim 2a27:plustwo 2a29:mcomma 2a2a:minusdu 2a2d:loplus 2a2e:roplus 2a2f:Cross 2a30:timesd
  2a31:timesbar 2a33:smashp 2a34:lotimes 2a35:rotimes 2a36:otimesas 2a37:Otimes 2a38:odiv 2a39:triplus 2a3a:triminus
  2a3b:tritime 2a3c:intprod,iprod 2a3f:amalg 2a40:capdot 2a42:ncup 2a43:ncap 2a44:capand 2a45:cupor 2a46:cupcap
  2a47:capcup 2a48:cupbrcap 2a49:capbrcup 2a4a:cupcup 2a4b:capcap 2a4c:ccups 2a4d:ccaps 2a50:ccupssm 2a53:And 2a54:Or
  2a55:andand 2a56:oror 2a57:orslope 2a58:andslope 2a5a:andv 2a5b:orv 2a5c:andd 2a5d:ord 2a5f:wedbar 2a66:sdote
  2a6a:simdot 2a6d,338:ncongdot 2a6d:congdot 2a6e:easter 2a6f:apacir 2a70,338:napE 2a70:apE 2a71:eplus 2a72:pluse
  2a73:Esim 2a74:Colone 2a75:Equal 2a77:ddotseq,eDDot 2a78:equivDD 2a79:ltcir 2a7a:gtcir 2a7b:ltquest 2a7c:gtquest
  2a7d,338:NotLessSlantEqual,nleqslant,nles 2a7d:LessSlantEqual,leqslant,les
  2a7e,338:NotGreaterSlantEqual,ngeqslant,nges 2a7e:GreaterSlantEqual,geqslant,ges 2a7f:lesdot 2a80:gesdot
  2a81:lesdoto 2a82:gesdoto 2a83:lesdotor 2a84:gesdotol 2a85:lap,lessapprox 2a86:gap,gtrapprox 2a87:lne,lneq
  2a88:gne,gneq 2a89:lnap,lnapprox 2a8a:gnap,gnapprox 2a8b:lEg,lesseqqgtr 2a8c:gEl,gtreqqless 2a8d:lsime 2a8e:gsime
  2a8f:lsimg 2a90:gsiml 2a91:lgE 2a92:glE 2a93:lesges 2a94:gesles 2a95:els,eqslantless 2a96:egs,eqslantgtr 2a97:elsdot
  2a98:egsdot 2a99:el 2a9a:eg 2a9d:siml 2a9e:simg 2a9f:simlE 2a:ast,midast 2aa0:simgE 2aa1,338:NotNestedLessLess
  2aa1:LessLess 2aa2,338:NotNestedGreaterGreater 2aa2:GreaterGreater 2aa4:glj 2aa5:gla 2aa6:ltcc 2aa7:gtcc 2aa8:lescc
  2aa9:gescc 2aaa:smt 2aab:lat 2aac,fe00:smtes 2aac:smte 2aad,fe00:lates 2aad:late 2aae:bumpE
  2aaf,338:NotPrecedesEqual,npre,npreceq 2aaf:PrecedesEqual,pre,preceq 2ab0,338:NotSucceedsEqual,nsce,nsucceq
  2ab0:SucceedsEqual,sce,succeq 2ab3:prE 2ab4:scE 2ab5:precneqq,prnE 2ab6:scnE,succneqq 2ab7:prap,precapprox
  2ab8:scap,succapprox 2ab9:precnapprox,prnap 2aba:scnap,succnapprox 2abb:Pr 2abc:Sc 2abd:subdot 2abe:supdot
  2abf:subplus 2ac0:supplus 2ac1:submult 2ac2:supmult 2ac3:subedot 2ac4:supedot 2ac5,338:nsubE,nsubseteqq
  2ac5:subE,subseteqq 2ac6,338:nsupE,nsupseteqq 2ac6:supE,supseteqq 2ac7:subsim 2ac8:supsim
  2acb,fe00:varsubsetneqq,vsubnE 2acb:subnE,subsetneqq 2acc,fe00:varsupsetneqq,vsupnE 2acc:supnE,supsetneqq 2acf:csub
  2ad0:csup 2ad1:csube 2ad2:csupe 2ad3:subsup 2ad4:supsub 2ad5:subsub 2ad6:supsup 2ad7:suphsub 2ad8:supdsub 2ad9:forkv
  2ada:topfork 2adb:mlcp 2ae4:Dashv,DoubleLeftTee 2ae6:Vdashl 2ae7:Barv 2ae8:vBar 2ae9:vBarv 2aeb:Vbar 2aec:Not
  2aed:bNot 2aee:rnmid 2aef:cirmid 2af0:midcir 2af1:topcir 2af2:nhpar 2af3:parsim 2afd,20e5:nparsl 2afd:parsl 2b:plus
  2c6:circ 2c7:Hacek,caron 2c:comma 2d8:Breve,breve 2d9:DiacriticalDot,dot 2da:ring 2db:ogon
  2dc:DiacriticalTilde,tilde 2dd:DiacriticalDoubleAcute,dblac 2e:period 2f:sol 311:DownBreve 391:Alpha 392:Beta
  393:Gamma 394:Delta 395:Epsilon 396:Zeta 397:Eta 398:Theta 399:Iota 39a:Kappa 39b:Lambda 39c:Mu 39d:Nu 39e:Xi
  39f:Omicron 3a0:Pi 3a1:Rho 3a3:Sigma 3a4:Tau 3a5:Upsilon 3a6:Phi 3a7:Chi 3a8:Psi 3a9:Omega,ohm 3a:colon 3b1:alpha
  3b2:beta 3b3:gamma 3b4:delta 3b5:epsi,epsilon 3b6:zeta 3b7:eta 3b8:theta 3b9:iota 3b:semi 3ba:kappa 3bb:lambda
  3bc:mu 3bd:nu 3be:xi 3bf:omicron 3c,20d2:nvlt 3c0:pi 3c1:rho 3c2:sigmaf,sigmav,varsigma 3c3:sigma 3c4:tau
  3c5:upsi,upsilon 3c6:phi 3c7:chi 3c8:psi 3c9:omega 3c:LT,lt 3d,20e5:bne 3d1:thetasym,thetav,vartheta 3d2:Upsi,upsih
  3d5:phiv,straightphi,varphi 3d6:piv,varpi 3d:equals 3dc:Gammad 3dd:digamma,gammad 3e,20d2:nvgt 3e:GT,gt
  3f0:kappav,varkappa 3f1:rhov,varrho 3f5:epsiv,straightepsilon,varepsilon 3f6:backepsilon,bepsi 3f:quest 401:IOcy
  402:DJcy 403:GJcy 404:Jukcy 405:DScy 406:Iukcy 407:YIcy 408:Jsercy 409:LJcy 40:commat 40a:NJcy 40b:TSHcy 40c:KJcy
  40e:Ubrcy 40f:DZcy 410:Acy 411:Bcy 412:Vcy 413:Gcy 414:Dcy 415:IEcy 416:ZHcy 417:Zcy 418:Icy 419:Jcy 41a:Kcy 41b:Lcy
  41c:Mcy 41d:Ncy 41e:Ocy 41f:Pcy 420:Rcy 421:Scy 422:Tcy 423:Ucy 424:Fcy 425:KHcy 426:TScy 427:CHcy 428:SHcy
  429:SHCHcy 42a:HARDcy 42b:Ycy 42c:SOFTcy 42d:Ecy 42e:YUcy 42f:YAcy 430:acy 431:bcy 432:vcy 433:gcy 434:dcy 435:iecy
  436:zhcy 437:zcy 438:icy 439:jcy 43a:kcy 43b:lcy 43c:mcy 43d:ncy 43e:ocy 43f:pcy 440:rcy 441:scy 442:tcy 443:ucy
  444:fcy 445:khcy 446:tscy 447:chcy 448:shcy 449:shchcy 44a:hardcy 44b:ycy 44c:softcy 44d:ecy 44e:yucy 44f:yacy
  451:iocy 452:djcy 453:gjcy 454:jukcy 455:dscy 456:iukcy 457:yicy 458:jsercy 459:ljcy 45a:njcy 45b:tshcy 45c:kjcy
  45e:ubrcy 45f:dzcy 5b:lbrack,lsqb 5c:bsol 5d:rbrack,rsqb 5e:Hat 5f:UnderBar,lowbar 60:DiacriticalGrave,grave
  66,6a:fjlig 7b:lbrace,lcub 7c:VerticalLine,verbar,vert 7d:rbrace,rcub 9:Tab a0:NonBreakingSpace,nbsp a1:iexcl
  a2:cent a3:pound a4:curren a5:yen a6:brvbar a7:sect a8:Dot,DoubleDot,die,uml a9:COPY,copy a:NewLine aa:ordf ab:laquo
  ac:not ad:shy ae:REG,circledR,reg af:macr,strns b0:deg b1:PlusMinus,plusmn,pm b2:sup2 b3:sup3
  b4:DiacriticalAcute,acute b5:micro b6:para b7:CenterDot,centerdot,middot b8:Cedilla,cedil b9:sup1 ba:ordm bb:raquo
  bc:frac14 bd:frac12,half be:frac34 bf:iquest c0:Agrave c1:Aacute c2:Acirc c3:Atilde c4:Auml c5:Aring,angst c6:AElig
  c7:Ccedil c8:Egrave c9:Eacute ca:Ecirc cb:Euml cc:Igrave cd:Iacute ce:Icirc cf:Iuml d0:ETH d1:Ntilde d2:Ograve
  d3:Oacute d4:Ocirc d5:Otilde d6:Ouml d7:times d8:Oslash d9:Ugrave da:Uacute db:Ucirc dc:Uuml dd:Yacute de:THORN
  df:szlig e0:agrave e1:aacute e2:acirc e3:atilde e4:auml e5:aring e6:aelig e7:ccedil e8:egrave e9:eacute ea:ecirc
  eb:euml ec:igrave ed:iacute ee:icirc ef:iuml f0:eth f1:ntilde f2:ograve f3:oacute f4:ocirc f5:otilde f6:ouml
  f7:div,divide f8:oslash f9:ugrave fa:uacute fb00:fflig fb01:filig fb02:fllig fb03:ffilig fb04:ffllig fb:ucirc
  fc:uuml fd:yacute fe:thorn ff:yuml
`.trim().split(/\s+/).flatMap((entry) => {
  const [points, names] = entry.split(":");
  const value = String.fromCodePoint(...points.split(",").map((point) => Number.parseInt(point, 16)));
  return names.split(",").map((name) => [name, value] as const);
}));

/** Decode one text layer. Code spans arrive with every literal ampersand escaped by marked. */
function decodeMarkdownText(text = ""): string {
  return text.replace(/&(#(?:[xX][\da-fA-F]{1,6}|\d{1,7})|[A-Za-z][A-Za-z\d]{1,31});/g, (entity, reference: string) => {
    if (reference[0] !== "#") return markdownEntities.get(reference) ?? entity;
    let point = reference[1]?.toLowerCase() === "x"
      ? Number.parseInt(reference.slice(2), 16) : Number.parseInt(reference.slice(1), 10);
    if (!point || point > 0x10ffff || point >= 0xd800 && point <= 0xdfff) return "\ufffd";
    // HTML numeric references retain the legacy Windows-1252 replacements.
    if (point >= 0x80 && point <= 0x9f) point = [
      0x20ac, 0x81, 0x201a, 0x192, 0x201e, 0x2026, 0x2020, 0x2021,
      0x2c6, 0x2030, 0x160, 0x2039, 0x152, 0x8d, 0x17d, 0x8f,
      0x90, 0x2018, 0x2019, 0x201c, 0x201d, 0x2022, 0x2013, 0x2014,
      0x2dc, 0x2122, 0x161, 0x203a, 0x153, 0x9d, 0x17e, 0x178,
    ][point - 0x80];
    return String.fromCodePoint(point);
  });
}

function markdownImageLabel(token: MarkdownToken): MarkdownToken[] {
  // Original labels distinguish escaped punctuation from authored entities before marked escapes them.
  const raw = token.raw || "";
  let depth = 1;
  for (let index = 2; index < raw.length; index += 1) {
    if (raw[index] === "\\") { index += 1; continue; }
    if (raw[index] === "[") depth += 1;
    if (raw[index] === "]" && --depth === 0) return markdownParser.Lexer.lexInline(raw.slice(2, index));
  }
  return [{ type: "text", text: token.text }];
}

function safeLink(href = ""): string | undefined {
  if (/^#\//.test(href)) return href;
  try {
    const url = new URL(href);
    if (["https:", "http:", "mailto:"].includes(url.protocol) && !url.username && !url.password) return href;
  } catch { /* A relative file path has no navigation contract. */ }
  return undefined;
}
/** Use the installed Markdown parser, with React nodes instead of an HTML injection sink. */
function markdownNodes(tokens: MarkdownToken[], textOnly = false): ReactNode {
  let rawBlock = false;
  return tokens.map((token, index) => {
    const children = token.tokens ? markdownNodes(token.tokens, textOnly) : token.text || "";
    if (textOnly && token.tokens) return <Fragment key={index}>{children}</Fragment>;
    let node: ReactNode;
    switch (token.type) {
      case "space": return null;
      case "heading": node = createElement(`h${Math.min(6, Math.max(2, token.depth || 2))}`, null, children); break;
      case "paragraph": node = <p>{children}</p>; break;
      case "strong": node = <strong>{children}</strong>; break;
      case "em": node = <em>{children}</em>; break;
      case "del": node = <del>{children}</del>; break;
      case "codespan": node = textOnly ? decodeMarkdownText(token.text) : <code>{decodeMarkdownText(token.text)}</code>; break;
      case "code": node = <pre tabIndex={0}><code>{token.text}</code></pre>; break;
      case "text": node = token.tokens ? children : rawBlock ? token.text || "" : decodeMarkdownText(token.text); break;
      case "escape": node = decodeMarkdownText(token.text); break;
      case "html": rawBlock = !!token.inRawBlock; node = token.text || ""; break;
      case "blockquote": node = <blockquote>{children}</blockquote>; break;
      case "br": node = <br />; break;
      case "hr": node = <hr />; break;
      case "link": node = safeLink(token.href) ? <a href={safeLink(token.href)} rel="noopener noreferrer">{children}</a> : children; break;
      case "image": node = markdownNodes(markdownImageLabel(token), true); break;
      case "list": node = createElement(token.ordered ? "ol" : "ul", token.ordered ? { start: token.start } : {},
        token.items?.map((item, itemIndex) => <li key={itemIndex}>
          {item.task ? <input type="checkbox" checked={!!item.checked} disabled aria-label="Task" /> : null}
          {markdownNodes(item.tokens || [])}</li>)); break;
      case "table": node = <div className="intelligence-markdown-table" tabIndex={0} role="region" aria-label="File table"><table>
        <thead><tr>{token.header?.map((cell, cellIndex) => <th key={cellIndex} scope="col">{markdownNodes(cell.tokens || [])}</th>)}</tr></thead>
        <tbody>{token.rows?.map((row, rowIndex) => <tr key={rowIndex}>{row.map((cell, cellIndex) =>
          <td key={cellIndex}>{markdownNodes(cell.tokens || [])}</td>)}</tr>)}</tbody>
      </table></div>; break;
      // Raw HTML remains text. Images cannot make third-party requests from a private file.
      default: node = children;
    }
    return <Fragment key={index}>{node}</Fragment>;
  });
}

export function FileMarkdown({ body, preserveFrontmatter = false }: { body: string; preserveFrontmatter?: boolean }) {
  const content = preserveFrontmatter ? body : body.replace(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/, "");
  const nodes = useMemo(() => markdownNodes(markdownParser.lexer(content)), [content]);
  return <div className="intelligence-markdown" data-testid="intelligence-markdown">{nodes}</div>;
}

function frontMatter(body: string) {
  const prefix = body.match(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/)?.[0] || "";
  return { prefix, content: body.slice(prefix.length) };
}

function frontMatterField(prefix: string, key: string) {
  const field = prefix.match(new RegExp(`^${key}:[ \\t]*([^\\r\\n]*)`, "m"));
  if (!field) return undefined;
  let start = field.index! + field[0].length - field[1].length;
  if (!field[1]) {
    const leading = prefix.slice(start).match(/^(?:\r?\n[ \t]*)+/)?.[0] || "";
    if (/\n[ \t]+$/.test(leading)) start += leading.length;
  }
  const rest = prefix.slice(start);
  let length = field[1].length;
  if (/^["']/.test(rest)) {
    for (let index = 1; index < rest.length; index += 1) {
      if (rest[0] === '"' && rest[index] === "\\") { index += 1; continue; }
      if (rest[index] !== rest[0]) continue;
      if (rest[0] === "'" && rest[index + 1] === "'") { index += 1; continue; }
      length = index + 1; break;
    }
  } else {
    const scalar = rest.match(/^[^\r\n]*(?:\r?\n(?:[ \t]+[^\r\n]*|(?=\r?\n)))*/)?.[0] || "";
    length = /^[>|]/.test(rest) ? scalar.length : scalar
      .replace(/(?:\r?\n[ \t]*(?:#[^\r\n]*)?)*$/, "").replace(/[ \t]+#[^\r\n]*$/, "").trimEnd().length;
    if (/^[>|]/.test(rest)) {
      const lines = Array.from(scalar.matchAll(/\r?\n([^\r\n]*)/g));
      const indent = Number(scalar.match(/^[>|][+-]?([1-9])/)?.[1])
        || lines.find((line) => line[1].trim())?.[1].match(/^ */)?.[0].length || 0;
      const outside = lines.find((line) => line[1].trim() && (line[1].match(/^ */)?.[0].length || 0) < indent);
      if (outside) length = outside.index!;
    }
  }
  return { start, end: start + length, raw: rest.slice(0, length) };
}

/** Decode text scalars only. The server remains the validator for all front matter. */
function frontMatterValue(prefix: string, key: string, fallback?: string, originalPrefix?: string): string {
  const field = frontMatterField(prefix, key);
  if (originalPrefix !== undefined && fallback !== undefined
    && field?.raw === frontMatterField(originalPrefix, key)?.raw) return fallback;
  if (!field) return originalPrefix === undefined ? fallback || "" : "";
  const raw = field.raw.replace(/\r\n/g, "\n");
  const block = raw.match(/^([>|])([1-9]?[+-]?|[+-][1-9]?)[ \t]*(?:#.*)?(?=\n|$)/);
  if (block) {
    const lines = raw.includes("\n") ? raw.slice(block[0].length + 1).split("\n") : [];
    const indent = Number(block[2].match(/[1-9]/)?.[0])
      || lines.find((line) => line.trim())?.match(/^ */)?.[0].length
      || lines.reduce((width, line) => Math.max(width, line.length), 0);
    const text = lines.map((line) => line.slice(indent));
    const lastContent = text.reduce((last, line, index) => line ? index : last, -1);
    let value = "";
    text.forEach((line, index) => {
      const next = text[index + 1];
      value += line;
      if (block[1] === "|" || next === undefined || /^[ \t]/.test(line) || /^[ \t]/.test(next)) value += "\n";
      else if (line && next) value += " ";
      else if (!line || index >= lastContent || /^[ \t]/.test(text.slice(index + 1).find((part) => part) || "")) value += "\n";
    });
    if (block[2].includes("+")) return value;
    const stripped = value.replace(/\n+$/, "");
    return stripped + (!block[2].includes("-") && stripped ? "\n" : "");
  }
  const quote = /^["']/.test(raw) ? raw[0] : "";
  if (quote && (raw.length < 2 || !raw.endsWith(quote))) return "";
  const text = quote ? raw.slice(1, -1) : raw.split("\n")
    .filter((line) => !/^[ \t]*#/.test(line)).map((line) => line.replace(/(?:^|[ \t]+)#.*$/, "")).join("\n").trim();
  const escapes: Record<string, string> = {
    "0": "\0", a: "\x07", b: "\b", t: "\t", n: "\n", v: "\v", f: "\f", r: "\r", e: "\x1b",
    " ": " ", "\t": "\t", '"': '"', "/": "/", "\\": "\\", N: "\x85", _: "\xa0", L: "\u2028", P: "\u2029",
  };
  let value = "";
  for (let index = 0; index < text.length; index += 1) {
    const character = text[index];
    if (quote === '"' && character === "\\") {
      const escape = text[++index];
      if (escape === "\n") {
        while (/[ \t]/.test(text[index + 1] || "\0")) index += 1;
        while (text[index + 1] === "\n") {
          value += "\n"; index += 1;
          while (/[ \t]/.test(text[index + 1] || "\0")) index += 1;
        }
      } else if (escape in escapes) value += escapes[escape];
      else if (/[xuU]/.test(escape || "!")) {
        const size = escape === "x" ? 2 : escape === "u" ? 4 : 8;
        const digits = text.slice(index + 1, index + 1 + size);
        const point = Number.parseInt(digits, 16);
        if (digits.length !== size || /[^\da-f]/i.test(digits) || point > 0x10ffff) return "";
        value += String.fromCodePoint(point); index += size;
      } else return "";
    } else if (quote === "'" && character === "'" && text[index + 1] === "'") {
      value += "'"; index += 1;
    } else if (character === "\n" || /[ \t]/.test(character) && /^[ \t]*\n/.test(text.slice(index))) {
      let breaks = 0;
      while (index < text.length && /[ \t\n]/.test(text[index])) {
        if (text[index] === "\n") breaks += 1;
        index += 1;
      }
      value += breaks === 1 ? " " : "\n".repeat(breaks - 1); index -= 1;
    } else value += character;
  }
  return value;
}

function updateFrontMatter(body: string, key: string, value: string) {
  const { prefix, content } = frontMatter(body);
  if (!prefix) return body;
  const field = frontMatterField(prefix, key);
  const line = `${key}: ${JSON.stringify(value)}`;
  const ending = prefix.includes("\r\n") ? "\r\n" : "\n";
  const comment = /^[>|]/.test(field?.raw || "") ? field?.raw.split(/\r?\n/)[0].match(/[ \t]+#.*$/)?.[0] || "" : "";
  return (field ? prefix.slice(0, field.start) + JSON.stringify(value) + comment + prefix.slice(field.end)
    : prefix.replace(/---(\r?\n)?$/, (close) => line + ending + close)) + content;
}

function markdownBlocks(source: string): MarkdownToken[] {
  // Marked normalizes line endings and leading tabs. Map its blocks back to exact source slices.
  const offsets = [0];
  let normalized = "", indent: "spaces" | "tabs" | "done" = "spaces";
  for (let index = 0; index < source.length; index += 1) {
    let character = source[index];
    if (character === "\r") { if (source[index + 1] === "\n") index += 1; character = "\n"; }
    if (character === "\n") indent = "spaces";
    else if (character === "\t" && indent !== "done") { character = "    "; indent = "tabs"; }
    else if (character !== " " || indent === "tabs") indent = "done";
    normalized += character;
    for (let count = 0; count < character.length; count += 1) offsets.push(index + 1);
  }
  const result: MarkdownToken[] = [];
  let cursor = 0;
  for (const token of markdownParser.lexer(source)) {
    const start = normalized.indexOf(token.raw || "", cursor);
    if (start < 0) return [{ type: "paragraph", raw: source, text: source, tokens: [{ type: "text", text: source }] }];
    if (start > cursor) result.push({ type: "space", raw: source.slice(offsets[cursor], offsets[start]) });
    const end = start + (token.raw?.length || 0);
    result.push({ ...token, raw: source.slice(offsets[start], offsets[end]) });
    cursor = end;
  }
  if (cursor < normalized.length) result.push({ type: "space", raw: source.slice(offsets[cursor]) });
  return result;
}

function escapeMarkdown(text: string) {
  return text.replace(/&/g, "&amp;").replace(/\\/g, "\\\\").replace(/([`*_\[\]~<>])/g, "\\$1").replace(/^(\s*)([#>]|\d+\.)/gm, "$1\\$2");
}

/** Serialize only changed blocks. Untouched blocks keep their original Markdown bytes. */
function editedMarkdown(node: Node): string {
  if (node.nodeType === Node.TEXT_NODE) return escapeMarkdown(node.textContent || "");
  if (!(node instanceof HTMLElement)) return "";
  const inside = () => Array.from(node.childNodes).map(editedMarkdown).join("");
  const tag = node.tagName.toLowerCase();
  if (tag === "pre") {
    const text = node.textContent || "";
    const fence = "`".repeat(Math.max(3, ...Array.from(text.matchAll(/`+/g), (match) => match[0].length + 1)));
    return `${fence}\n${text.replace(/\n$/, "")}\n${fence}\n\n`;
  }
  if (tag === "code") {
    const text = node.textContent || "";
    const fence = "`".repeat(Math.max(1, ...Array.from(text.matchAll(/`+/g), (match) => match[0].length + 1)));
    const pad = /^[` ]|[` ]$/.test(text) ? " " : "";
    return `${fence}${pad}${text}${pad}${fence}`;
  }
  if (tag === "strong" || tag === "b") return `**${inside()}**`;
  if (tag === "em" || tag === "i") return `_${inside()}_`;
  if (tag === "del" || tag === "s" || tag === "strike") return `~~${inside()}~~`;
  if (/^h[1-6]$/.test(tag)) return `${"#".repeat(Number(tag[1]))} ${inside().trim()}\n\n`;
  if (tag === "p") return `${inside()}\n\n`;
  if (tag === "br") return "\n";
  if (tag === "hr") return "---\n\n";
  if (tag === "blockquote") return inside().trimEnd().split("\n").map((line) => `> ${line}`).join("\n") + "\n\n";
  if (tag === "a") {
    const href = safeLink(node.getAttribute("href") || "");
    return href ? `[${inside()}](<${href.replace(/>/g, "%3E")}>)` : inside();
  }
  if (tag === "input" && node instanceof HTMLInputElement && node.type === "checkbox") return node.checked ? "[x] " : "[ ] ";
  if (tag === "ul" || tag === "ol") {
    const start = Number(node.getAttribute("start")) || 1;
    return Array.from(node.children).map((item, index) => {
      const marker = tag === "ol" ? `${start + index}. ` : "- ";
      return marker + editedMarkdown(item).trim().replace(/\n/g, "\n" + " ".repeat(marker.length));
    }).join("\n") + "\n\n";
  }
  if (tag === "table") {
    const rows = Array.from(node.querySelectorAll("tr")).map((row) =>
      "| " + Array.from(row.children).map((cell) => editedMarkdown(cell).trim().replace(/\|/g, "\\|").replace(/\n/g, "<br>")).join(" | ") + " |");
    if (rows.length) rows.splice(1, 0, "| " + Array.from(node.querySelector("tr")!.children, () => "---").join(" | ") + " |");
    return rows.join("\n") + "\n\n";
  }
  return inside() + (tag === "div" && !node.classList.contains("intelligence-markdown-table") ? "\n" : "");
}

function EditableBlock({ token, index, disabled, onChange }: {
  token: MarkdownToken; index: number; disabled: boolean; onChange: (raw: string) => void;
}) {
  // React never replaces the browser's editing DOM while its caret or undo history is active.
  const [nodes] = useState(() => token.type === "heading"
    ? createElement(`h${token.depth || 2}`, null, markdownNodes(token.tokens || [])) : markdownNodes([token]));
  const baseline = useRef("");
  const root = useRef<HTMLDivElement>(null);
  useEffect(() => { if (root.current) baseline.current = Array.from(root.current.childNodes).map(editedMarkdown).join(""); }, []);
  function changed() {
    if (!root.current) return;
    let text = Array.from(root.current.childNodes).map(editedMarkdown).join("");
    if (text === baseline.current) { onChange(token.raw || ""); return; }
    const ending = token.raw?.match(/(?:\r?\n)+$/)?.[0] ?? "\n\n";
    if (token.type === "code") {
      const language = token.raw?.match(/^(?:`{3,}|~{3,})([^\r\n]*)/)?.[1] || "";
      text = text.replace(/^(`{3,})\n/, `$1${language}\n`);
    }
    onChange(text.replace(/\n+$/, "") + ending);
  }
  return <div ref={root} className="brain-edit-block intelligence-markdown" contentEditable={!disabled}
    suppressContentEditableWarning role="textbox" aria-multiline="true" aria-disabled={disabled}
    aria-label={`Markdown block ${index + 1}`} data-brain-block={index} onInput={changed}
    onPaste={(event) => {
      event.preventDefault();
      document.execCommand("insertText", false, event.clipboardData.getData("text/plain"));
      changed();
    }} onKeyDown={(event) => {
      if ((event.ctrlKey || event.metaKey) && ["b", "i"].includes(event.key.toLowerCase())) {
        event.preventDefault();
        document.execCommand(event.key.toLowerCase() === "b" ? "bold" : "italic"); changed();
      }
    }}>{nodes}</div>;
}

function FormattedEditor({ body, disabled, onChange }: { body: string; disabled: boolean; onChange: (body: string) => void }) {
  const editorRef = useRef<HTMLDivElement>(null);
  const selectionRef = useRef<Range | null>(null);
  const [initial] = useState(() => {
    const { content } = frontMatter(body);
    const tokens = markdownBlocks(content);
    if (!tokens.some((token) => token.type !== "space")) tokens.push({ type: "paragraph", text: "", raw: "", tokens: [] });
    return { tokens };
  });
  const parts = useRef(initial.tokens.map((token) => token.raw || ""));
  function format(command: string) {
    const range = selectionRef.current;
    if (!range || !editorRef.current?.contains(range.commonAncestorContainer)) return;
    const selection = window.getSelection();
    const element = range.startContainer instanceof HTMLElement ? range.startContainer : range.startContainer.parentElement;
    const block = element?.closest<HTMLElement>('[contenteditable="true"]');
    block?.focus();
    selection?.removeAllRanges(); selection?.addRange(range);
    document.execCommand(command);
    block?.dispatchEvent(new Event("input", { bubbles: true }));
  }
  return <div ref={editorRef} className="brain-formatted-editor" data-testid="brain-formatted-editor"
    onBlurCapture={() => {
      const selection = window.getSelection();
      if (selection?.rangeCount && editorRef.current?.contains(selection.anchorNode)) selectionRef.current = selection.getRangeAt(0).cloneRange();
    }}>
    <div className="brain-format-tools" role="group" aria-label="Text format">
      <button type="button" className="intelligence-button" disabled={disabled} title="Ctrl or Command B" onClick={() => format("bold")}>Bold</button>
      <button type="button" className="intelligence-button" disabled={disabled} title="Ctrl or Command I" onClick={() => format("italic")}>Italic</button>
    </div>
    {initial.tokens.map((token, index) => token.type === "space" ? null : <EditableBlock key={index}
      token={token} index={index} disabled={disabled} onChange={(raw) => {
        parts.current[index] = raw;
        onChange(frontMatter(body).prefix + parts.current.join(""));
      }} />)}
  </div>;
}

export function unsavedChangeCount(before: string, after: string) {
  if (before === after) return 0;
  const a = before.split("\n"), b = after.split("\n");
  let start = 0, end = 0;
  while (start < Math.min(a.length, b.length) && a[start] === b[start]) start += 1;
  while (end < Math.min(a.length, b.length) - start && a[a.length - end - 1] === b[b.length - end - 1]) end += 1;
  return Math.max(a.length, b.length) - start - end;
}

export function BrainMarkdownEditor({ body, originalBody, onChange, title, description, disabled = false, readOnly = false }: {
  body: string; originalBody?: string; onChange?: (body: string) => void; title?: string; description?: string; disabled?: boolean; readOnly?: boolean;
}) {
  const [source, setSource] = useState(false);
  const sourceId = useId();
  const sourceRef = useRef<HTMLTextAreaElement>(null);
  const editorRef = useRef<HTMLDivElement>(null);
  const numbersRef = useRef<HTMLDivElement>(null);
  const lines = body.split("\n");
  const { prefix } = frontMatter(body);
  const originalPrefix = originalBody === undefined ? undefined : frontMatter(originalBody).prefix;
  const name = frontMatterValue(prefix, "title", title ?? "Untitled", originalPrefix);
  const summary = frontMatterValue(prefix, "description", description, originalPrefix);
  useEffect(() => {
    if (readOnly) return;
    if (source) sourceRef.current?.focus();
    else editorRef.current?.querySelector<HTMLElement>('[contenteditable="true"]')?.focus();
  }, [source, readOnly]);
  return <div ref={editorRef} className="brain-editor" data-testid="brain-editor" data-source={source}>
    <div className="brain-editor-head">
      <button type="button" className="intelligence-button brain-source-toggle" aria-pressed={source}
        aria-controls={sourceId} disabled={disabled} onClick={() => setSource((value) => !value)}>Source</button>
    </div>
    {source ? <div id={sourceId} className="brain-source" data-testid="brain-source">
      {readOnly ? <pre className="brain-source-read">{lines.map((line, index) => <span className="brain-source-line" key={index}>
        <span className="brain-line-number" aria-hidden="true">{index + 1}</span><span>{line || "\n"}</span>
      </span>)}</pre> : <>
        <div ref={numbersRef} className="brain-source-numbers" aria-hidden="true">{lines.map((_, index) => <div key={index}>{index + 1}</div>)}</div>
        <textarea ref={sourceRef} className="brain-source-input" aria-label="Markdown source" spellCheck={false}
          wrap="off" value={body} disabled={disabled} rows={16} onChange={(event) => onChange?.(event.target.value)}
          onScroll={(event) => { if (numbersRef.current) numbersRef.current.scrollTop = event.currentTarget.scrollTop; }} />
      </>}
    </div> : <div id={sourceId} className="brain-formatted">
      {prefix ? <table className="brain-frontmatter" aria-label="Front matter"><tbody>
        <tr><th scope="row">Name</th><td>{readOnly ? name : <input aria-label="File name" value={name} disabled={disabled}
          onChange={(event) => onChange?.(updateFrontMatter(body, "title", event.target.value))} />}</td></tr>
        <tr><th scope="row">Description</th><td>{readOnly ? summary || "No description" : <textarea aria-label="File description"
          rows={2} value={summary} disabled={disabled} onChange={(event) => onChange?.(updateFrontMatter(body, "description", event.target.value))} />}</td></tr>
      </tbody></table> : null}
      {readOnly ? <FileMarkdown body={body} /> : <FormattedEditor body={body} disabled={disabled} onChange={(value) => onChange?.(value)} />}
    </div>}
  </div>;
}

export default function FileView({ path, api, onClose, initialHistory = false, onChanged }: {
  path: string; api: IntelligenceApi; onClose: () => void; initialHistory?: boolean; onChanged?: () => void;
}) {
  const backRef = useRef<HTMLButtonElement>(null);
  const titleId = useId();
  const [file, setFile] = useState<IntelligenceFile | null>(null);
  const [problem, setProblem] = useState("");
  const [missingFile, setMissingFile] = useState(false);
  const [loading, setLoading] = useState(true);
  const [retry, setRetry] = useState(0);
  const [showHistory, setShowHistory] = useState(initialHistory);
  const [restoreBusy, setRestoreBusy] = useState(false);
  const restoring = useRef(false);
  const readRequest = useRef<AbortController | null>(null);
  const noteEditorRef = useRef<HTMLTextAreaElement>(null);
  const saveRequest = useRef<AbortController | null>(null);
  const [draft, setDraft] = useState<{ body: string; version: number } | null>(null);
  const [saveBusy, setSaveBusy] = useState(false);
  const [saveProblem, setSaveProblem] = useState("");
  const [saveConflict, setSaveConflict] = useState(false);
  const [saved, setSaved] = useState(false);
  const [proposed, setProposed] = useState(false);
  const [proposalRevision, setProposalRevision] = useState(0);
  const [admission, setAdmission] = useState<{
    api: IntelligenceApi; path: string; retry: number; proposal: IntelligenceProposal | null;
  } | null>(null);
  const onProposalsLoaded = useCallback((rows: IntelligenceProposal[] | null) => {
    setAdmission({ api, path, retry, proposal: rows?.find((row) => row.path === path
      && row.baseVersion === 0 && row.status !== "approved") || null });
  }, [api, path, retry]);
  const newProposal = admission?.api === api && admission.path === path && admission.retry === retry
    ? admission.proposal : null;
  const databaseNote = path.startsWith("database-notes/") || file?.section === "database-notes";
  const generatedWiki = /^wiki\/(log|index)\//i.test(path);
  const purposeFile = /^wiki\/purposes\//i.test(path);
  const ownerOnly = databaseNote || purposeFile;
  const editing = draft !== null;
  const viewingHistory = showHistory && !databaseNote;
  // A file is a page: focus lands on Back, the control that returns to the folder.
  useEffect(() => { backRef.current?.focus({ preventScroll: true }); }, []);
  useEffect(() => {
    const abort = new AbortController();
    readRequest.current = abort;
    setLoading(true); setProblem(""); setMissingFile(false); setFile(null);
    setDraft(null); setSaveBusy(false); setSaveProblem(""); setSaveConflict(false); setSaved(false); setProposed(false);
    void api.readFile(path, abort.signal).then((value) => {
      if (!abort.signal.aborted) setFile(value);
    }).catch((error: unknown) => {
      if (!abort.signal.aborted) {
        setMissingFile(error instanceof IntelligenceApiError && error.status === 404 && error.code === "no_file");
        setProblem(intelligenceProblem(error, "This file could not be read. Try again."));
      }
    }).finally(() => { if (!abort.signal.aborted) setLoading(false); });
    return () => { abort.abort(); saveRequest.current?.abort(); saveRequest.current = null; };
  }, [api, path, retry]);
  useEffect(() => { if (editing) noteEditorRef.current?.focus(); }, [editing]);

  function acceptFile(value: IntelligenceFile) {
    readRequest.current?.abort();
    setFile(value); setProblem(""); setMissingFile(false); setLoading(false); onChanged?.();
  }

  async function saveEdit(event: FormEvent) {
    event.preventDefault();
    if (!draft || !file || generatedWiki || (ownerOnly && file.canEdit !== true) || !api.saveFile || saveRequest.current || saveConflict
      || draft.body === file.body) return;
    if (new TextEncoder().encode(draft.body).length > BRAIN_MAX_BODY_BYTES) {
      setSaveProblem(BRAIN_BODY_LIMIT_MESSAGE); return;
    }
    const abort = new AbortController();
    saveRequest.current = abort;
    setSaveBusy(true); setSaveProblem(""); setSaved(false);
    try {
      const value = await api.saveFile(path, draft.body, draft.version, abort.signal);
      if (abort.signal.aborted || saveRequest.current !== abort) return;
      if ("proposal" in value) {
        setFile((current) => current ? { ...current, canEdit: false } : null);
        setDraft(null); setProposed(true); setProposalRevision((revision) => revision + 1); onChanged?.();
      } else { acceptFile(value); setDraft(null); setSaved(true); }
    } catch (error) {
      if (abort.signal.aborted || saveRequest.current !== abort) return;
      const conflict = error instanceof IntelligenceApiError && error.code === "version_conflict";
      setSaveConflict(conflict);
      setSaveProblem(conflict ? "The file changed. Reload before editing." : intelligenceProblem(error, "The file could not be saved. Try again."));
    } finally {
      if (!abort.signal.aborted && saveRequest.current === abort) { saveRequest.current = null; setSaveBusy(false); }
    }
  }

  function cancelEdit() {
    setDraft(null); setSaveProblem(""); setSaved(false);
    if (saveConflict) setRetry((value) => value + 1);
    setSaveConflict(false);
  }

  function startEdit() {
    if (!file || generatedWiki || typeof file.canEdit !== "boolean" || (ownerOnly && file.canEdit !== true)) return;
    setDraft({ body: file.body, version: file.version }); setSaveProblem(""); setSaved(false); setProposed(false);
  }

  return <section className="intelligence-file-page" aria-labelledby={titleId}
      data-testid="intelligence-file" aria-busy={loading || saveBusy}>
      <header className="home-section-head intelligence-file-head">
        <button ref={backRef} type="button" className="cg-btn" data-file-close aria-label="Back" title="Back"
          disabled={restoreBusy || saveBusy} onClick={onClose}>
          <svg viewBox="0 0 16 16" aria-hidden="true" className="home-layout-icon" fill="none" stroke="currentColor">
            <path d="M10 3 5 8l5 5" />
          </svg>
        </button>
        <h1 id={titleId} className="home-title">{file?.title || newProposal?.title || "File"}</h1>
      </header>
      {loading ? <div className="intelligence-skeleton" role="status" aria-label="Loading file"><span /><span /><span /></div> : null}
      {problem && !(missingFile && newProposal) ? <div className="intelligence-feedback" role="alert"><span>{problem}</span>
        <button type="button" className="intelligence-button" onClick={() => setRetry((value) => value + 1)}>Retry</button></div> : null}
      {!databaseNote ? <div className="intelligence-view-switch" role="group" aria-label="File view">
        <button type="button" className="intelligence-button" disabled={restoreBusy || editing} aria-pressed={!showHistory} onClick={() => setShowHistory(false)}>File</button>
        <button type="button" className="intelligence-button" disabled={restoreBusy || editing} aria-pressed={showHistory} onClick={() => setShowHistory(true)}>History</button>
        {!generatedWiki && file?.canEdit === true && api.saveFile && !editing && !showHistory ? <button type="button"
          className="intelligence-button" data-brain-edit onClick={startEdit}>Edit</button> : null}
        {!generatedWiki && !purposeFile && file?.canEdit === false && api.saveFile && !editing && !showHistory ? <button type="button"
          className="intelligence-button" data-brain-propose onClick={startEdit}>Propose change</button> : null}
      </div> : null}
      {viewingHistory ? <History path={path} api={api} revision={file?.version || 0}
        onBusy={(busy) => { restoring.current = busy; setRestoreBusy(busy); }}
        onRestored={acceptFile} /> : <>
      <Proposals key={`${path}/${proposalRevision}`} path={path} api={api} onApproved={acceptFile} onLoaded={onProposalsLoaded} />
      {file ? <>
        {databaseNote ? <div className="intelligence-view-switch" role="group" aria-label="Database note">
          {file.databaseKey ? <a className="intelligence-button" href={`#/data?database=${encodeURIComponent(file.databaseKey)}`}>Open database</a> : null}
          {file.canEdit === true && api.saveFile && !editing ? <button type="button" className="intelligence-button"
            onClick={startEdit}>Edit</button> : null}
        </div> : null}
        {draft ? <form className="intelligence-create brain-edit-form" aria-busy={saveBusy} onSubmit={(event) => void saveEdit(event)}>
          {databaseNote ? <label>Note<textarea ref={noteEditorRef} value={draft.body} disabled={saveBusy} rows={12}
            onChange={(event) => { const body = event.target.value; setDraft((current) => current ? { ...current, body } : null); }} /></label>
            : <BrainMarkdownEditor body={draft.body} originalBody={file.body} title={file.metadata?.title ?? file.title}
              description={file.metadata?.description ?? file.description}
              disabled={saveBusy} onChange={(body) => setDraft((current) => current ? { ...current, body } : null)} />}
          {saveProblem ? <div className="intelligence-feedback" role="alert"><span>{saveProblem}</span>
            <button className="intelligence-button" type="button" disabled={saveBusy} onClick={() => setRetry((value) => value + 1)}>Reload</button></div> : null}
          <div className="intelligence-create-actions brain-editor-foot">
            {!databaseNote ? <span className="brain-unsaved" role="status" data-testid="brain-unsaved"
              title="Source lines in the changed range">{unsavedChangeCount(file.body, draft.body)} unsaved {unsavedChangeCount(file.body, draft.body) === 1 ? "change" : "changes"}</span> : null}
            <button className="intelligence-button" type="button" disabled={saveBusy} onClick={cancelEdit}>Cancel</button>
            <button className="intelligence-button intelligence-primary" type="submit"
              disabled={saveBusy || saveConflict || generatedWiki || (ownerOnly && file.canEdit !== true) || !api.saveFile || draft.body === file.body}>
              {saveBusy ? "Saving…" : file.canEdit === false ? "Propose change" : "Save"}</button>
          </div>
        </form> : databaseNote ? <FileMarkdown body={file.body} preserveFrontmatter /> : file.section === "agent-prompts"
        ? <PromptView tools={file.resolvedTools || []}><BrainMarkdownEditor body={file.body} originalBody={file.body}
            title={file.metadata?.title ?? file.title} description={file.metadata?.description ?? file.description} readOnly /></PromptView>
        : <BrainMarkdownEditor body={file.body} originalBody={file.body} title={file.metadata?.title ?? file.title}
            description={file.metadata?.description ?? file.description} readOnly />}
        {saved ? <p className="intelligence-meta" role="status">Saved.</p> : null}
        {proposed ? <p className="intelligence-meta" role="status">Change proposed for approval.</p> : null}
        <footer className="intelligence-file-by" data-testid="intelligence-version">
          {databaseNote ? <div>History is in Notes</div> : null}
          <div>Version {file.version} · Last changed by {file.author}{file.onBehalfOf ? ` for ${file.onBehalfOf}` : ""}</div>
          {file.approvedBy?.length ? <div>Approved by {file.approvedBy.join(", ")}</div> : null}
          {file.restoredFrom ? <div>Restored from version {file.restoredFrom}</div> : null}
          <time dateTime={file.updated}>{fileDate(file.updated)}</time>
        </footer>
      </> : null}</>}
    </section>;
}