File size: 111,788 Bytes
5b48487
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
# ===== file: src/accessibility-semantics.ts =====
// Read-only accessibility semantics: defines color roles, reduced-color
// fallbacks, and reduced-motion preferences for activity rendering.
//
// Color roles expose semantic name, full-color value, reduced-color
// fallback (symbol/glyph), and contrast ratio. Reduced-motion preferences
// disable animation hints. The model supports screen-reader label
// generation. The view is read-only and never renders actual UI, executes
// commands, or modifies preferences.

export const ACCESSIBILITY_SEMANTICS_SCHEMA = "oh-my-cli.accessibility-semantics";
export const ACCESSIBILITY_SEMANTICS_VERSION = 1;

// --- types ------------------------------------------------------------------

export type ColorRole =
  | "status-running"
  | "status-success"
  | "status-failure"
  | "status-waiting"
  | "emphasis"
  | "warning"
  | "error"
  | "muted";

export interface ColorDefinition {
  role: ColorRole;
  /** Semantic meaning description. */
  meaning: string;
  /** Full-color hex value. */
  fullColor: string;
  /** Reduced-color fallback glyph/symbol. */
  reducedGlyph: string;
  /** WCAG contrast ratio against the background (approximate). */
  contrastRatio: number;
  /** Screen-reader label. */
  screenReaderLabel: string;
}

export interface MotionPreference {
  /** Whether animations are enabled. */
  animationsEnabled: boolean;
  /** Static alternative for spinner/progress. */
  staticSpinner: string;
  /** Static alternative for progress bar. */
  staticProgress: string;
}

export interface AccessibilityProfile {
  /** Whether reduced-color mode is active. */
  reducedColor: boolean;
  /** Whether reduced-motion mode is active. */
  reducedMotion: boolean;
  /** Color definitions. */
  colors: ColorDefinition[];
  /** Motion preferences. */
  motion: MotionPreference;
}

// --- default definitions ----------------------------------------------------

const DEFAULT_COLORS: ColorDefinition[] = [
  { role: "status-running", meaning: "Active/running process", fullColor: "#3B82F6", reducedGlyph: "▶", contrastRatio: 4.5, screenReaderLabel: "Running" },
  { role: "status-success", meaning: "Successful completion", fullColor: "#22C55E", reducedGlyph: "✓", contrastRatio: 4.6, screenReaderLabel: "Succeeded" },
  { role: "status-failure", meaning: "Failed operation", fullColor: "#EF4444", reducedGlyph: "✗", contrastRatio: 4.5, screenReaderLabel: "Failed" },
  { role: "status-waiting", meaning: "Waiting for input or dependency", fullColor: "#F59E0B", reducedGlyph: "○", contrastRatio: 4.5, screenReaderLabel: "Waiting" },
  { role: "emphasis", meaning: "Emphasized content", fullColor: "#8B5CF6", reducedGlyph: "★", contrastRatio: 4.6, screenReaderLabel: "Emphasis" },
  { role: "warning", meaning: "Warning condition", fullColor: "#F97316", reducedGlyph: "⚠", contrastRatio: 4.5, screenReaderLabel: "Warning" },
  { role: "error", meaning: "Error condition", fullColor: "#DC2626", reducedGlyph: "⛔", contrastRatio: 5.0, screenReaderLabel: "Error" },
  { role: "muted", meaning: "De-emphasized content", fullColor: "#6B7280", reducedGlyph: "·", contrastRatio: 4.5, screenReaderLabel: "Muted" },
];

const DEFAULT_MOTION: MotionPreference = {
  animationsEnabled: true,
  staticSpinner: "[working]",
  staticProgress: "[=====>    ]",
};

const REDUCED_MOTION: MotionPreference = {
  animationsEnabled: false,
  staticSpinner: "[working]",
  staticProgress: "[=====>    ]",
};

// --- profile builder --------------------------------------------------------

export function buildAccessibilityProfile(opts: {
  reducedColor?: boolean;
  reducedMotion?: boolean;
} = {}): AccessibilityProfile {
  return {
    reducedColor: opts.reducedColor ?? false,
    reducedMotion: opts.reducedMotion ?? false,
    colors: DEFAULT_COLORS,
    motion: opts.reducedMotion ? REDUCED_MOTION : DEFAULT_MOTION,
  };
}

// --- rendering helpers (pure, no actual UI) ---------------------------------

// Render a status indicator for a given role, respecting the profile.
export function renderStatusIndicator(role: ColorRole, profile: AccessibilityProfile): string {
  const color = profile.colors.find((c) => c.role === role);
  if (!color) return "?";

  if (profile.reducedColor) {
    return color.reducedGlyph;
  }
  return `${color.reducedGlyph}`; // In a real TUI, this would use ANSI colors.
}

// Generate a screen-reader label for an activity state.
export function screenReaderLabel(role: ColorRole, detail: string, profile: AccessibilityProfile): string {
  const color = profile.colors.find((c) => c.role === role);
  const label = color?.screenReaderLabel ?? role;
  return `${label}: ${detail}`;
}

// Render a spinner/progress respecting motion preferences.
export function renderProgress(pct: number, profile: AccessibilityProfile): string {
  if (!profile.motion.animationsEnabled) {
    return profile.motion.staticProgress;
  }
  const width = 20;
  // Issue #808: clamp the fill into [0, width] so an out-of-range pct
  // (over-100 or negative) renders a clamped bar instead of throwing a
  // RangeError from a negative repeat count. In-range output is unchanged.
  const filled = Math.max(0, Math.min(width, Math.round((pct / 100) * width)));
  return `[${"=".repeat(filled)}>${" ".repeat(width - filled)}]`;
}

// --- formatting -------------------------------------------------------------

export function formatAccessibilityProfile(profile: AccessibilityProfile): string {
  const lines: string[] = [];
  lines.push("Accessibility Semantics");
  lines.push("═".repeat(50));
  lines.push(`Reduced color: ${profile.reducedColor ? "YES" : "no"}  Reduced motion: ${profile.reducedMotion ? "YES" : "no"}`);

  lines.push("");
  lines.push("Color roles:");
  for (const color of profile.colors) {
    const display = profile.reducedColor ? color.reducedGlyph : `${color.reducedGlyph} (${color.fullColor})`;
    lines.push(`  ${display} ${color.role} — ${color.meaning} [${color.contrastRatio}:1] "${color.screenReaderLabel}"`);
  }

  lines.push("");
  lines.push(`Motion: animations ${profile.motion.animationsEnabled ? "enabled" : "disabled"}`);
  lines.push(`  Spinner: ${profile.motion.staticSpinner}`);
  lines.push(`  Progress: ${profile.motion.staticProgress}`);

  lines.push("");
  lines.push("Read-only: no UI rendered, no preferences modified.");

  return lines.join("\n");
}

# ===== file: src/activity-render.ts =====
// Activity rendering: render the #306 presented activity event stream as
// progressive-disclosure cards for the mission-control TUI view (Issue #307, the
// TUI activity-rendering child of #291). Each card shows a status glyph, the
// event kind, its summary, elapsed time, and a liveness marker; expanding a card
// reveals its bounded detail. The rendering is a pure function of the presented
// events plus a small view state (which cards are expanded, follow-mode, and an
// unread count), so the same events and view state always render the same view,
// and expanding/collapsing never loses the underlying events.
//
// This module returns plain text lines (no ANSI); the TUI panel in tui-shell.ts
// applies color/style around them, exactly as the mission lifecycle (#314) and
// background-task panels style their bodies. Keeping rendering pure and
// style-free makes it unit-testable against fixture event streams and reusable by
// the Desktop canvas (#318). Reduced-color/no-color degrades to the glyphs and
// plain text without losing information.
//
// Trust boundary: the rendering reads only already-presented events (sanitized by
// the #306 mapper); it executes nothing and adds no untrusted content.

import type { PresentedEvent, EventStatus } from "./event-presentation.js";

// A stable glyph per activity status, so a card communicates status at a glance
// without relying on color alone.
const STATUS_GLYPHS: Record<EventStatus, string> = {
  pending: "○",
  active: "◆",
  completed: "✓",
  failed: "✕",
  waiting: "◇",
  cancelled: "⊘",
};

export function activityGlyph(status: EventStatus): string {
  return STATUS_GLYPHS[status] ?? "?";
}

// Compact human elapsed time: seconds under a minute, minutes under an hour,
// hours otherwise.
export function formatElapsed(ms: number): string {
  const seconds = Math.max(0, Math.floor(ms / 1000));
  if (seconds >= 3600) return `${Math.floor(seconds / 3600)}h`;
  if (seconds >= 60) return `${Math.floor(seconds / 60)}m`;
  return `${seconds}s`;
}

// A liveness marker: a filled dot while the event is live, blank otherwise.
export function livenessMarker(live: boolean): string {
  return live ? "●" : "·";
}

// Render one activity card. Collapsed shows a single summary line; expanded adds
// the bounded detail (with a truncation note when the #306 mapper bounded it).
export function renderActivityCard(event: PresentedEvent, expanded: boolean): string[] {
  const summary = event.summary || event.kind;
  const head = `${activityGlyph(event.status)} ${event.kind} · ${summary} · ${formatElapsed(
    event.elapsedMs,
  )} ${livenessMarker(event.live)} ${event.status}`;
  if (!expanded) return [head];
  const detail = event.detail === "" ? ["  (no detail)"] : event.detail.split("\n").map((l) => `  ${l}`);
  const truncated = event.detailTruncated ? ["  … (detail truncated)"] : [];
  return [head, ...detail, ...truncated];
}

// The activity view state: which card indices are expanded, whether follow-mode
// is on (auto-track the latest event), and how many events arrived since the view
// was last read. Immutable; transitions return new states.
export interface ActivityViewState {
  expanded: ReadonlySet<number>;
  followMode: boolean;
  unread: number;
}

export function initialActivityViewState(): ActivityViewState {
  return { expanded: new Set<number>(), followMode: true, unread: 0 };
}

// Toggle whether one card index is expanded.
export function toggleExpand(state: ActivityViewState, index: number): ActivityViewState {
  const expanded = new Set(state.expanded);
  if (expanded.has(index)) expanded.delete(index);
  else expanded.add(index);
  return { ...state, expanded };
}

// Expand every card (when count > 0 and not all already expanded) or collapse all
// otherwise — a simple toggle-all for the panel's expand/collapse gesture.
export function toggleExpandAll(state: ActivityViewState, count: number): ActivityViewState {
  const allExpanded = count > 0 && state.expanded.size >= count;
  const expanded = allExpanded ? new Set<number>() : new Set<number>(Array.from({ length: count }, (_, i) => i));
  return { ...state, expanded };
}

export function setFollowMode(state: ActivityViewState, on: boolean): ActivityViewState {
  return { ...state, followMode: on };
}

export function markRead(state: ActivityViewState): ActivityViewState {
  return { ...state, unread: 0 };
}

export function bumpUnread(state: ActivityViewState, n: number): ActivityViewState {
  return { ...state, unread: state.unread + Math.max(0, Math.floor(n)) };
}

// Render the whole activity stream as progressive-disclosure cards (in event
// order), expanding the cards whose indices are in the view state. Empty stream
// renders a single placeholder line.
export function renderActivityStream(
  events: readonly PresentedEvent[],
  state: ActivityViewState,
): string[] {
  if (events.length === 0) return ["(no activity)"];
  const lines: string[] = [];
  events.forEach((event, index) => {
    lines.push(...renderActivityCard(event, state.expanded.has(index)));
  });
  return lines;
}

// Render the full read-only activity view: a header (counts + follow-mode +
// unread), the card stream, and a hint line. Pure and deterministic.
export function formatActivityView(
  events: readonly PresentedEvent[],
  state: ActivityViewState,
): string[] {
  const active = events.filter((e) => e.live).length;
  const header =
    `Activity (read-only) · events ${events.length} · live ${active} · ` +
    `follow ${state.followMode ? "on" : "off"} · unread ${state.unread}`;
  return [header, "", ...renderActivityStream(events, state)];
}

# ===== file: src/agent.ts =====
import type { Config } from "./config.js";
import type { SessionMessage } from "./session.js";
import type { ToolDef, ToolResult, ShellFailureDetail } from "./tools.js";
import { createTools, toolSchemasForOpenAI } from "./tools.js";
import {
  streamChat,
  backoffDelayMs,
  RETRY_MAX_ATTEMPTS,
  isQuotaExhausted,
  quotaExhaustedGuidance,
  classifyTransient,
} from "./provider.js";
import type { StreamProvider } from "./provider.js";
import { redactEndpointHost } from "./permission-impact.js";
import type { Workspace } from "./workspace.js";
import type { ApprovalMode } from "./approval.js";
import { needsApproval, promptApproval } from "./approval.js";
import { evaluateCommandPolicy, policyDenialMessage } from "./command-policy.js";
import { evaluatePreToolUseHooks, type PreToolUseHook } from "./hook-contract.js";
import { folderTrustDenialMessage } from "./folder-trust.js";
import { estimateCostUsd, lookupModelPrice, formatCostUsd } from "./cost.js";
import { computeMessageTiming, formatMessageUsageLine } from "./message-usage.js";
import { buildEffectiveSystemPrompt, composeAppendedSystemPrompt } from "./instruction-context.js";
import { promptWithTextAttachments } from "./text-attachment.js";
import type { LoadedTextAttachment } from "./text-attachment.js";
import { compactMessages, buildCompactedTranscript } from "./compaction.js";
import type { LoadedImage } from "./image-input.js";
import type { TurnImageCollector } from "./turn-checkpoint.js";
import type { BottleneckCollector } from "./run-bottleneck.js";
import type { FailureTaxonomyCollector } from "./run-failure-taxonomy.js";

const MAX_ROUNDS = 30;

// Transcript content for a tool call cancelled before execution (Issue #550).
// A bounded, secret-free placeholder that keeps the transcript resume-valid:
// every tool_call_id keeps exactly one tool message. session-stats derives
// deterministic cancellation counts by matching this exact content.
export const CANCELLED_TOOL_CONTENT = "[cancelled: turn cancelled before this tool ran]";

// Bounded wait between empty-completion recovery attempts (#244). Mirrors the
// provider's own bounded backoff so an unattended run can never loop or overspend
// indefinitely waiting for a non-empty answer.
function sleep(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

export interface AgentOptions {
  config: Config;
  workspace: Workspace;
  approvalMode: ApprovalMode;
  sessionId: string;
  onMessage: (msg: SessionMessage) => void;
  sink?: AgentSink;
  // Optional spend budget in USD. When the running cost estimate reaches this
  // cap, the loop stops before issuing further provider calls. Null disables it.
  budgetUsd?: number | null;
  // Optional operator turn cap (Issue #515). When set, the loop stops before
  // the (n+1)th provider round at the round boundary — never mid-tool-call and
  // never mid-stream. Null disables it.
  maxTurns?: number | null;
  // Optional operator wall-time cap in milliseconds (Issue #515). When set, the
  // loop stops the first round that would start at or after this much wall
  // time has elapsed since the run began — at the round boundary only. Null
  // disables it.
  maxWallTimeMs?: number | null;
  // Optional operator tool-call cap (Issue #517). When set, the loop stops at
  // the first round boundary after the cumulative processed tool-call count
  // reaches it — every tool call the round emitted already has its result, so
  // the transcript stays complete. Null disables it.
  maxToolCalls?: number | null;
  // Run-scoped user instructions (Issue #789): appended as a labeled section
  // after the built-in system prompt when a fresh session is seeded here.
  // Validated at the dispatch boundary (bounded, non-empty, fresh sessions
  // only); the agent trusts what it receives. Undefined disables it.
  appendSystemPrompt?: string;
  // Folder-trust enforcement. When false, every mutating tool (file or shell)
  // fails closed before approval is even considered, regardless of approvalMode
  // (so yolo cannot widen the boundary). Defaults to true (no enforcement) so
  // callers that do not opt in keep the existing behaviour.
  mutatingAllowed?: boolean;
  // Context-pressure threshold in tokens. When the most recent provider call's
  // prompt size reaches this, the in-memory transcript is compacted before the
  // next provider call (the on-disk transcript is untouched). Undefined or <= 0
  // disables auto-compaction.
  compactThreshold?: number;
  // Image attachments for the initial user prompt. They are sent to the provider
  // as multimodal content parts; only a non-secret reference is persisted (the
  // data URL never reaches the session log).
  images?: LoadedImage[];
  // Text-file attachments for the initial user prompt (Issue #797): pinned
  // verbatim into the next user message as delimited, path-labeled sections.
  // One-shot: the surface consumes its pending attachments when the turn
  // submits.
  textAttachments?: LoadedTextAttachment[];
  // Optional collector for safe turn undo/redo. When present, the pre-image of
  // each file a mutating-file tool touches is captured before the tool runs, so
  // the turn's workspace mutations can later be reversed without a Git reset.
  turnImages?: TurnImageCollector;
  // User-owned PreToolUse hooks (resolved from the user settings scope by the
  // caller). Each matching hook runs as a deny-only gate before a tool executes;
  // a hook can only block a call, never approve it. Empty/undefined ⇒ no hooks.
  preToolUseHooks?: readonly PreToolUseHook[];
  // Optional wall-time bottleneck collector. When present, the loop records each
  // tool's execution wall-time and each approval gate's wait wall-time so the
  // caller can build a privacy-safe bottleneck report. Undefined ⇒ no collection.
  bottleneck?: BottleneckCollector;
  // Optional failure-taxonomy collector. When present, the loop records the cause
  // of each failed tool call (policy/hook/approval denial, path escape, tool
  // error, unknown tool, folder-trust denial) so the caller can build a
  // privacy-safe failure-taxonomy report. Undefined ⇒ no collection.
  failureTaxonomy?: FailureTaxonomyCollector;
  // Optional shell failure receipt sink (Issue #574). When present, every
  // non-zero/killed/timed-out shell execution reports its structured failure
  // descriptor so the caller can persist a bounded, redacted receipt. The sink
  // is best-effort: a recording failure never changes tool results, approval
  // behavior, or turn outcomes. Undefined ⇒ no capture.
  onShellFailure?: (detail: ShellFailureDetail) => void;
  // Optional provider stream override. Defaults to the network `streamChat`;
  // the deterministic task-fixture replay (#224) supplies a scripted provider so
  // the same fixture always produces the same run. Undefined ⇒ network provider.
  streamProvider?: StreamProvider;
  // Read-only mode (#234): restrict the run to read-only tools and refuse any
  // mutating tool fail-closed, regardless of approval mode or folder trust, so
  // parallel investigators can safely share one workspace. Defaults to false.
  readOnly?: boolean;
  // Injectable wall-clock for per-message timing (TTFT / tok/s). Defaults to
  // Date.now; tests supply a deterministic clock so responsiveness metrics are
  // reproducible. Undefined ⇒ Date.now.
  now?: () => number;
  // Injectable wall-time clock for the operator wall-time cap (Issue #515).
  // Deliberately distinct from `now` (per-message timing) so capping a run
  // never shifts TTFT clock sequences. Defaults to Date.now. Undefined ⇒
  // Date.now.
  runClock?: () => number;
  // One-shot fallback model (Issue #590). When set and the primary model's
  // request fails with a retryable (transient) provider error BEFORE producing
  // any output, the run degrades at most once to this model for the remainder
  // of the run; a subsequent failure never re-degrades. Null/undefined
  // disables fallback entirely and keeps existing behavior. Callers driving a
  // scripted provider (task-fixture replay) must never set this — a scripted
  // run cannot degrade truthfully.
  fallbackModel?: string | null;
  // Cooperative cancellation (#489). Polled before the first provider call, at
  // every round boundary, and between streamed events. When it returns true the
  // loop stops as soon as the current event is handled: any streamed assistant
  // text is persisted as one interrupted turn (never lost, never reported as a
  // completed answer) and the run ends with reason "cancelled". Undefined ⇒ the
  // run cannot be cancelled.
  cancelRequested?: () => boolean;
  // Retry support (#489). When false the run does NOT create or persist a user
  // message — the caller has already persisted the turn's user message and it is
  // present in existingMessages, so a retry reuses one request identity instead
  // of duplicating the user turn. Defaults to true. Attachments belong to the
  // original turn and are never re-attached on retry.
  appendUserMessage?: boolean;
}

// Cumulative usage and cost reported after each round. `estimatedCostUsd` is an
// estimate (never authoritative billing); `costKnown` reports whether the model
// price was found in the bundled table. `budgetReached` is true once the running
// estimate has met or exceeded `budgetUsd`.
export interface AgentUsage {
  round: number;
  tokens: { prompt: number; completion: number; total: number };
  estimatedCostUsd: number;
  costKnown: boolean;
  budgetUsd: number | null;
  budgetReached: boolean;
  // Per-message responsiveness for this turn (#241): time-to-first-token and
  // output throughput. Null when the provider did not stream text tokens or did
  // not report usage/timing — omitted downstream rather than guessed.
  ttftMs: number | null;
  tokensPerSecond: number | null;
}

// A transient provider failure is being retried within a round. Metadata only —
// which attempt, the transient reason class, and the scheduled wait — so a
// consumer can observe resilience without seeing error text or secrets.
export interface AgentRetry {
  round: number;
  attempt: number;
  maxAttempts: number;
  reasonClass: string;
  delayMs: number;
}

// The in-memory transcript was compacted to relieve context pressure. Metadata
// only — how many messages were summarized and how many completed-action
// receipts were retained — so a consumer can observe the event without seeing
// content or secrets.
export interface AgentCompaction {
  round: number;
  summarizedMessages: number;
  receipts: number;
  promptTokens: number;
}

// The run degraded from the primary model to the configured one-shot fallback
// after a retryable provider failure produced no output (Issue #590). Metadata
// only — model identifiers and the transient reason class — never error text,
// request bodies, or secrets.
export interface AgentFallback {
  round: number;
  fromModel: string;
  toModel: string;
  reasonClass: string;
}

// Output sink for the agent loop. The default console sink reproduces the
// existing terminal behaviour; the headless sink (see headless-protocol.ts)
// renders the same lifecycle as a versioned JSON event stream.
export interface AgentSink {
  assistantDelta(delta: string): void;
  // `interrupted` is true when the turn's provider stream failed after emitting
  // text (#243): the text is preserved but the turn is incomplete. Absent/false
  // for normal turns.
  assistantTurn(text: string, round: number, opts: { final: boolean; interrupted?: boolean }): void;
  // `args` carries the tool's parsed arguments so a sink can render structured
  // detail (e.g. a file diff) without re-parsing; optional so existing sinks are
  // unaffected.
  toolStart(info: { id: string; name: string; round: number; args?: Record<string, unknown> }): void;
  toolResult(info: { id: string; name: string; result: ToolResult; round: number }): void;
  providerError(message: string): void;
  // Cumulative token usage and cost estimate, reported once per round.
  usage(info: AgentUsage): void;
  // A transient provider failure is being retried (bounded backoff).
  retry(info: AgentRetry): void;
  // The run degraded to the one-shot fallback model (Issue #590). Optional so
  // existing sinks are unaffected.
  fallback?(info: AgentFallback): void;
  // The in-memory transcript was compacted to relieve context pressure.
  compaction?(info: AgentCompaction): void;
  // A tool requires approval before executing. Optional: when present the sink
  // owns the prompt (e.g. the full-screen shell coordinates it within its own
  // raw-mode input model); when absent the agent falls back to the terminal
  // prompt. Returning false denies the tool exactly like a "no" at the prompt.
  requestApproval?(info: { name: string; args: Record<string, unknown> }): Promise<boolean>;
}

export function createConsoleSink(opts?: { messageUsage?: boolean }): AgentSink {
  const messageUsage = opts?.messageUsage ?? false;
  return {
    assistantDelta: (delta) => {
      process.stdout.write(delta);
    },
    assistantTurn: (_text, _round, opts) => {
      if (opts.interrupted) {
        // Terminate the partial line and show a plain-text (non-color-only)
        // interruption indicator. The emitted text stays visible on stdout; the
        // marker goes to stderr like the other run-level notes (#243).
        process.stdout.write("\n");
        process.stderr.write("[interrupted: incomplete response; the partial answer above was preserved]\n");
        return;
      }
      if (opts.final) process.stdout.write("\n");
    },
    toolStart: () => {},
    toolResult: () => {},
    providerError: (message) => {
      process.stderr.write(`\nProvider error: ${message}\n`);
    },
    usage: (info) => {
      // Opt-in per-message usage line (#241): a redacted turn-level readout of
      // tokens, estimated cost, TTFT, and throughput. Off by default so normal
      // conversation output is unchanged; written to stderr like the other
      // run-level notes so it never interleaves with assistant text on stdout.
      if (messageUsage) {
        process.stderr.write(
          `\n${formatMessageUsageLine({
            round: info.round,
            promptTokens: info.tokens.prompt,
            completionTokens: info.tokens.completion,
            totalTokens: info.tokens.total,
            estimatedCostUsd: info.estimatedCostUsd,
            costKnown: info.costKnown,
            ttftMs: info.ttftMs,
            tokensPerSecond: info.tokensPerSecond,
          })}\n`,
        );
      }
      // Keep normal output uncluttered; surface only the actionable budget stop.
      if (info.budgetReached && info.budgetUsd !== null) {
        process.stderr.write(
          `\nSpend budget reached: estimated ${formatCostUsd(info.estimatedCostUsd)} ` +
            `>= ${formatCostUsd(info.budgetUsd)}; stopping before further provider calls.\n`,
        );
      }
    },
    retry: (info) => {
      // A brief stderr note so the wait is visible without polluting stdout.
      process.stderr.write(
        `\nProvider retry ${info.attempt}/${info.maxAttempts} after ${info.reasonClass} ` +
          `(waiting ${info.delayMs}ms).\n`,
      );
    },
    fallback: (info) => {
      // The degrade is a material change of model for the rest of the run; it
      // goes to stderr like the other run-level notes, never into stdout.
      process.stderr.write(
        `\nProvider fallback: model "${info.fromModel}" failed transiently (${info.reasonClass}); ` +
          `degrading this run to fallback model "${info.toModel}".\n`,
      );
    },
    compaction: (info) => {
      // Surface the compaction so the context reduction is observable.
      process.stderr.write(
        `\nContext compacted: summarized ${info.summarizedMessages} message(s) ` +
          `(${info.receipts} completed-action receipt(s)) after ${info.promptTokens} prompt tokens.\n`,
      );
    },
  };
}

export interface AgentResult {
  text: string;
  ok: boolean;
  // `empty_response` is the terminal anomaly when the provider keeps returning a
  // stream with no assistant text and no valid tool call and the bounded
  // empty-completion recovery is exhausted (#244). `max_turns_reached`,
  // `wall_time_reached`, and `tool_call_budget_reached` are operator run-cap
  // stops (Issues #515, #517): bounded, round-boundary halts distinct from
  // failures.
  reason:
    | "completed"
    | "provider_error"
    | "max_rounds"
    | "budget_reached"
    | "max_turns_reached"
    | "wall_time_reached"
    | "tool_call_budget_reached"
    | "empty_response"
    | "cancelled";
  rounds: number;
  // Total transient provider retries across the run (0 when the provider never
  // failed transiently). Lets a consumer distinguish "exhausted retries"
  // (retries > 0, then provider_error) from "non-retryable" (retries 0).
  retries: number;
  // Bounded per-tool activity counts for the whole run. Each processed tool
  // call — executed (with or without error) or cancelled before execution —
  // is counted exactly once (no double-counted retries).
  stats: {
    toolCalls: Record<string, number>;
    toolFailures: Record<string, number>;
    // Calls cancelled before execution (#550); a subset of toolCalls that is
    // never counted in toolFailures.
    toolCancellations: Record<string, number>;
  };
  // Aggregated token totals across all rounds, or null when the provider never
  // reported usage.
  tokens: { prompt: number; completion: number; total: number } | null;
  // Prompt size of the most recent provider call in this run (Issue #721) —
  // the exact input the context-pressure auto-compaction gate compares
  // against. Null when no call has reported usage yet (including right after
  // an auto-compaction reset, until the next call reports).
  lastCallPromptTokens: number | null;
  // Estimated provider cost (USD) across the run, or null when the provider
  // never reported usage. An estimate, not authoritative billing.
  estimatedCostUsd: number | null;
  // Whether the model price was found in the bundled table (false ⇒ the
  // conservative fallback rate was used).
  costKnown: boolean;
  // One-shot fallback degrade (Issue #590): true when the run degraded from
  // the primary model to the configured fallback; `fallbackModel` is the model
  // the run degraded to (null when no degrade happened).
  fellBack: boolean;
  fallbackModel: string | null;
}

export async function runAgent(
  userPrompt: string,
  existingMessages: SessionMessage[],
  opts: AgentOptions,
): Promise<AgentResult> {
  const sink = opts.sink ?? createConsoleSink();
  // Wall-clock used for per-message timing; injectable for deterministic tests.
  const now = opts.now ?? Date.now;
  // Approval is owned by the sink when it offers a handler (the full-screen shell
  // coordinates the prompt within its raw-mode input model); otherwise the agent
  // falls back to the terminal prompt so non-interactive callers are unchanged.
  const requestApproval = sink.requestApproval
    ? (name: string, args: Record<string, unknown>): Promise<boolean> =>
        sink.requestApproval!({ name, args })
    : promptApproval;
  const tools = createTools();
  const toolMap = new Map(tools.map((t) => [t.name, t]));
  const schemas = toolSchemasForOpenAI(tools);
  const preToolUseHooks = opts.preToolUseHooks ?? [];
  // Provider stream: the network `streamChat` by default, or a deterministic
  // scripted provider for task-fixture replay (#224).
  const stream = opts.streamProvider ?? streamChat;

  const messages: SessionMessage[] = [...existingMessages];

  if (messages.length === 0) {
    // Fresh session: seed with the effective repository instruction context
    // (bounded identity + Git state + trusted instruction hierarchy) instead of
    // a generic prompt. Resumed sessions keep their original system message.
    const { text } = buildEffectiveSystemPrompt({ workspace: opts.workspace.root });
    // Run-scoped user instructions (Issue #789): appended as a labeled section
    // after the built-in prompt — the built-in text is a byte-for-byte prefix,
    // never modified. Validated at the dispatch boundary.
    const systemText = opts.appendSystemPrompt
      ? composeAppendedSystemPrompt(text, opts.appendSystemPrompt)
      : text;
    const system: SessionMessage = { role: "system", content: systemText };
    messages.push(system);
    opts.onMessage(system);
  }

  if (opts.appendUserMessage !== false) {
    // Text attachments (Issue #797) ride inside the message content itself —
    // unlike image bytes there is no out-of-band channel, and what the model
    // sees is exactly what the session persists. No attachments → the prompt
    // is used byte-for-byte.
    const userMsg: SessionMessage = {
      role: "user",
      content: promptWithTextAttachments(userPrompt, opts.textAttachments ?? []),
    };
    if (opts.images && opts.images.length > 0) {
      // In-memory copy carries the data URLs the provider needs.
      userMsg.images = opts.images.map((img) => ({
        name: img.name,
        mediaType: img.mediaType,
        bytes: img.bytes,
        dataUrl: img.dataUrl,
      }));
    }
    messages.push(userMsg);
    // Persist a privacy-safe copy: the data URL (raw image bytes) never reaches
    // the session log; only the non-secret reference (name, type, size) is kept.
    opts.onMessage(
      userMsg.images
        ? { ...userMsg, images: userMsg.images.map(({ name, mediaType, bytes }) => ({ name, mediaType, bytes })) }
        : userMsg,
    );
  }

  let finalText = "";

  const toolCalls: Record<string, number> = {};
  const toolFailures: Record<string, number> = {};
  const toolCancellations: Record<string, number> = {};
  const tokens = { prompt: 0, completion: 0, total: 0 };
  let hasUsage = false;
  // Total transient provider retries observed across the run.
  let retries = 0;
  // Running cost estimate (USD) across the run. Recomputed from cumulative
  // tokens each round; null in snapshots until the provider reports usage.
  let costUsd = 0;
  // One-shot fallback degrade (Issue #590). `activeConfig` is the provider
  // config the current round runs under; the degrade swaps its model once for
  // the remainder of the run. Cost accounting splits at the degrade so tokens
  // streamed under the primary keep the primary's price — with no degrade the
  // baselines stay 0 and the math reduces to whole-run pricing.
  const fallbackModel =
    typeof opts.fallbackModel === "string" && opts.fallbackModel.trim() !== ""
      ? opts.fallbackModel.trim()
      : null;
  let activeConfig = opts.config;
  let fellBack = false;
  let costBaselineUsd = 0;
  let baselinePromptTokens = 0;
  let baselineCompletionTokens = 0;
  let costKnown = lookupModelPrice(opts.config.model).known;
  const budgetUsd = opts.budgetUsd ?? null;
  // Operator run caps (Issue #515): same round-boundary semantics as the spend
  // budget. The wall-time cap measures real elapsed time through a dedicated
  // injectable clock (`runClock`), kept distinct from the per-message `now`
  // clock so capping never shifts TTFT timing sequences.
  const maxTurns =
    typeof opts.maxTurns === "number" && opts.maxTurns > 0 ? opts.maxTurns : null;
  const maxWallTimeMs =
    typeof opts.maxWallTimeMs === "number" && opts.maxWallTimeMs >= 0
      ? opts.maxWallTimeMs
      : null;
  // Tool-call cap (Issue #517): counts every tool call the loop processes
  // (including denied attempts, which also consume rounds and can loop), via
  // the same per-tool counters that back the run stats.
  const maxToolCalls =
    typeof opts.maxToolCalls === "number" && opts.maxToolCalls > 0
      ? opts.maxToolCalls
      : null;
  const runClock = opts.runClock ?? Date.now;
  const runStartedAt = runClock();
  // Context-pressure auto-compaction. Null disables it. `lastPromptTokens` is the
  // most recent provider call's prompt size — the live context pressure that
  // drives compaction at the next round boundary.
  const compactThreshold =
    typeof opts.compactThreshold === "number" && opts.compactThreshold > 0
      ? opts.compactThreshold
      : null;
  let lastPromptTokens = 0;
  const bump = (map: Record<string, number>, name: string) => {
    map[name] = (map[name] ?? 0) + 1;
  };
  const statsSnapshot = () => ({
    toolCalls: { ...toolCalls },
    toolFailures: { ...toolFailures },
    toolCancellations: { ...toolCancellations },
  });
  const tokensSnapshot = () => (hasUsage ? { ...tokens } : null);
  const costSnapshot = () => (hasUsage ? costUsd : null);
  // Issue #721: the auto-compaction gate input, surfaced for the /context
  // view. 0 means "no call has reported usage (yet)" — including right after
  // the gate resets the counter on compaction — and maps to null.
  const lastCallPromptTokensSnapshot = () =>
    lastPromptTokens > 0 ? lastPromptTokens : null;
  const budgetReached = () => budgetUsd !== null && costUsd >= budgetUsd;
  const totalToolCalls = () =>
    Object.values(toolCalls).reduce((sum, n) => sum + n, 0);

  for (let round = 0; round < MAX_ROUNDS; round++) {
    // Cooperative cancellation (#489): checked before any provider call in this
    // round, so a cancel issued while queued or between rounds stops the loop
    // without another billable call. Nothing has been streamed at a round
    // boundary, so there is no partial turn to persist here.
    if (opts.cancelRequested?.()) {
      return {
        text: finalText,
        ok: false,
        reason: "cancelled",
        rounds: round,
        retries,
        stats: statsSnapshot(),
        tokens: tokensSnapshot(),
        lastCallPromptTokens: lastCallPromptTokensSnapshot(),
        estimatedCostUsd: costSnapshot(),
        costKnown,
        fellBack,
        fallbackModel: fellBack ? fallbackModel : null,
      };
    }

    // Spend budget gate: once the running estimate has reached the cap, stop
    // before issuing a new provider call so no further billable calls are made.
    if (budgetReached()) {
      return {
        text: finalText,
        ok: false,
        reason: "budget_reached",
        rounds: round,
        retries,
        stats: statsSnapshot(),
        tokens: tokensSnapshot(),
        lastCallPromptTokens: lastCallPromptTokensSnapshot(),
        estimatedCostUsd: costSnapshot(),
        costKnown,
        fellBack,
        fallbackModel: fellBack ? fallbackModel : null,
      };
    }

    // Operator run-cap gates (Issue #515): the same round-boundary semantics as
    // the spend budget — stop before the next provider call, never mid-tool and
    // never mid-stream, so no partial turn or orphan tool call is produced.
    if (maxTurns !== null && round >= maxTurns) {
      return {
        text: finalText,
        ok: false,
        reason: "max_turns_reached",
        rounds: round,
        retries,
        stats: statsSnapshot(),
        tokens: tokensSnapshot(),
        lastCallPromptTokens: lastCallPromptTokensSnapshot(),
        estimatedCostUsd: costSnapshot(),
        costKnown,
        fellBack,
        fallbackModel: fellBack ? fallbackModel : null,
      };
    }
    if (maxWallTimeMs !== null && runClock() - runStartedAt >= maxWallTimeMs) {
      return {
        text: finalText,
        ok: false,
        reason: "wall_time_reached",
        rounds: round,
        retries,
        stats: statsSnapshot(),
        tokens: tokensSnapshot(),
        lastCallPromptTokens: lastCallPromptTokensSnapshot(),
        estimatedCostUsd: costSnapshot(),
        costKnown,
        fellBack,
        fallbackModel: fellBack ? fallbackModel : null,
      };
    }
    // Tool-call cap gate (Issue #517): stop at the first round boundary after
    // the cumulative processed tool-call count reaches the cap. The boundary
    // guarantees every tool call emitted by prior rounds has its result, so
    // the persisted transcript stays complete (no orphan tool_call).
    if (maxToolCalls !== null && totalToolCalls() >= maxToolCalls) {
      return {
        text: finalText,
        ok: false,
        reason: "tool_call_budget_reached",
        rounds: round,
        retries,
        stats: statsSnapshot(),
        tokens: tokensSnapshot(),
        lastCallPromptTokens: lastCallPromptTokensSnapshot(),
        estimatedCostUsd: costSnapshot(),
        costKnown,
        fellBack,
        fallbackModel: fellBack ? fallbackModel : null,
      };
    }

    // Context-pressure gate: when the most recent provider call's prompt size has
    // reached the threshold, compact the in-memory transcript before the next
    // provider call. Only the live `messages` window is replaced with a bounded
    // summary; the on-disk transcript is untouched (every message was already
    // persisted via onMessage). This runs at a round boundary where every prior
    // tool call already has its result, so no orphan tool_call is produced. The
    // threshold is reset so we do not re-compact until the context grows again.
    if (compactThreshold !== null && lastPromptTokens >= compactThreshold && messages.length > 1) {
      const triggeredAt = lastPromptTokens;
      const { summary } = compactMessages(messages);
      const compacted = buildCompactedTranscript(messages, summary);
      messages.length = 0;
      messages.push(...compacted);
      lastPromptTokens = 0;
      sink.compaction?.({
        round,
        summarizedMessages: summary.messageCount,
        receipts: summary.receipts.length,
        promptTokens: triggeredAt,
      });
    }

    let assistantText = "";
    let assistantToolCalls: Array<{ id: string; name: string; arguments: string }> = [];

    // Per-message timing (#241): the wall-clock just before the request, the
    // first streamed text token (for TTFT), and the turn's own completion tokens
    // (for throughput). firstTokenAt stays null for a turn that streams no text
    // (e.g. a pure tool-call turn), which omits TTFT downstream. These are
    // (re)assigned at the start of each attempt below; the placeholders here
    // satisfy definite-assignment without consuming a clock read.
    let roundStart = 0;
    let firstTokenAt: number | null = null;
    let roundCompletionTokens: number | null = null;

    // Bounded empty-completion recovery (#244): a stream that ends with neither
    // assistant text nor a valid tool call is an anomaly, not a completed answer.
    // Re-invoke the provider up to the fixed retry cap, charging each attempt's
    // usage to the budget and exposing each retry through the retry event path.
    let emptyAttempts = 0;
    let exhaustedEmpty = false;
    while (true) {
      assistantText = "";
      assistantToolCalls = [];
      roundStart = now();
      firstTokenAt = null;
      roundCompletionTokens = null;

      try {
        for await (const event of stream(activeConfig, messages, { tools: schemas })) {
          if (event.type === "text") {
            if (firstTokenAt === null) firstTokenAt = now();
            assistantText += event.delta;
            sink.assistantDelta(event.delta);
          } else if (event.type === "tool_call") {
            assistantToolCalls.push({ id: event.id, name: event.name, arguments: event.arguments });
          } else if (event.type === "usage") {
            hasUsage = true;
            tokens.prompt += event.promptTokens;
            tokens.completion += event.completionTokens;
            tokens.total += event.totalTokens;
            lastPromptTokens = event.promptTokens;
            roundCompletionTokens = event.completionTokens;
          } else if (event.type === "retry") {
            retries++;
            sink.retry({
              round,
              attempt: event.attempt,
              maxAttempts: event.maxAttempts,
              reasonClass: event.reasonClass,
              delayMs: event.delayMs,
            });
          }
          // Cooperative cancellation (#489): polled between streamed events so a
          // cancel takes effect at the next event boundary. Partial tool calls
          // are never persisted; only emitted assistant text survives, as one
          // interrupted turn.
          if (opts.cancelRequested?.()) {
            if (assistantText.length > 0) {
              const partial: SessionMessage = {
                role: "assistant",
                content: assistantText,
                interrupted: true,
              };
              messages.push(partial);
              opts.onMessage(partial);
              sink.assistantTurn(assistantText, round, { final: false, interrupted: true });
            }
            return {
              text: assistantText,
              ok: false,
              reason: "cancelled",
              rounds: round,
              retries,
              stats: statsSnapshot(),
              tokens: tokensSnapshot(),
              lastCallPromptTokens: lastCallPromptTokensSnapshot(),
              estimatedCostUsd: costSnapshot(),
              costKnown,
              fellBack,
              fallbackModel: fellBack ? fallbackModel : null,
            };
          }
        }
      } catch (err: unknown) {
        // One-shot fallback degrade (Issue #590): when the active model's
        // request fails transiently BEFORE producing any output (no text, no
        // tool calls) and a fallback is configured and not yet used, swap to
        // the fallback for the rest of the run and re-invoke the provider for
        // this round. The provider's own bounded retries already ran inside
        // streamChat; this is a degrade, not another retry of the same model.
        // A failure after any output, a non-retryable failure, or any failure
        // once already degraded falls through to the terminal path below.
        const transient = classifyTransient(err);
        if (
          fallbackModel !== null &&
          !fellBack &&
          transient !== null &&
          assistantText.length === 0 &&
          assistantToolCalls.length === 0
        ) {
          if (hasUsage) {
            costBaselineUsd = estimateCostUsd(activeConfig.model, {
              prompt: tokens.prompt,
              completion: tokens.completion,
            }).usd;
          }
          baselinePromptTokens = tokens.prompt;
          baselineCompletionTokens = tokens.completion;
          const fromModel = activeConfig.model;
          activeConfig = { ...activeConfig, model: fallbackModel };
          costKnown = costKnown && lookupModelPrice(fallbackModel).known;
          fellBack = true;
          sink.fallback?.({
            round,
            fromModel,
            toModel: fallbackModel,
            reasonClass: transient.reasonClass,
          });
          continue;
        }
        const rawMsg = err instanceof Error ? err.message : String(err);
        // Surface a stable, secret-safe quota-exhausted guidance instead of raw
        // provider prose when the failure is an exhausted quota (#247); other
        // failures keep their existing message.
        const msg = isQuotaExhausted(err)
          ? quotaExhaustedGuidance({
              model: activeConfig.model,
              redactedHost: redactEndpointHost(activeConfig.baseUrl),
            })
          : rawMsg;
        // Preserve a partial answer (#243): when the stream fails after emitting
        // text, persist exactly one interrupted assistant turn carrying only the
        // emitted text — never partial tool calls, raw provider errors, or
        // credentials — and surface it to the sink BEFORE the terminal failure so
        // consumers observe the partial record first. A failure before any text
        // persists nothing (no empty entry). The run still terminates as
        // provider_error with a non-zero exit; the partial turn is never reported
        // as completed, and the no-retry-after-output invariant is unchanged.
        if (assistantText.length > 0) {
          const partial: SessionMessage = {
            role: "assistant",
            content: assistantText,
            interrupted: true,
          };
          messages.push(partial);
          opts.onMessage(partial);
          sink.assistantTurn(assistantText, round, { final: false, interrupted: true });
        }
        sink.providerError(msg);
        return {
          text: assistantText,
          ok: false,
          reason: "provider_error",
          rounds: round,
          retries,
          stats: statsSnapshot(),
          tokens: tokensSnapshot(),
          lastCallPromptTokens: lastCallPromptTokensSnapshot(),
          estimatedCostUsd: costSnapshot(),
          costKnown,
          fellBack,
          fallbackModel: fellBack ? fallbackModel : null,
        };
      }

      // Charge this attempt's usage to the running cost estimate so every empty
      // attempt is accounted before any retry. Tokens streamed before a
      // fallback degrade (Issue #590) keep the earlier model's price via the
      // baseline; with no degrade the baseline is 0 and this is whole-run
      // pricing under the primary model.
      if (hasUsage) {
        costUsd =
          costBaselineUsd +
          estimateCostUsd(activeConfig.model, {
            prompt: tokens.prompt - baselinePromptTokens,
            completion: tokens.completion - baselineCompletionTokens,
          }).usd;
      }

      // A valid completion has at least one non-empty text delta or at least one
      // complete tool call; anything else is an empty completion to recover from.
      if (assistantText.length > 0 || assistantToolCalls.length > 0) break;

      emptyAttempts++;
      // The spend budget can prevent the next attempt.
      if (budgetReached()) {
        return {
          text: finalText,
          ok: false,
          reason: "budget_reached",
          rounds: round,
          retries,
          stats: statsSnapshot(),
          tokens: tokensSnapshot(),
          lastCallPromptTokens: lastCallPromptTokensSnapshot(),
          estimatedCostUsd: costSnapshot(),
          costKnown,
          fellBack,
          fallbackModel: fellBack ? fallbackModel : null,
        };
      }
      if (emptyAttempts >= RETRY_MAX_ATTEMPTS) {
        exhaustedEmpty = true;
        break;
      }
      const delayMs = backoffDelayMs(emptyAttempts, null);
      retries++;
      sink.retry({
        round,
        attempt: emptyAttempts + 1,
        maxAttempts: RETRY_MAX_ATTEMPTS,
        reasonClass: "empty_response",
        delayMs,
      });
      await sleep(delayMs);
    }

    if (exhaustedEmpty) {
      // Persistent empty completions: a truthful terminal failure with a non-zero
      // exit. No assistant turn (empty or otherwise) is persisted.
      sink.providerError(
        "provider returned an empty completion (no assistant text or tool call) after bounded retries",
      );
      return {
        text: "",
        ok: false,
        reason: "empty_response",
        rounds: round,
        retries,
        stats: statsSnapshot(),
        tokens: tokensSnapshot(),
        lastCallPromptTokens: lastCallPromptTokensSnapshot(),
        estimatedCostUsd: costSnapshot(),
        costKnown,
        fellBack,
        fallbackModel: fellBack ? fallbackModel : null,
      };
    }

    // Per-message responsiveness for this turn (#241), derived from the captured
    // timestamps; degrades to nulls when the provider gave no text token or usage.
    const timing = computeMessageTiming({
      requestStartMs: roundStart,
      firstTokenMs: firstTokenAt,
      generationEndMs: now(),
      completionTokens: roundCompletionTokens,
    });
    sink.usage({
      round,
      tokens: { ...tokens },
      estimatedCostUsd: costUsd,
      costKnown,
      budgetUsd,
      budgetReached: budgetReached(),
      ttftMs: timing.ttftMs,
      tokensPerSecond: timing.tokensPerSecond,
    });

    const final = assistantToolCalls.length === 0;
    sink.assistantTurn(assistantText, round, { final });

    if (final) {
      // Final answer
      finalText = assistantText;
      const assistantMsg: SessionMessage = { role: "assistant", content: assistantText };
      messages.push(assistantMsg);
      opts.onMessage(assistantMsg);
      return {
        text: finalText,
        ok: true,
        reason: "completed",
        rounds: round + 1,
        retries,
        stats: statsSnapshot(),
        tokens: tokensSnapshot(),
        lastCallPromptTokens: lastCallPromptTokensSnapshot(),
        estimatedCostUsd: costSnapshot(),
        costKnown,
        fellBack,
        fallbackModel: fellBack ? fallbackModel : null,
      };
    }

    // Record assistant message with tool calls
    const assistantMsg: SessionMessage = {
      role: "assistant",
      content: assistantText || null,
      tool_calls: assistantToolCalls.map((tc) => ({
        id: tc.id,
        type: "function",
        function: { name: tc.name, arguments: tc.arguments },
      })),
    };
    messages.push(assistantMsg);
    opts.onMessage(assistantMsg);

    // Execute each tool call. Cooperative cancellation (#489, refined by #550)
    // is polled before each call in the batch: the call in flight is never
    // killed, but once a cancel is requested the remaining calls are never
    // executed and each gets a transcript-valid cancelled placeholder, so the
    // transcript stays resume-valid and the record distinguishes cancelled
    // calls from executed ones.
    for (let i = 0; i < assistantToolCalls.length; i++) {
      const tc = assistantToolCalls[i];
      if (opts.cancelRequested?.()) {
        for (const pending of assistantToolCalls.slice(i)) {
          bump(toolCalls, pending.name);
          bump(toolCancellations, pending.name);
          sink.toolStart({ id: pending.id, name: pending.name, round, args: {} });
          sink.toolResult({
            id: pending.id,
            name: pending.name,
            result: { content: CANCELLED_TOOL_CONTENT, isError: true },
            round,
          });
          const cancelledMsg: SessionMessage = {
            role: "tool",
            content: CANCELLED_TOOL_CONTENT,
            tool_call_id: pending.id,
          };
          messages.push(cancelledMsg);
          opts.onMessage(cancelledMsg);
        }
        return {
          text: finalText,
          ok: false,
          reason: "cancelled",
          rounds: round,
          retries,
          stats: statsSnapshot(),
          tokens: tokensSnapshot(),
          lastCallPromptTokens: lastCallPromptTokensSnapshot(),
          estimatedCostUsd: costSnapshot(),
          costKnown,
          fellBack,
          fallbackModel: fellBack ? fallbackModel : null,
        };
      }
      // Parse the arguments once so the sink can render structured detail (e.g. a
      // file diff); a malformed payload degrades to no args rather than throwing.
      let parsedArgs: Record<string, unknown> = {};
      try {
        const p = JSON.parse(tc.arguments);
        if (p && typeof p === "object") parsedArgs = p as Record<string, unknown>;
      } catch {
        /* leave parsedArgs empty */
      }
      sink.toolStart({ id: tc.id, name: tc.name, round, args: parsedArgs });
      const result = await executeToolCall(
        tc,
        toolMap,
        opts.approvalMode,
        opts.workspace,
        opts.mutatingAllowed ?? true,
        requestApproval,
        preToolUseHooks,
        opts.bottleneck,
        opts.failureTaxonomy,
        opts.readOnly ?? false,
        opts.turnImages,
        opts.onShellFailure,
      );
      sink.toolResult({ id: tc.id, name: tc.name, result, round });
      bump(toolCalls, tc.name);
      if (result.isError) bump(toolFailures, tc.name);

      const toolMsg: SessionMessage = {
        role: "tool",
        content: result.content,
        tool_call_id: tc.id,
      };
      messages.push(toolMsg);
      opts.onMessage(toolMsg);
    }
  }

  return {
    text: finalText,
    ok: false,
    reason: "max_rounds",
    rounds: MAX_ROUNDS,
    retries,
    stats: statsSnapshot(),
    tokens: tokensSnapshot(),
    lastCallPromptTokens: lastCallPromptTokensSnapshot(),
    estimatedCostUsd: costSnapshot(),
    costKnown,
    fellBack,
    fallbackModel: fellBack ? fallbackModel : null,
  };
}

// Resolve a single tool call to its result, applying approval gating and
// uniform error handling. Approval is sought only when required; a denial or an
// unknown tool yields an error result rather than throwing.
async function executeToolCall(
  tc: { id: string; name: string; arguments: string },
  toolMap: Map<string, ToolDef>,
  approvalMode: ApprovalMode,
  workspace: Workspace,
  mutatingAllowed: boolean,
  requestApproval: (name: string, args: Record<string, unknown>) => Promise<boolean>,
  preToolUseHooks: readonly PreToolUseHook[],
  bottleneck: BottleneckCollector | undefined,
  failureTaxonomy: FailureTaxonomyCollector | undefined,
  readOnly: boolean,
  turnImages?: TurnImageCollector,
  onShellFailure?: (detail: ShellFailureDetail) => void,
): Promise<ToolResult> {
  const tool = toolMap.get(tc.name);
  if (!tool) {
    failureTaxonomy?.record("unknown_tool");
    return { content: `Error: unknown tool "${tc.name}"`, isError: true };
  }

  // Read-only mode (e.g. parallel investigation, #234) restricts the run to
  // read-only tools and refuses any mutating tool fail-closed, regardless of
  // approval mode or folder-trust state — yolo cannot widen it. This is what lets
  // several investigators share one workspace safely without isolation.
  if (readOnly && tool.category !== "read") {
    failureTaxonomy?.record("read_only_denied");
    return {
      content: "Tool execution denied: read-only mode allows only read-only tools (list, glob, grep, read)",
      isError: true,
    };
  }

  // Folder-trust enforcement runs first and regardless of approval mode, so an
  // untrusted workspace fails closed for every mutating tool — yolo cannot widen
  // the boundary. Read-only tools (list/glob/grep/read) are always permitted.
  if (!mutatingAllowed && tool.category !== "read") {
    failureTaxonomy?.record("folder_trust_denied");
    return { content: folderTrustDenialMessage(), isError: true };
  }

  // Deterministic command policy runs before approval and regardless of mode,
  // so a known-dangerous shape is denied even under yolo. Commands that pass
  // keep the existing approval/yolo behaviour unchanged.
  if (tool.category === "mutate-shell") {
    let command = "";
    try {
      const parsed = JSON.parse(tc.arguments);
      if (typeof parsed.command === "string") command = parsed.command;
    } catch { /* ignore */ }
    const decision = evaluateCommandPolicy(command, {
      provenance: "repository",
      workspace: workspace.root,
    });
    if (!decision.allowed) {
      failureTaxonomy?.record("policy_denied");
      return { content: policyDenialMessage(decision), isError: true };
    }
  }

  // PreToolUse hook gate (user-owned, deny-only): a matching hook may block the
  // call before approval is considered; silence leaves the normal approval flow
  // unchanged. A hook can only ever deny, never approve. A hook timeout or spawn
  // failure fails closed (the call is blocked) before any tool side effect.
  if (preToolUseHooks.length > 0) {
    let hookArgs: Record<string, unknown> = {};
    try {
      const parsed = JSON.parse(tc.arguments);
      if (parsed && typeof parsed === "object") hookArgs = parsed as Record<string, unknown>;
    } catch {
      /* leave hookArgs empty */
    }
    const decision = await evaluatePreToolUseHooks(
      preToolUseHooks,
      { toolName: tc.name, toolInput: hookArgs },
      { cwd: workspace.root },
    );
    if (decision.denied) {
      failureTaxonomy?.record("hook_denied");
      return {
        content: decision.reason
          ? `Tool call denied by a user PreToolUse hook: ${decision.reason}`
          : "Tool call denied by a user PreToolUse hook",
        isError: true,
      };
    }
  }

  if (needsApproval(approvalMode, tool.category)) {
    let parsed: Record<string, unknown> = {};
    try {
      parsed = JSON.parse(tc.arguments);
    } catch { /* ignore */ }
    // Time the approval gate separately from the tool's own execution so a long
    // human-approval wait surfaces as an `approval` bottleneck, not a tool one.
    const approvalStartedAt = Date.now();
    const approved = await requestApproval(tc.name, parsed);
    bottleneck?.recordApproval(tc.name, Date.now() - approvalStartedAt);
    if (!approved) {
      failureTaxonomy?.record("approval_denied");
      return { content: "Tool execution denied by user", isError: true };
    }
  }

  // Detects a path escape so a thrown escape is categorized distinctly from a
  // generic tool error in the failure taxonomy.
  let pathEscape = false;
  try {
    const parsed = JSON.parse(tc.arguments);
    // Capture the file's pre-image before a mutating-file tool overwrites it, so
    // the turn's workspace change can later be undone without a Git reset. Only
    // the first touch per path is recorded (the state before the turn); an
    // unresolvable path is left for the tool itself to reject.
    if (turnImages && tool.category === "mutate-file" && typeof parsed.path === "string") {
      try {
        turnImages.capture(workspace.resolveSafe(parsed.path));
      } catch {
        /* path escape is the tool's own error to surface */
      }
    }
    if (failureTaxonomy && tool.category === "mutate-file" && typeof parsed.path === "string") {
      try {
        workspace.resolveSafe(parsed.path);
      } catch {
        pathEscape = true;
      }
    }
    // Time only the tool's own execution (approval/policy/hook gates are measured
    // or rejected above); recorded even when the tool throws via the finally.
    const executeStartedAt = Date.now();
    try {
      const result = await tool.execute(parsed, workspace);
      // A tool that reports an error result without throwing is still a failed
      // call; categorize it (a detected path escape takes precedence).
      if (result.isError) {
        failureTaxonomy?.record(pathEscape ? "path_escape" : "tool_error");
      }
      // Shell failure receipt capture (Issue #574): best-effort, and a
      // recording failure never changes the result the turn observes.
      if (result.shellFailure && onShellFailure) {
        try {
          onShellFailure(result.shellFailure);
        } catch {
          /* best-effort evidence capture */
        }
      }
      return result;
    } catch (err: unknown) {
      failureTaxonomy?.record(pathEscape ? "path_escape" : "tool_error");
      const msg = err instanceof Error ? err.message : String(err);
      return { content: `Tool error: ${msg}`, isError: true };
    } finally {
      bottleneck?.recordTool(tc.name, Date.now() - executeStartedAt);
    }
  } catch (err: unknown) {
    // A failure outside the tool's own execution (e.g. malformed arguments).
    failureTaxonomy?.record("tool_error");
    const msg = err instanceof Error ? err.message : String(err);
    return { content: `Tool error: ${msg}`, isError: true };
  }
}

# ===== file: src/answer-routing.ts =====
// Answer routing: routes user answers to the waiting Goal instead of
// creating an unrelated conversation turn.
//
// When a Goal is waiting for user input, the user's response is associated
// with the waiting Goal revision and attempt. Answer routes are bounded
// (max 50), redacted, and deterministic.

import { redactSecrets } from "./permission-impact.js";
import { safeCutEnd } from "./text-cut.js";

export const ANSWER_ROUTING_SCHEMA = "oh-my-cli.answer-routing";
export const ANSWER_ROUTING_VERSION = 1;

// --- types ------------------------------------------------------------------

export interface AnswerRoute {
  /** Route identifier. */
  id: string;
  /** The user's answer text (bounded, redacted). */
  answerText: string;
  /** Goal revision the answer is routed to. */
  goalRevision: number;
  /** Attempt the answer is routed to. */
  attempt: number;
  /** When the answer was received (epoch ms). */
  receivedAt: number;
  /** Whether the answer has been consumed by the Goal. */
  consumed: boolean;
  /** When the answer was consumed (epoch ms). */
  consumedAt?: number;
}

// --- bounds -----------------------------------------------------------------

const MAX_ROUTES = 50;
const MAX_ANSWER_LENGTH = 500;

function safeAnswer(value: string): string {
  const terminalSafe = value
    .replace(/[\u0000-\u001f\u007f]+/g, " ")
    .replace(/[\u200b-\u200f\u202a-\u202e\u2060-\u206f\ufeff]/g, "")
    .replace(/\s+/g, " ")
    .trim();
  const redacted = redactSecrets(terminalSafe).text;
  return redacted.length <= MAX_ANSWER_LENGTH
    ? redacted
    : `${redacted.slice(0, safeCutEnd(redacted, MAX_ANSWER_LENGTH - 1))}…`;
}

// --- answer router ----------------------------------------------------------

export class AnswerRouter {
  private readonly routes: AnswerRoute[] = [];
  private nextId = 1;

  /** Route a user answer to a waiting Goal. */
  routeAnswer(
    answerText: string,
    goalRevision: number,
    attempt: number,
    receivedAt: number = Date.now(),
  ): AnswerRoute | null {
    if (this.routes.length >= MAX_ROUTES) {
      return null; // At capacity.
    }

    const route: AnswerRoute = {
      id: `answer-${this.nextId++}`,
      answerText: safeAnswer(answerText),
      goalRevision,
      attempt,
      receivedAt,
      consumed: false,
    };

    this.routes.push(route);
    return { ...route };
  }

  /** Get all pending (unconsumed) answer routes. */
  getPendingAnswerRoutes(): AnswerRoute[] {
    return this.routes
      .filter((r) => !r.consumed)
      .map((r) => ({ ...r }));
  }

  /** Get all answer routes for a specific revision. */
  getRoutesForRevision(goalRevision: number): AnswerRoute[] {
    return this.routes
      .filter((r) => r.goalRevision === goalRevision)
      .map((r) => ({ ...r }));
  }

  /** Consume an answer route (mark as consumed). */
  consumeAnswer(routeId: string, consumedAt: number = Date.now()): AnswerRoute | null {
    const route = this.routes.find((r) => r.id === routeId);
    if (!route || route.consumed) return null;

    route.consumed = true;
    route.consumedAt = consumedAt;
    return { ...route };
  }

  /** Number of routes. */
  get size(): number {
    return this.routes.length;
  }

  /** Number of pending routes. */
  get pendingCount(): number {
    return this.routes.filter((r) => !r.consumed).length;
  }
}

// --- formatting -------------------------------------------------------------

export function formatAnswerRouter(router: AnswerRouter): string {
  const pending = router.getPendingAnswerRoutes();
  const lines: string[] = [];

  lines.push("Answer Routes");
  lines.push("═".repeat(50));
  lines.push(`Total: ${router.size}  Pending: ${router.pendingCount}`);
  lines.push("");

  for (const route of pending) {
    lines.push(`  ○ ${route.id} → rev ${route.goalRevision}, attempt ${route.attempt}`);
    lines.push(`    "${route.answerText}"`);
  }

  if (pending.length === 0) {
    lines.push("  No pending answers.");
  }

  lines.push("");
  lines.push("Read-only: no conversation turns managed.");

  return lines.join("\n");
}

# ===== file: src/approval-inbox.ts =====
// Read-only approval inbox inspection: shows pending and decided approval
// requests with action context, risk, expiry, and decision trail.
//
// Approval entries expose id, action summary, risk level, requested-by,
// expiry, head SHA, decision state, decided-by, and decided-at. Expired
// approvals are flagged when current time exceeds expiry. Stale-head
// detection flags approvals where the head SHA has changed. The view is
// read-only and never grants approvals, executes actions, or modifies
// the inbox.

export const APPROVAL_INBOX_SCHEMA = "oh-my-cli.approval-inbox";
export const APPROVAL_INBOX_VERSION = 1;

// --- types ------------------------------------------------------------------

export type RiskLevel = "low" | "medium" | "high" | "critical";
export type ApprovalState = "pending" | "approved" | "rejected" | "expired";

export interface ApprovalEntry {
  /** Stable approval identifier. */
  id: string;
  /** Summary of the action requiring approval. */
  actionSummary: string;
  riskLevel: RiskLevel;
  /** Who requested the approval. */
  requestedBy: string;
  /** Epoch ms of the request. */
  requestedAt: number;
  /** Epoch ms when the approval expires. */
  expiresAt: number;
  /** Head SHA at the time of the request. */
  headSha: string;
  /** Current decision state. */
  state: ApprovalState;
  /** Who made the decision (when decided). */
  decidedBy?: string;
  /** Epoch ms of the decision (when decided). */
  decidedAt?: number;
  /** Whether the head SHA has changed since the request. */
  staleHead: boolean;
}

// --- approval inbox ---------------------------------------------------------

export class ApprovalInbox {
  private readonly entries: ApprovalEntry[] = [];

  /** Add an approval request. */
  request(opts: {
    id: string;
    actionSummary: string;
    riskLevel: RiskLevel;
    requestedBy: string;
    requestedAt: number;
    expiresAt: number;
    headSha: string;
  }): ApprovalEntry {
    const entry: ApprovalEntry = {
      ...opts,
      state: "pending",
      staleHead: false,
    };
    this.entries.push(entry);
    return entry;
  }

  /** Record an approval decision (read-only model: records, does not execute). */
  decide(id: string, decision: "approved" | "rejected", decidedBy: string, decidedAt: number): void {
    const entry = this.entries.find((e) => e.id === id);
    if (!entry || entry.state !== "pending") return;
    entry.state = decision;
    entry.decidedBy = decidedBy;
    entry.decidedAt = decidedAt;
  }

  /** Refresh expiry and staleness state. */
  refresh(now: number, currentHeadSha: string): void {
    for (const entry of this.entries) {
      if (entry.state === "pending" && now > entry.expiresAt) {
        entry.state = "expired";
      }
      entry.staleHead = entry.headSha !== currentHeadSha;
    }
  }

  get(id: string): ApprovalEntry | undefined {
    return this.entries.find((e) => e.id === id);
  }

  list(): ApprovalEntry[] {
    return [...this.entries];
  }

  getPending(): ApprovalEntry[] {
    return this.entries.filter((e) => e.state === "pending");
  }

  getDecided(): ApprovalEntry[] {
    return this.entries.filter((e) => e.state === "approved" || e.state === "rejected");
  }

  getExpired(): ApprovalEntry[] {
    return this.entries.filter((e) => e.state === "expired");
  }

  getStaleHead(): ApprovalEntry[] {
    return this.entries.filter((e) => e.staleHead);
  }

  get size(): number {
    return this.entries.length;
  }
}

// --- inbox view -------------------------------------------------------------

export interface ApprovalInboxView {
  schema: typeof APPROVAL_INBOX_SCHEMA;
  v: typeof APPROVAL_INBOX_VERSION;
  entries: ApprovalEntry[];
  totalCount: number;
  pendingCount: number;
  decidedCount: number;
  expiredCount: number;
  staleHeadCount: number;
  hasStaleHead: boolean;
  snapshotAt: number;
}

export function assembleInboxView(inbox: ApprovalInbox): ApprovalInboxView {
  const entries = inbox.list();
  return {
    schema: APPROVAL_INBOX_SCHEMA,
    v: APPROVAL_INBOX_VERSION,
    entries,
    totalCount: entries.length,
    pendingCount: inbox.getPending().length,
    decidedCount: inbox.getDecided().length,
    expiredCount: inbox.getExpired().length,
    staleHeadCount: inbox.getStaleHead().length,
    hasStaleHead: inbox.getStaleHead().length > 0,
    snapshotAt: Date.now(),
  };
}

// --- formatting -------------------------------------------------------------

export function formatApprovalEntry(entry: ApprovalEntry): string {
  const icon = stateIcon(entry.state);
  const risk = riskIcon(entry.riskLevel);
  const stale = entry.staleHead ? " ⚠STALE HEAD" : "";
  const lines: string[] = [];
  lines.push(`${icon} ${entry.actionSummary} [${entry.riskLevel}]${stale}`);
  lines.push(`  Requested by ${entry.requestedBy}  Expires: ${new Date(entry.expiresAt).toISOString()}`);
  lines.push(`  Head: ${entry.headSha.slice(0, 12)}`);

  if (entry.state !== "pending") {
    lines.push(`  Decision: ${entry.state} by ${entry.decidedBy ?? "system"} at ${entry.decidedAt ? new Date(entry.decidedAt).toISOString() : "N/A"}`);
  }

  return lines.join("\n");
}

export function formatInboxSummary(inbox: ApprovalInbox): string {
  const lines: string[] = [];
  lines.push("Approval Inbox");
  lines.push("═".repeat(50));
  lines.push(`Total: ${inbox.size}  Pending: ${inbox.getPending().length}  Decided: ${inbox.getDecided().length}  Expired: ${inbox.getExpired().length}`);

  if (inbox.getStaleHead().length > 0) {
    lines.push("⚠ Stale-head approvals detected (head SHA changed)");
  }

  for (const entry of inbox.list()) {
    lines.push("");
    lines.push(formatApprovalEntry(entry));
  }

  lines.push("");
  lines.push("Read-only: no approvals granted, no actions executed.");

  return lines.join("\n");
}

function stateIcon(state: ApprovalState): string {
  switch (state) {
    case "pending": return "○";
    case "approved": return "✓";
    case "rejected": return "✗";
    case "expired": return "⏰";
  }
}

function riskIcon(risk: RiskLevel): string {
  switch (risk) {
    case "low": return "▽";
    case "medium": return "◆";
    case "high": return "▲";
    case "critical": return "⚠";
  }
}

# ===== file: src/approval-mode-switch.ts =====
// Runtime approval-mode switching (Issue #715): the pure decision model behind
// the interactive `/approval-mode` command. The palette used to advertise three
// multi-word stubs that could never resolve from typed input and changed
// nothing from palette selection; this model makes the advertised control real
// and honest: report the effective mode, reject invalid input naming the valid
// modes, apply a de-escalation (tighter gating) immediately, and apply an
// escalation (looser gating) only through an explicit two-step confirmation.
//
// The decision is pure and shared by both interactive surfaces so the
// full-screen shell and the plain readline REPL render identical outcomes. The
// approval plane itself (needsApproval/promptApproval) is untouched — it
// consumes the effective mode as input.

import type { ApprovalMode } from "./approval.js";

export const APPROVAL_MODES: readonly ApprovalMode[] = ["default", "auto-edit", "yolo"];

// Permission rank: lower is stricter. De-escalation moves toward 0,
// escalation away from it.
const MODE_RANK: Record<ApprovalMode, number> = {
  default: 0,
  "auto-edit": 1,
  yolo: 2,
};

export function parseApprovalMode(text: string): ApprovalMode | null {
  const trimmed = text.trim().toLowerCase();
  const match = APPROVAL_MODES.find((mode) => mode.toLowerCase() === trimmed);
  return match ?? null;
}

export type ApprovalModeCommandDecision =
  // No argument: report the effective mode and the command shape.
  | { kind: "report"; mode: ApprovalMode }
  // Unknown mode or trailing form: nothing changes; the notice names the
  // valid modes / usage.
  | { kind: "invalid"; requested: string }
  // Requested mode equals the effective one: nothing changes, said plainly.
  | { kind: "unchanged"; mode: ApprovalMode }
  // Strictly tighter gating: applies immediately.
  | { kind: "de-escalate"; mode: ApprovalMode }
  // Looser gating: NOT applied. The caller records the pending escalation and
  // shows the warning; only the explicit confirm form applies it.
  | { kind: "escalation-needs-confirm"; mode: ApprovalMode }
  // `confirm` was given but there is no matching pending escalation: nothing
  // changes, and the notice says exactly that.
  | { kind: "escalation-unconfirmed"; mode: ApprovalMode }
  // `confirm` matches the pending escalation: applies.
  | { kind: "escalation-confirmed"; mode: ApprovalMode };

export function approvalModeCommandDecision(
  current: ApprovalMode,
  args: string,
  pendingEscalation: ApprovalMode | null,
): ApprovalModeCommandDecision {
  const parts = args.trim().split(/\s+/).filter(Boolean);
  if (parts.length === 0) return { kind: "report", mode: current };
  const mode = parseApprovalMode(parts[0]);
  if (mode === null) return { kind: "invalid", requested: parts[0] };
  const rest = parts.slice(1);
  if (rest.length > 0 && rest.join(" ").toLowerCase() !== "confirm") {
    return { kind: "invalid", requested: rest.join(" ") };
  }
  const confirmed = rest.length > 0;
  if (mode === current) return { kind: "unchanged", mode };
  if (MODE_RANK[mode] < MODE_RANK[current]) return { kind: "de-escalate", mode };
  // Escalation from here on: never applied without the explicit confirm form
  // matching a pending request for exactly this mode.
  if (!confirmed) return { kind: "escalation-needs-confirm", mode };
  if (pendingEscalation !== mode) return { kind: "escalation-unconfirmed", mode };
  return { kind: "escalation-confirmed", mode };
}

// Does the decision apply a new effective mode?
export function decisionAppliesMode(
  decision: ApprovalModeCommandDecision,
): decision is
  | { kind: "de-escalate"; mode: ApprovalMode }
  | { kind: "escalation-confirmed"; mode: ApprovalMode } {
  return decision.kind === "de-escalate" || decision.kind === "escalation-confirmed";
}

// What pending escalation the caller should hold after this decision: an
// escalation request replaces it; every other outcome clears it, so a stale
// confirmation can never apply a request the user moved away from.
export function nextPendingEscalation(
  decision: ApprovalModeCommandDecision,
): ApprovalMode | null {
  return decision.kind === "escalation-needs-confirm" ? decision.mode : null;
}

const ESCALATION_CONSEQUENCE: Record<ApprovalMode, string> = {
  default: "",
  "auto-edit": "file edits will run without approval; shell commands still require it",
  yolo: "all mutating tools will run without approval",
};

// One shared renderer so both interactive surfaces (and the tests) show the
// same honest outcome. Never implies approval for any pending request.
export function formatApprovalModeNotice(decision: ApprovalModeCommandDecision): string {
  switch (decision.kind) {
    case "report":
      return (
        `Approval mode: ${decision.mode}. ` +
        `Change with /approval-mode <${APPROVAL_MODES.join("|")}>; loosening requires an explicit confirm.`
      );
    case "invalid":
      return (
        `Unknown approval mode or form "${decision.requested}". ` +
        `Valid modes: ${APPROVAL_MODES.join(", ")}. Usage: /approval-mode [mode [confirm]].`
      );
    case "unchanged":
      return `Approval mode is already ${decision.mode}.`;
    case "de-escalate":
      return `Approval mode set to ${decision.mode} (tighter). Subsequent turns are gated by it.`;
    case "escalation-needs-confirm":
      return (
        `Escalating to ${decision.mode} loosens tool gating: ${ESCALATION_CONSEQUENCE[decision.mode]}. ` +
        `Not applied — run /approval-mode ${decision.mode} confirm to apply.`
      );
    case "escalation-unconfirmed":
      return (
        `Nothing confirmed — there is no pending escalation to ${decision.mode}. ` +
        `Run /approval-mode ${decision.mode} first, then /approval-mode ${decision.mode} confirm.`
      );
    case "escalation-confirmed":
      return `Approval mode set to ${decision.mode} (looser, explicitly confirmed). Subsequent turns are gated by it.`;
  }
}

# ===== file: src/approval.ts =====
import readline from "node:readline";
import { analyzeImpact, formatImpact } from "./permission-impact.js";

export type ApprovalMode = "default" | "auto-edit" | "yolo";

export type ToolCategory = "read" | "mutate-file" | "mutate-shell";

export function needsApproval(mode: ApprovalMode, category: ToolCategory): boolean {
  if (category === "read") return false;
  if (mode === "yolo") return false;
  if (mode === "auto-edit" && category === "mutate-file") return false;
  return true;
}

export async function promptApproval(toolName: string, args: Record<string, unknown>): Promise<boolean> {
  if (!process.stdin.isTTY) {
    return false;
  }

  const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
  const summary = formatImpact(analyzeImpact(toolName, args));
  return new Promise((resolve) => {
    rl.question(`\n⚠ Tool "${toolName}" requires approval.\n${summary}\nAllow? (y/N) `, (answer) => {
      rl.close();
      resolve(answer.toLowerCase() === "y");
    });
  });
}

# ===== file: src/archive-stale.ts =====
// Archive-stale executor (Issue #702): the retention story's action half.
// The stale-sessions report (#626, strict-gated by #680) detects archive
// candidates; this surface acts on exactly those candidates.
//
// Dry run is the default: resolve the same candidates the stale-sessions
// report shows and print them with a trailing note, mutating nothing.
// --apply opts into the mutation, and the mutation is bounded by design:
// archiving writes the existing archived marker (via the same primitive as
// --archive-session), never deletes, never touches transcripts or any
// other sidecar, and is reversible with --unarchive-session. Pinned and
// already-archived sessions are protected by the builder and never become
// candidates, so they can never be re-archived here either.

import type { SessionStore } from "./session.js";
import {
  buildStaleSessionsReport,
  type StaleSessionsRecord,
} from "./stale-sessions.js";
import { archiveSession } from "./session-archive.js";

export const ARCHIVE_STALE_SCHEMA = "oh-my-cli.archive-stale" as const;
export const ARCHIVE_STALE_VERSION = 1 as const;

export type ArchiveStaleMode = "dry-run" | "apply";

/** Versioned machine-readable record of an archive-stale run (Issue #702). */
export interface ArchiveStaleRecord {
  schema: typeof ARCHIVE_STALE_SCHEMA;
  v: typeof ARCHIVE_STALE_VERSION;
  thresholdDays: number;
  mode: ArchiveStaleMode;
  /** Sessions resolved as archive candidates, oldest first. */
  candidates: Array<{ sessionId: string; shortId: string }>;
  /** Session ids archived by this run; empty in dry-run mode. */
  archivedIds: string[];
  protectedPinned: number;
  protectedArchived: number;
}

export interface ArchiveStaleOutcome {
  /** The resolved stale report — reused verbatim for the dry-run text. */
  report: StaleSessionsRecord;
  record: ArchiveStaleRecord;
}

/**
 * Execute an archive-stale run (Issue #702). In dry-run mode the store is
 * never touched; in apply mode exactly the resolved candidates receive the
 * archived marker via the shared archiveSession primitive (idempotent —
 * a session that is already archived is reported as such, never rewritten).
 */
export function executeArchiveStale(
  store: SessionStore,
  opts: { thresholdDays: number; apply: boolean },
): ArchiveStaleOutcome {
  const report = buildStaleSessionsReport(store, { thresholdDays: opts.thresholdDays });
  const candidates = report.candidates.map((c) => ({
    sessionId: c.sessionId,
    shortId: c.shortId,
  }));
  const archivedIds: string[] = [];
  if (opts.apply) {
    for (const candidate of candidates) {
      const result = archiveSession(store, candidate.sessionId);
      if (result.ok && !result.alreadyArchived) {
        archivedIds.push(candidate.sessionId);
      }
    }
  }
  return {
    report,
    record: {
      schema: ARCHIVE_STALE_SCHEMA,
      v: ARCHIVE_STALE_VERSION,
      thresholdDays: opts.thresholdDays,
      mode: opts.apply ? "apply" : "dry-run",
      candidates,
      archivedIds,
      protectedPinned: report.protectedPinned,
      protectedArchived: report.protectedArchived,
    },
  };
}

/**
 * Render the apply-mode result as lines (Issue #702). Dry-run text is the
 * stale-sessions report itself plus a trailing note (rendered by the
 * caller), so its "Advisory only — nothing is archived" footer stays true.
 */
export function formatArchiveStale(record: ArchiveStaleRecord): string[] {
  const lines: string[] = [];
  lines.push(`Archive stale sessions — threshold ${record.thresholdDays} day(s)`);
  lines.push("─".repeat(40));
  lines.push("");
  if (record.candidates.length === 0) {
    lines.push("No stale archive candidates at this threshold.");
  } else {
    lines.push("Archived:");
    for (const candidate of record.candidates) {
      lines.push(`  ${candidate.shortId}`);
    }
  }
  lines.push(
    `Protected (older than threshold): ${record.protectedPinned} pinned · ${record.protectedArchived} archived.`,
  );
  lines.push("");
  lines.push(
    `Archived ${record.archivedIds.length} session(s). Nothing was deleted; restore any with --unarchive-session ${record.candidates.length > 0 ? record.candidates[0].shortId : "<id>"}.`,
  );
  return lines;
}

/** The trailing note appended to the dry-run rendering (Issue #702). */
export const ARCHIVE_STALE_DRY_RUN_NOTE =
  "Dry run: nothing archived (re-run with --apply to archive the sessions above).";

# ===== file: src/artifact-history.ts =====
// Read-only artifact history: links produced artifacts to producing turns
// and file diffs when real evidence exists.
//
// Artifact entries expose stable identity, kind, producing turn, session,
// content hash, timestamp, and associated file paths. History is ordered by
// production time and bounded. Attribution is present only when real
// evidence exists; absent evidence reports "no attribution". The view is
// read-only and never creates, modifies, or deletes artifacts.

export const ARTIFACT_HISTORY_SCHEMA = "oh-my-cli.artifact-history";
export const ARTIFACT_HISTORY_VERSION = 1;

// --- bounds -----------------------------------------------------------------

const DEFAULT_MAX_ENTRIES = 100;

// --- artifact types ---------------------------------------------------------

export type ArtifactKind = "html" | "image" | "screenshot" | "export" | "document" | "other";

export type AttributionState = "attributed" | "no-attribution";

export interface ArtifactEntry {
  /** Stable, unique identifier. */
  id: string;
  kind: ArtifactKind;
  /** Display label. */
  label: string;
  /** SHA-256 hex digest of the artifact content. */
  contentHash: string;
  /** Session that produced this artifact. */
  sessionId: string;
  /** Turn that produced this artifact (when known). */
  turnId?: string;
  /** Associated file paths (when known). */
  filePaths: string[];
  /** Epoch ms of production. */
  producedAt: number;
  /** Size in bytes. */
  sizeBytes: number;
  /** Whether turn/file attribution is based on real evidence. */
  attributionState: AttributionState;
}

// --- artifact history -------------------------------------------------------

export class ArtifactHistory {
  private readonly entries: ArtifactEntry[] = [];
  private readonly maxEntries: number;

  constructor(maxEntries: number = DEFAULT_MAX_ENTRIES) {
    this.maxEntries = maxEntries;
  }

  /** Record a produced artifact. */
  record(opts: {
    id: string;
    kind: ArtifactKind;
    label: string;
    contentHash: string;
    sessionId: string;
    turnId?: string;
    filePaths?: string[];
    producedAt: number;
    sizeBytes: number;
  }): ArtifactEntry {
    const entry: ArtifactEntry = {
      ...opts,
      filePaths: opts.filePaths ?? [],
      attributionState: (opts.turnId || (opts.filePaths && opts.filePaths.length > 0))
        ? "attributed"
        : "no-attribution",
    };
    this.entries.push(entry);
    // Bound the history.
    if (this.entries.length > this.maxEntries) {
      this.entries.shift(); // Remove oldest.
    }
    return entry;
  }

  /** Get all entries ordered by production time (newest first). */
  list(): ArtifactEntry[] {
    return [...this.entries].sort((a, b) => b.producedAt - a.producedAt);
  }

  /** Get entries for a specific session. */
  getBySession(sessionId: string): ArtifactEntry[] {
    return this.list().filter((e) => e.sessionId === sessionId);
  }

  /** Get entries for a specific turn. */
  getByTurn(turnId: string): ArtifactEntry[] {
    return this.list().filter((e) => e.turnId === turnId);
  }

  /** Get entries with no attribution. */
  getUnattributed(): ArtifactEntry[] {
    return this.list().filter((e) => e.attributionState === "no-attribution");
  }

  get size(): number {
    return this.entries.length;
  }
}

// --- history view -----------------------------------------------------------

export interface ArtifactHistoryView {
  schema: typeof ARTIFACT_HISTORY_SCHEMA;
  v: typeof ARTIFACT_HISTORY_VERSION;
  entries: ArtifactEntry[];
  totalCount: number;
  attributedCount: number;
  unattributedCount: number;
  /** Counts by kind. */
  kindCounts: Partial<Record<ArtifactKind, number>>;
  snapshotAt: number;
}

// Assemble a read-only history view.
export function assembleArtifactHistoryView(history: ArtifactHistory): ArtifactHistoryView {
  const entries = history.list();
  const kindCounts: Partial<Record<ArtifactKind, number>> = {};

  let attributedCount = 0;
  let unattributedCount = 0;

  for (const e of entries) {
    kindCounts[e.kind] = (kindCounts[e.kind] ?? 0) + 1;
    if (e.attributionState === "attributed") attributedCount++;
    else unattributedCount++;
  }

  return {
    schema: ARTIFACT_HISTORY_SCHEMA,
    v: ARTIFACT_HISTORY_VERSION,
    entries,
    totalCount: entries.length,
    attributedCount,
    unattributedCount,
    kindCounts,
    snapshotAt: Date.now(),
  };
}

// --- formatting -------------------------------------------------------------

// Format a history view as a compact TUI view.
export function formatArtifactHistoryView(view: ArtifactHistoryView): string {
  const lines: string[] = [];
  lines.push("Artifact History");
  lines.push("═".repeat(50));
  lines.push(`Total: ${view.totalCount}  Attributed: ${view.attributedCount}  Unattributed: ${view.unattributedCount}`);

  const kinds = Object.entries(view.kindCounts);
  if (kinds.length > 0) {
    lines.push(`Kinds: ${kinds.map(([k, v]) => `${k}:${v}`).join("  ")}`);
  }

  for (const entry of view.entries.slice(0, 10)) {
    const icon = kindIcon(entry.kind);
    const turn = entry.turnId ? ` turn:${entry.turnId}` : " turn:(no attribution)";
    const files = entry.filePaths.length > 0 ? ` files:[${entry.filePaths.join(", ")}]` : "";
    lines.push(`${icon} ${entry.label} [${entry.id}]${turn}${files}`);
    lines.push(`  ${entry.kind}  ${entry.sizeBytes}B  hash:${entry.contentHash.slice(0, 12)}…`);
  }

  if (view.entries.length > 10) {
    lines.push(`… ${view.entries.length - 10} more artifacts`);
  }

  lines.push("");
  lines.push("Read-only: no artifacts created, modified, or deleted.");

  return lines.join("\n");
}

function kindIcon(kind: ArtifactKind): string {
  switch (kind) {
    case "html": return "◆";
    case "image": return "▣";
    case "screenshot": return "▣";
    case "export": return "◇";
    case "document": return "▤";
    case "other": return "·";
  }
}

# ===== file: src/artifact-preview.ts =====
// Safe static HTML artifact preview.
//
// Accepts a local HTML artifact reference, resolves it within the trusted
// workspace, and produces an inspectable preview with scripts, network,
// navigation, and filesystem access disabled by default. The preview policy
// is fail-closed: anything not explicitly allowed is blocked, and every
// blocked item is reported with a reason. Preview evidence is attributable
// to the active session and exact artifact content hash.
//
// The module is surface-independent: the same artifact produces the same
// sanitized output and policy report for both the TUI and a future Desktop
// pane.

import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import type { Workspace } from "./workspace.js";
import { safeCutEnd } from "./text-cut.js";

export const ARTIFACT_PREVIEW_SCHEMA = "oh-my-cli.artifact-preview";
export const ARTIFACT_PREVIEW_VERSION = 1;

// --- bounds -----------------------------------------------------------------

const MAX_ARTIFACT_BYTES = 5 * 1_048_576; // 5 MiB
const MAX_PREVIEW_LINES = 500;
const SNIFF_BYTES = 8_000;

// --- preview policy ---------------------------------------------------------

// The security policy applied to every artifact preview. All capabilities
// are disabled by default; the struct records what was enforced.
export interface PreviewPolicy {
  scripts: "disabled";
  network: "disabled";
  navigation: "disabled";
  filesystem: "disabled";
  forms: "disabled";
}

export const DEFAULT_PREVIEW_POLICY: PreviewPolicy = Object.freeze({
  scripts: "disabled",
  network: "disabled",
  navigation: "disabled",
  filesystem: "disabled",
  forms: "disabled",
});

// --- blocked content --------------------------------------------------------

export type BlockedReason =
  | "script-tag"
  | "event-handler"
  | "remote-url"
  | "iframe"
  | "form"
  | "meta-refresh"
  | "object-embed"
  | "javascript-uri";

export interface BlockedContent {
  reason: BlockedReason;
  /** 1-based line number where the content was found. */
  line: number;
  /** Truncated preview of the blocked line. */
  preview: string;
}

// --- artifact identity ------------------------------------------------------

export interface ArtifactIdentity {
  /** Workspace-relative path. */
  path: string;
  /** SHA-256 hex digest of the raw artifact content. */
  contentHash: string;
  /** Size in bytes. */
  sizeBytes: number;
}

// --- preview result ---------------------------------------------------------

export type RenderStatus = "ok" | "refused";

export interface ArtifactPreview {
  schema: typeof ARTIFACT_PREVIEW_SCHEMA;
  v: typeof ARTIFACT_PREVIEW_VERSION;
  identity: ArtifactIdentity;
  policy: PreviewPolicy;
  renderStatus: RenderStatus;
  /** Sanitized HTML lines (scripts/network/navigation removed). */
  sanitizedLines: string[];
  /** Total lines in the original artifact. */
  totalLines: number;
  /** Whether the preview was truncated to MAX_PREVIEW_LINES. */
  truncated: boolean;
  /** Content that was blocked, with reasons. */
  blocked: BlockedContent[];
  /** Whether any content was blocked. */
  hasBlockedContent: boolean;
}

export interface ArtifactRefusal {
  renderStatus: "refused";
  reason: "untrusted" | "oversized" | "unreadable" | "binary" | "outside-workspace" | "not-html";
  detail: string;
}

export type ArtifactPreviewResult = ArtifactPreview | ArtifactRefusal;

// --- detection patterns -----------------------------------------------------

const SCRIPT_TAG_RE = /<script[\s>]/i;
const EVENT_HANDLER_RE = /\bon\w+\s*=/i;
const REMOTE_URL_RE = /(?:src|href|action|data|poster)\s*=\s*["']?https?:\/\//i;
const IFRAME_RE = /<iframe[\s>]/i;
const FORM_RE = /<form[\s>]/i;
const META_REFRESH_RE = /<meta[^>]+http-equiv\s*=\s*["']?refresh/i;
const OBJECT_EMBED_RE = /<(?:object|embed)[\s>]/i;
const JAVASCRIPT_URI_RE = /(?:href|src|action)\s*=\s*["']?\s*javascript:/i;

const DETECTION_RULES: Array<{ re: RegExp; reason: BlockedReason }> = [
  { re: SCRIPT_TAG_RE, reason: "script-tag" },
  { re: EVENT_HANDLER_RE, reason: "event-handler" },
  { re: REMOTE_URL_RE, reason: "remote-url" },
  { re: IFRAME_RE, reason: "iframe" },
  { re: FORM_RE, reason: "form" },
  { re: META_REFRESH_RE, reason: "meta-refresh" },
  { re: OBJECT_EMBED_RE, reason: "object-embed" },
  { re: JAVASCRIPT_URI_RE, reason: "javascript-uri" },
];

// --- sanitization -----------------------------------------------------------

// Sanitize a single HTML line by neutralizing dangerous content. The line
// is returned with blocked patterns replaced by safe placeholders, and the
// blocked items are recorded.
function sanitizeLine(line: string, lineNum: number, blocked: BlockedContent[]): string {
  let sanitized = line;

  for (const { re, reason } of DETECTION_RULES) {
    if (re.test(sanitized)) {
      blocked.push({
        reason,
        line: lineNum,
        preview: truncate(line.trim(), 120),
      });
      // Neutralize: replace the dangerous content with a safe comment.
      sanitized = neutralize(sanitized, reason);
    }
  }

  return sanitized;
}

// Replace dangerous HTML constructs with safe, visible placeholders.
function neutralize(line: string, reason: BlockedReason): string {
  switch (reason) {
    case "script-tag":
      return line.replace(/<script[\s\S]*?<\/script>/gi, `<!-- [BLOCKED: script] -->`)
                 .replace(/<script[\s>][^>]*>/gi, `<!-- [BLOCKED: script] -->`);
    case "event-handler":
      return line.replace(/\bon\w+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, "data-blocked-handler");
    case "remote-url":
      return line.replace(/((?:src|href|action|data|poster)\s*=\s*["']?)https?:\/\/[^"'\s>]*/gi, "$1about:blank");
    case "iframe":
      return line.replace(/<iframe[\s\S]*?<\/iframe>/gi, `<!-- [BLOCKED: iframe] -->`)
                 .replace(/<iframe[^>]*\/?>/gi, `<!-- [BLOCKED: iframe] -->`);
    case "form":
      return line.replace(/<form([^>]*)>/gi, "<div data-blocked-form$1>")
                 .replace(/<\/form>/gi, "</div>");
    case "meta-refresh":
      return line.replace(/<meta[^>]+http-equiv\s*=\s*["']?refresh[^>]*>/gi, `<!-- [BLOCKED: meta-refresh] -->`);
    case "object-embed":
      return line.replace(/<(?:object|embed)[\s\S]*?<\/(?:object|embed)>/gi, `<!-- [BLOCKED: object/embed] -->`)
                 .replace(/<(?:object|embed)[^>]*\/?>/gi, `<!-- [BLOCKED: object/embed] -->`);
    case "javascript-uri":
      return line.replace(/((?:href|src|action)\s*=\s*["']?\s*)javascript:[^"'\s>]*/gi, "$1about:blank");
    default:
      return line;
  }
}

function truncate(s: string, max: number): string {
  if (s.length <= max) return s;
  return s.slice(0, safeCutEnd(s, max - 1)) + "…";
}

// --- binary detection -------------------------------------------------------

function looksBinary(buf: Buffer): boolean {
  const limit = Math.min(buf.length, SNIFF_BYTES);
  for (let i = 0; i < limit; i++) {
    if (buf[i] === 0) return true;
  }
  return false;
}

// --- preview ----------------------------------------------------------------

export interface PreviewOptions {
  /** Whether the workspace is trusted. Defaults to true. */
  trusted?: boolean;
  /** Maximum artifact size in bytes. */
  maxBytes?: number;
}

// Default deliverable path for an exported artifact (Issue #803): strip one
// trailing .html/.htm extension from the basename and append ".safe.html",
// keeping the file beside the original. Pure: no filesystem access.
export function defaultDeliverablePath(relPath: string): string {
  const dir = path.dirname(relPath);
  const base = path.basename(relPath).replace(/\.(html|htm)$/i, "");
  const name = `${base}.safe.html`;
  return dir === "." ? name : path.join(dir, name);
}

// Produce a safe static preview of a local HTML artifact. The artifact is
// resolved within the workspace, validated, sanitized (scripts, network,
// navigation, forms disabled), and returned with a full policy report and
// blocked-content inventory. Fails closed with explicit recovery guidance.
export function previewArtifact(
  workspace: Workspace,
  relPath: string,
  opts: PreviewOptions = {},
): ArtifactPreviewResult {
  const trusted = opts.trusted ?? true;
  const maxBytes = opts.maxBytes ?? MAX_ARTIFACT_BYTES;

  // Trust gate.
  if (!trusted) {
    return { renderStatus: "refused", reason: "untrusted", detail: "Workspace is untrusted. Trust it with --trust or add it to the trust store." };
  }

  // Path safety.
  if (relPath.startsWith("/") || relPath.split("/").includes("..")) {
    return { renderStatus: "refused", reason: "outside-workspace", detail: "Path is absolute or contains ... Use a workspace-relative path." };
  }

  // Extension check.
  const ext = path.extname(relPath).toLowerCase();
  if (ext !== ".html" && ext !== ".htm") {
    return { renderStatus: "refused", reason: "not-html", detail: `Extension "${ext}" is not HTML. Only .html and .htm files can be previewed.` };
  }

  // Resolve within workspace.
  let abs: string;
  try {
    abs = workspace.resolve(relPath);
  } catch {
    return { renderStatus: "refused", reason: "outside-workspace", detail: "Path escapes the workspace. Use a path within the project root." };
  }

  // Read and validate.
  let stat: fs.Stats;
  try {
    stat = fs.statSync(abs);
  } catch {
    return { renderStatus: "refused", reason: "unreadable", detail: "File does not exist or is not readable. Check the path and permissions." };
  }

  if (stat.size > maxBytes) {
    return { renderStatus: "refused", reason: "oversized", detail: `File is ${stat.size} bytes (limit ${maxBytes}). Reduce the artifact size.` };
  }

  let buf: Buffer;
  try {
    buf = fs.readFileSync(abs);
  } catch {
    return { renderStatus: "refused", reason: "unreadable", detail: "Read failed. Check permissions." };
  }

  if (looksBinary(buf)) {
    return { renderStatus: "refused", reason: "binary", detail: "Content contains NUL bytes. Only text HTML files can be previewed." };
  }

  const content = buf.toString("utf-8");
  const contentHash = crypto.createHash("sha256").update(buf).digest("hex");
  const allLines = content.split("\n");
  const totalLines = allLines.length;

  // Sanitize.
  const blocked: BlockedContent[] = [];
  const limit = Math.min(totalLines, MAX_PREVIEW_LINES);
  const sanitizedLines: string[] = [];

  for (let i = 0; i < limit; i++) {
    sanitizedLines.push(sanitizeLine(allLines[i], i + 1, blocked));
  }

  return {
    schema: ARTIFACT_PREVIEW_SCHEMA,
    v: ARTIFACT_PREVIEW_VERSION,
    identity: {
      path: relPath,
      contentHash,
      sizeBytes: stat.size,
    },
    policy: DEFAULT_PREVIEW_POLICY,
    renderStatus: "ok",
    sanitizedLines,
    totalLines,
    truncated: totalLines > MAX_PREVIEW_LINES,
    blocked,
    hasBlockedContent: blocked.length > 0,
  };
}

// --- formatting -------------------------------------------------------------

// Format a preview result as a compact, color-independent summary for the
// TUI. Shows artifact identity, policy, render status, blocked content,
// and safe actions.
export function formatArtifactPreview(result: ArtifactPreviewResult): string {
  if ("reason" in result) {
    const lines = [
      "Artifact Preview — REFUSED",
      "─".repeat(40),
      `Reason:  ${result.reason}`,
      `Detail:  ${result.detail}`,
    ];
    return lines.join("\n");
  }

  const lines: string[] = [];
  lines.push("Artifact Preview");
  lines.push("─".repeat(40));
  lines.push(`Path:    ${result.identity.path}`);
  lines.push(`Hash:    ${result.identity.contentHash.slice(0, 16)}…`);
  lines.push(`Size:    ${result.identity.sizeBytes} bytes`);
  lines.push(`Status:  ${result.renderStatus}`);
  lines.push(`Lines:   ${result.sanitizedLines.length} / ${result.totalLines}${result.truncated ? " (truncated)" : ""}`);
  lines.push("");
  lines.push("Policy:");
  lines.push(`  Scripts:     ${result.policy.scripts}`);
  lines.push(`  Network:     ${result.policy.network}`);
  lines.push(`  Navigation:  ${result.policy.navigation}`);
  lines.push(`  Filesystem:  ${result.policy.filesystem}`);
  lines.push(`  Forms:       ${result.policy.forms}`);

  if (result.blocked.length > 0) {
    lines.push("");
    lines.push(`Blocked content (${result.blocked.length}):`);
    for (const b of result.blocked) {
      lines.push(`  ✗ L${b.line} [${b.reason}] ${b.preview}`);
    }
  } else {
    lines.push("");
    lines.push("Blocked content: none");
  }

  lines.push("");
  lines.push("Actions: open (safe) · export sanitized");

  return lines.join("\n");
}

# ===== file: src/artifact-retention.ts =====
// Artifact retention: defines retention and cleanup rules for completed
// Goal execution artifacts.
//
// RetentionPolicy defines max age (days) and max count. ArtifactInventory
// tracks artifact type, creation time, and size. evaluateRetention determines
// cleanup eligibility. Read-only evaluation (does not delete anything).
// Deterministic.

export const ARTIFACT_RETENTION_SCHEMA = "oh-my-cli.artifact-retention";
export const ARTIFACT_RETENTION_VERSION = 1;

// --- types ------------------------------------------------------------------

export type ArtifactType =
  | "audit-event"
  | "cancelled-attempt"
  | "completion-summary"
  | "failure-summary"
  | "execution-outline"
  | "answer-route";

export interface ArtifactRecord {
  /** Artifact identifier. */
  id: string;
  type: ArtifactType;
  /** When the artifact was created (epoch ms). */
  createdAt: number;
  /** Size in bytes (approximate). */
  sizeBytes: number;
  /** Goal revision this artifact belongs to. */
  goalRevision: number;
}

export interface RetentionPolicy {
  /** Maximum age in days. Artifacts older than this are eligible for cleanup. */
  maxAgeDays: number;
  /** Maximum count per Goal revision. Excess artifacts are eligible for cleanup. */
  maxCountPerRevision: number;
}

export interface RetentionEvaluation {
  /** Artifacts that should be retained. */
  retained: ArtifactRecord[];
  /** Artifacts eligible for cleanup. */
  eligibleForCleanup: ArtifactRecord[];
  /** Reason for each cleanup eligibility. */
  cleanupReasons: Map<string, string>;
  /** Total size of retained artifacts. */
  retainedSizeBytes: number;
  /** Total size of cleanup-eligible artifacts. */
  cleanupSizeBytes: number;
}

// --- default policy ---------------------------------------------------------

export const DEFAULT_RETENTION_POLICY: RetentionPolicy = {
  maxAgeDays: 7,
  maxCountPerRevision: 50,
};

// --- retention evaluation ---------------------------------------------------

const MS_PER_DAY = 86_400_000;

// Evaluate retention for a set of artifacts.
export function evaluateRetention(
  artifacts: ArtifactRecord[],
  policy: RetentionPolicy = DEFAULT_RETENTION_POLICY,
  now: number = Date.now(),
): RetentionEvaluation {
  const retained: ArtifactRecord[] = [];
  const eligibleForCleanup: ArtifactRecord[] = [];
  const cleanupReasons = new Map<string, string>();

  const maxAgeMs = policy.maxAgeDays * MS_PER_DAY;

  // Group by revision for count-based evaluation.
  const byRevision = new Map<number, ArtifactRecord[]>();
  for (const artifact of artifacts) {
    const group = byRevision.get(artifact.goalRevision) ?? [];
    group.push(artifact);
    byRevision.set(artifact.goalRevision, group);
  }

  // Count-based ranking: sort each revision group once (newest first) and
  // record each artifact's rank. This replaces the previous per-artifact
  // re-sort + linear indexOf scan with one sort per revision plus an O(1) rank
  // lookup, turning count evaluation from O(n² log n) into O(n log n) (#852).
  // Behavior is unchanged: same stable newest-first ordering and ranks.
  const indexByArtifact = new Map<ArtifactRecord, number>();
  for (const group of byRevision.values()) {
    const sorted = [...group].sort((a, b) => b.createdAt - a.createdAt);
    sorted.forEach((artifact, index) => indexByArtifact.set(artifact, index));
  }

  for (const artifact of artifacts) {
    const ageMs = now - artifact.createdAt;
    const isTooOld = ageMs > maxAgeMs;

    const indexInRevision = indexByArtifact.get(artifact)!;
    const isExcess = indexInRevision >= policy.maxCountPerRevision;

    if (isTooOld) {
      eligibleForCleanup.push(artifact);
      cleanupReasons.set(artifact.id, `Age ${Math.floor(ageMs / MS_PER_DAY)}d exceeds max ${policy.maxAgeDays}d`);
    } else if (isExcess) {
      eligibleForCleanup.push(artifact);
      cleanupReasons.set(artifact.id, `Count ${indexInRevision + 1} exceeds max ${policy.maxCountPerRevision} per revision`);
    } else {
      retained.push(artifact);
    }
  }

  const retainedSizeBytes = retained.reduce((sum, a) => sum + a.sizeBytes, 0);
  const cleanupSizeBytes = eligibleForCleanup.reduce((sum, a) => sum + a.sizeBytes, 0);

  return {
    retained,
    eligibleForCleanup,
    cleanupReasons,
    retainedSizeBytes,
    cleanupSizeBytes,
  };
}

// --- formatting -------------------------------------------------------------

export function formatRetentionReport(evaluation: RetentionEvaluation): string {
  const lines: string[] = [];

  lines.push("Artifact Retention Report");
  lines.push("═".repeat(50));
  lines.push(`Retained: ${evaluation.retained.length} (${formatBytes(evaluation.retainedSizeBytes)})`);
  lines.push(`Eligible for cleanup: ${evaluation.eligibleForCleanup.length} (${formatBytes(evaluation.cleanupSizeBytes)})`);

  if (evaluation.eligibleForCleanup.length > 0) {
    lines.push("");
    lines.push("Eligible for cleanup:");
    for (const artifact of evaluation.eligibleForCleanup.slice(0, 10)) {
      const reason = evaluation.cleanupReasons.get(artifact.id) ?? "unknown";
      lines.push(`  · ${artifact.id} [${artifact.type}] — ${reason}`);
    }
    if (evaluation.eligibleForCleanup.length > 10) {
      lines.push(`  … ${evaluation.eligibleForCleanup.length - 10} more`);
    }
  }

  lines.push("");
  lines.push("Read-only: no artifacts deleted.");

  return lines.join("\n");
}

export function formatBytes(bytes: number): string {
  if (bytes < 1024) return `${bytes}B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;
  // Issue #850: scale past MB as well, so multi-gigabyte footprints (session
  // stores, retention totals) render as GB/TB instead of thousands/millions of
  // MB (a 1 TB store previously printed "1048576.0MB").
  if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
  if (bytes < 1024 * 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)}GB`;
  return `${(bytes / (1024 * 1024 * 1024 * 1024)).toFixed(1)}TB`;
}

# ===== file: src/ascii-output.ts =====
// ASCII-safe output mode for the read-only report/journal surfaces
// (Issue #672), extended to the read-only session surfaces (Issue #674).
//
// The report/journal family renders with Unicode decoration — box-drawing
// separators, middle dots, multiplication signs, em dashes — and the
// session surfaces additionally emit semantic marks (status checks, arrows,
// ellipses); the health inventory adds warning/disabled status marks
// (Issue #696). For screen readers, legacy terminals, C-locale pipelines, and
// log scrapers these glyphs are noise or breakage. `--ascii` maps the
// glyphs to ASCII equivalents while keeping all content and structure
// identical: decorative glyphs map to their nearest ASCII shape; semantic
// marks map to readable ASCII that preserves the mark's meaning.
//
// The transformation is a pure, deterministic per-line substitution applied
// only to the known glyphs; user content (note text, goal objectives) is
// never rewritten. JSON output is untouched — it is already ASCII-safe data.

/**
 * Glyphs emitted by the in-scope surfaces, mapped to ASCII. Semantic marks
 * (Issue #674) map to readable ASCII preserving the mark's meaning;
 * decorative glyphs map to their nearest ASCII shape.
 */
export const ASCII_GLYPH_MAP: Readonly<Record<string, string>> = {
  "\u2500": "-", // ─ box-drawing separator
  "\u00b7": "|", // · middle-dot field separator
  "\u00d7": "x", // × count multiplier
  "\u2014": "-", // — em dash
  "\u2026": "...", // … ellipsis
  "\u2192": "->", // → arrow
  "\u2194": "<->", // ↔ bidirectional arrow