File size: 73,532 Bytes
df01731
 
 
 
53df0c2
df01731
296b327
df01731
 
6d453e3
df01731
 
 
6d453e3
df01731
 
 
 
 
6d453e3
296b327
 
6d453e3
296b327
 
6d453e3
 
 
df01731
296b327
df01731
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d453e3
 
 
 
 
 
 
 
 
 
 
296b327
 
 
 
 
 
 
 
 
 
 
 
6d453e3
 
 
 
 
 
 
 
 
 
 
296b327
 
 
 
6d453e3
 
df01731
 
 
 
 
 
 
 
 
 
 
 
 
 
53df0c2
 
 
 
df01731
 
 
 
 
 
 
53df0c2
 
 
 
 
6d453e3
53df0c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d453e3
 
 
 
 
 
 
 
 
 
 
 
df01731
296b327
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df01731
 
 
 
 
 
 
 
 
296b327
 
df01731
296b327
 
 
df01731
 
 
 
 
 
 
 
 
6d453e3
df01731
 
 
6d453e3
296b327
df01731
 
53df0c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d453e3
53df0c2
 
 
 
 
6d453e3
53df0c2
 
6d453e3
 
 
 
 
df01731
 
6d453e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
296b327
6d453e3
 
 
 
 
 
 
 
 
 
296b327
6d453e3
296b327
 
6d453e3
 
 
 
296b327
6d453e3
 
296b327
 
 
 
 
 
 
6d453e3
 
 
 
 
 
296b327
 
 
 
 
 
 
 
 
 
6d453e3
296b327
6d453e3
 
296b327
 
6d453e3
 
296b327
 
 
 
6d453e3
 
 
 
 
296b327
6d453e3
 
296b327
 
 
 
 
 
 
6d453e3
296b327
 
 
6d453e3
296b327
6d453e3
296b327
 
 
6d453e3
296b327
6d453e3
296b327
6d453e3
296b327
6d453e3
 
53df0c2
 
6d453e3
296b327
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d453e3
 
 
 
 
 
 
 
53df0c2
6d453e3
 
53df0c2
 
 
 
 
 
 
296b327
6d453e3
53df0c2
 
6d453e3
296b327
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53df0c2
296b327
53df0c2
 
 
296b327
53df0c2
 
296b327
53df0c2
 
296b327
 
53df0c2
 
296b327
6d453e3
53df0c2
296b327
53df0c2
296b327
6d453e3
296b327
 
 
 
 
 
 
 
6d453e3
296b327
 
6d453e3
296b327
 
 
 
 
 
 
 
 
 
 
 
 
 
6d453e3
296b327
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53df0c2
 
 
6d453e3
 
 
 
296b327
 
6d453e3
296b327
 
 
6d453e3
296b327
 
6d453e3
296b327
 
6d453e3
 
296b327
 
6d453e3
296b327
 
 
6d453e3
 
296b327
6d453e3
 
 
 
296b327
6d453e3
 
 
 
 
 
 
296b327
 
6d453e3
 
296b327
 
6d453e3
 
 
 
 
296b327
6d453e3
 
 
 
53df0c2
 
296b327
 
 
 
 
 
 
 
 
 
 
6d453e3
296b327
53df0c2
6d453e3
 
 
296b327
 
6d453e3
 
296b327
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d453e3
 
296b327
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d453e3
 
 
 
296b327
 
 
6d453e3
296b327
 
 
 
6d453e3
 
296b327
 
 
6d453e3
 
 
296b327
 
 
6d453e3
296b327
 
6d453e3
296b327
6d453e3
296b327
6d453e3
296b327
 
6d453e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
296b327
6d453e3
 
296b327
6d453e3
296b327
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d453e3
 
 
 
296b327
 
6d453e3
296b327
6d453e3
 
296b327
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d453e3
296b327
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d453e3
 
 
 
296b327
 
6d453e3
 
 
 
296b327
 
6d453e3
 
296b327
53df0c2
 
296b327
 
6d453e3
 
 
296b327
6d453e3
 
 
 
296b327
6d453e3
296b327
6d453e3
 
 
 
296b327
6d453e3
 
 
 
 
 
 
53df0c2
6d453e3
 
 
 
53df0c2
6d453e3
 
 
 
 
 
296b327
6d453e3
df01731
6d453e3
 
 
 
 
 
 
 
296b327
6d453e3
 
 
 
 
 
df01731
 
6d453e3
53df0c2
6d453e3
296b327
 
6d453e3
296b327
 
 
 
6d453e3
 
 
 
 
296b327
53df0c2
296b327
 
 
 
 
 
 
 
6d453e3
 
 
 
 
296b327
 
6d453e3
296b327
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d453e3
 
 
296b327
53df0c2
296b327
53df0c2
6d453e3
53df0c2
296b327
 
6d453e3
53df0c2
296b327
 
6d453e3
53df0c2
 
 
 
6d453e3
 
 
 
296b327
6d453e3
53df0c2
6d453e3
296b327
 
 
 
 
 
 
 
 
6d453e3
 
 
296b327
 
 
 
 
 
 
 
 
 
 
 
6d453e3
 
 
 
296b327
6d453e3
 
 
 
 
296b327
 
6d453e3
 
296b327
 
 
6d453e3
 
296b327
 
 
6d453e3
296b327
6d453e3
 
 
53df0c2
6d453e3
 
 
 
 
 
 
296b327
53df0c2
 
 
6d453e3
 
53df0c2
 
 
 
 
 
 
296b327
 
 
df01731
 
6d453e3
 
 
 
 
 
 
 
 
 
 
296b327
6d453e3
 
 
 
 
 
 
 
 
 
 
296b327
6d453e3
 
 
 
 
 
 
 
 
 
 
 
 
296b327
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d453e3
 
df01731
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d453e3
 
296b327
6d453e3
 
df01731
6d453e3
296b327
6d453e3
296b327
 
 
 
 
 
6d453e3
 
296b327
 
6d453e3
 
 
 
df01731
 
296b327
 
 
df01731
6d453e3
df01731
296b327
df01731
 
 
 
 
 
6d453e3
 
df01731
 
 
6d453e3
df01731
 
 
 
296b327
6d453e3
 
 
 
 
 
 
 
 
296b327
 
 
 
 
 
 
df01731
296b327
 
df01731
 
6d453e3
df01731
6d453e3
 
 
 
 
 
 
 
 
 
 
296b327
 
6d453e3
 
 
 
df01731
6d453e3
 
df01731
 
6d453e3
df01731
 
6d453e3
 
 
df01731
6d453e3
 
df01731
 
 
6d453e3
 
 
 
 
 
df01731
 
6d453e3
 
 
df01731
 
 
 
 
 
 
 
 
296b327
53df0c2
 
 
 
6d453e3
296b327
 
 
6d453e3
296b327
 
 
 
6d453e3
 
 
 
 
 
53df0c2
6d453e3
 
 
 
 
53df0c2
6d453e3
 
 
 
 
 
296b327
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d453e3
 
 
 
 
 
 
 
 
 
 
 
296b327
6d453e3
 
 
 
 
 
296b327
 
 
 
 
6d453e3
 
 
 
 
 
 
 
 
 
 
296b327
6d453e3
 
 
 
 
 
296b327
 
6d453e3
296b327
 
 
 
 
 
 
 
6d453e3
 
 
296b327
6d453e3
296b327
 
 
 
6d453e3
 
 
53df0c2
 
df01731
 
 
6d453e3
296b327
6d453e3
df01731
 
 
 
 
53df0c2
df01731
 
 
 
6d453e3
296b327
df01731
 
 
 
 
 
 
 
 
 
 
 
296b327
 
 
53df0c2
296b327
df01731
296b327
6d453e3
296b327
df01731
296b327
 
 
 
df01731
296b327
53df0c2
296b327
 
 
 
 
 
df01731
296b327
 
 
 
 
 
 
6d453e3
 
296b327
df01731
296b327
 
6d453e3
df01731
296b327
df01731
296b327
 
 
df01731
296b327
6d453e3
296b327
df01731
 
 
 
 
 
 
 
 
 
 
 
 
6d453e3
 
 
296b327
 
6d453e3
 
 
 
296b327
6d453e3
 
296b327
 
6d453e3
296b327
df01731
53df0c2
 
6d453e3
53df0c2
df01731
 
 
 
 
 
 
 
296b327
 
 
 
df01731
 
 
296b327
6d453e3
 
df01731
 
 
 
296b327
 
6d453e3
df01731
296b327
 
 
 
 
 
6d453e3
 
296b327
df01731
 
 
6d453e3
 
 
 
296b327
6d453e3
 
 
 
 
df01731
 
 
 
 
 
296b327
df01731
 
 
 
 
296b327
df01731
6d453e3
296b327
 
 
df01731
6d453e3
 
 
 
 
 
 
 
 
 
296b327
 
6d453e3
296b327
 
 
 
 
 
 
 
 
df01731
6d453e3
 
296b327
 
df01731
 
 
296b327
 
df01731
 
296b327
 
 
df01731
296b327
df01731
296b327
6d453e3
 
296b327
df01731
 
 
 
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
#!/usr/bin/env python3
from __future__ import annotations

import argparse
import difflib
import json
import os
import random
import re
import shutil
import statistics
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any

import pandas as pd


DATASET_NAME = "LifeStreamingCoT"
REPO_ID = "skyzhou06/LifeStreamingCoT"
DATASET_VERSION = "v0.4"
GENERATION_METHOD = "source_grounded_rule_based_v0.4_quality_refined"
REASONING_POLICY = "selective_concise"
CHUNKING_METHOD = "semantic_sentence_split_v0.4_refined"
REFINEMENT_METHOD = "rule_based_quality_refinement_v0.4"
INSTRUCTION = "Help the user complete a real-life task based on gradually revealed information."
CACHE_DIR = Path(".lifesct_cache")
SOURCE_CACHE = CACHE_DIR / "v0_2_source_rows.jsonl"

BASE_FIELDS = [
    "id",
    "domain",
    "source_dataset",
    "instruction",
    "context",
    "context_chunks",
    "streaming_reasoning",
    "deep_reasoning",
    "answer",
    "response",
    "messages",
    "text",
    "num_chunks",
    "language",
    "split",
    "generation_method",
    "quality_flags",
    "version",
    "reasoning_policy",
    "chunking_method",
    "chunk_labels",
    "skip_chunks",
    "skip_reasons",
    "reasoning_token_budget",
    "original_num_chunks",
    "chunk_split_count",
]

V04_FIELDS = [
    "quality_score",
    "is_high_quality",
    "refinement_method",
    "llm_augmented",
    "llm_augmentation_model",
    "rejected_reason",
    "state_tracking_confidence",
]

REQUIRED_FIELDS = BASE_FIELDS + V04_FIELDS

REASONING_TOKEN_BUDGET = {
    "streaming_reasoning_max_words_per_chunk": 18,
    "deep_reasoning_max_words": 45,
    "answer_max_sentences": 3,
}

FORBIDDEN_GENERIC_PHRASES = [
    "the user is sharing everyday context",
    "the situation is about an everyday life situation",
    "the assistant should stay conversational",
    "the user is asking for help, clarification, or a next step",
    "support need centers on",
    "task_detail=noted",
    "emotion=positive; cause=",
    "emotion=negative; cause=",
    "given the full context",
    "tracked constraints so far",
]

BLOCKLIST = [
    "suicide",
    "self-harm",
    "self harm",
    "kill myself",
    "kill yourself",
    "sexual assault",
    "rape",
    "explicit sex",
    "porn",
    "build a gun",
    "make a bomb",
    "legal advice",
    "lawsuit",
    "attorney",
    "court case",
    "cocaine",
    "heroin",
    "methamphetamine",
    "credit card number",
    "social security number",
]

STOPWORDS = {
    "about",
    "after",
    "again",
    "also",
    "and",
    "are",
    "because",
    "before",
    "being",
    "but",
    "can",
    "could",
    "does",
    "doing",
    "for",
    "from",
    "get",
    "got",
    "good",
    "great",
    "had",
    "has",
    "have",
    "how",
    "into",
    "its",
    "it's",
    "just",
    "know",
    "later",
    "like",
    "more",
    "much",
    "need",
    "only",
    "please",
    "really",
    "should",
    "some",
    "sure",
    "that",
    "the",
    "their",
    "there",
    "these",
    "they",
    "thing",
    "things",
    "this",
    "time",
    "today",
    "want",
    "was",
    "were",
    "well",
    "what",
    "when",
    "where",
    "which",
    "with",
    "would",
    "yeah",
    "yes",
    "you",
    "your",
}

NUMBER_WORDS = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4,
    "five": 5,
    "six": 6,
    "seven": 7,
    "eight": 8,
    "nine": 9,
    "ten": 10,
}

SEVERE_FLAGS = {
    "generic_reasoning",
    "closing_mishandled",
    "possible_slot_error",
    "excessive_chunking",
    "fragment_chunk",
}

FLAG_PENALTIES = {
    "generic_reasoning": 0.20,
    "excessive_chunking": 0.15,
    "fragment_chunk": 0.15,
    "copied_source_response": 0.15,
    "closing_mishandled": 0.15,
    "short_answer": 0.10,
    "weak_context": 0.10,
    "low_specificity": 0.10,
    "possible_slot_error": 0.10,
    "too_many_skips": 0.05,
    "no_skip_labels": 0.05,
}


def clean_text(value: Any, max_chars: int = 420) -> str:
    if value is None:
        return ""
    if isinstance(value, (list, tuple)):
        value = " ".join(clean_text(item, max_chars=max_chars) for item in value)
    text = str(value)
    text = text.replace("_comma_", ",")
    text = text.replace("\r", " ").replace("\n", " ").replace("\t", " ")
    text = text.replace("\u2019", "'").replace("\u2018", "'")
    text = text.replace("\u201c", '"').replace("\u201d", '"')
    text = re.sub(r"<[^>]{1,40}>", " ", text)
    text = re.sub(r"\b(Mr|Mrs|Ms|Dr)\s+\.", r"\1.", text)
    text = re.sub(r"\b([A-Za-z])\s+'\s+([A-Za-z])", r"\1'\2", text)
    text = re.sub(r"\s+([,.!?;:])", r"\1", text)
    text = re.sub(r"\s+", " ", text).strip()
    text = re.sub(r"\b[\w.+-]+@[\w-]+\.[\w.-]+\b", "[email removed]", text)
    text = re.sub(r"\b(?:\+?\d[\d .()-]{7,}\d)\b", "[phone removed]", text)
    if len(text) > max_chars:
        cut = text[:max_chars].rsplit(" ", 1)[0].strip()
        text = f"{cut}."
    return text


def normalize(text: str) -> str:
    return re.sub(r"\W+", " ", text.lower()).strip()


def word_count(text: str) -> int:
    return len(re.findall(r"\b[\w'-]+\b", str(text)))


def tokenize_words(text: str) -> list[str]:
    return re.findall(r"[a-zA-Z][a-zA-Z'-]{2,}", text.lower())


def salient_terms(text: str, limit: int = 5) -> list[str]:
    terms: list[str] = []
    for word in tokenize_words(text):
        word = word.strip("'")
        if word not in STOPWORDS and word not in terms:
            terms.append(word)
        if len(terms) >= limit:
            break
    return terms


def compact_join(items: list[str], fallback: str = "") -> str:
    unique = [item for idx, item in enumerate(items) if item and item not in items[:idx]]
    if not unique:
        return fallback
    if len(unique) == 1:
        return unique[0]
    return ", ".join(unique[:-1]) + f", {unique[-1]}"


def finish_sentence(text: str) -> str:
    text = clean_text(text, max_chars=500)
    if text and text[-1] not in ".!?":
        text += "."
    return text


def read_jsonl(path: Path) -> list[dict[str, Any]]:
    rows: list[dict[str, Any]] = []
    if not path.exists():
        return rows
    with path.open("r", encoding="utf-8") as handle:
        for line in handle:
            line = line.strip()
            if line:
                rows.append(json.loads(line))
    return rows


def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("w", encoding="utf-8") as handle:
        for row in rows:
            handle.write(json.dumps(row, ensure_ascii=False) + "\n")


def parse_context_chunks(row: dict[str, Any]) -> list[str]:
    chunks = row.get("context_chunks")
    if isinstance(chunks, list):
        return [clean_text(chunk, max_chars=420) for chunk in chunks if clean_text(chunk)]
    parsed: list[str] = []
    for line in str(row.get("context") or "").splitlines():
        match = re.match(r"\s*Chunk\s+\d+\s*:\s*(.+)$", line)
        if match:
            parsed.append(clean_text(match.group(1), max_chars=420))
    return parsed


def load_source_rows(output_dir: Path) -> tuple[list[dict[str, Any]], list[dict[str, str]]]:
    CACHE_DIR.mkdir(parents=True, exist_ok=True)
    if SOURCE_CACHE.exists():
        return read_jsonl(SOURCE_CACHE), []
    local_rows = read_jsonl(output_dir / "data" / "train.jsonl") + read_jsonl(output_dir / "data" / "eval.jsonl")
    if local_rows:
        write_jsonl(SOURCE_CACHE, local_rows)
        return local_rows, [{"name": "local output", "reason": "v0.2 cache was missing; used local dataset rows"}]
    try:
        from datasets import load_dataset

        ds = load_dataset(REPO_ID)
        rows: list[dict[str, Any]] = []
        for split in ds:
            for row in ds[split]:
                rows.append(dict(row))
        if rows:
            write_jsonl(SOURCE_CACHE, rows)
            return rows, []
    except Exception as exc:  # noqa: BLE001
        return [], [{"name": REPO_ID, "reason": f"could not load existing dataset: {type(exc).__name__}"}]
    return [], [{"name": "source rows", "reason": "no local or remote source rows available"}]


def build_context(chunks: list[str]) -> str:
    return "\n".join(f"Chunk {idx}: {chunk}" for idx, chunk in enumerate(chunks, start=1))


def protect_abbreviations(text: str) -> str:
    for abbr in ["Mr.", "Mrs.", "Ms.", "Dr.", "Prof.", "St."]:
        text = text.replace(abbr, abbr.replace(".", "<prd>"))
    return text


def restore_abbreviations(text: str) -> str:
    return text.replace("<prd>", ".")


def split_plain_sentences(text: str) -> list[str]:
    text = clean_text(text, max_chars=700)
    if not text:
        return []
    protected = protect_abbreviations(text)
    pieces = re.split(r"(?<=[.!?])\s+|;\s+", protected)
    out: list[str] = []
    for piece in pieces:
        piece = restore_abbreviations(piece)
        piece = clean_text(piece, max_chars=320).strip(" ,;")
        if piece:
            out.append(finish_sentence(piece))
    return out or [finish_sentence(text)]


def skip_reason_for_text(text: str) -> str | None:
    lower = normalize(text)
    raw = text.lower()
    if not lower:
        return "low_information"
    strong_info = re.search(
        r"\b(address|phone|postcode|post code|reference|book|booking|reserve|restaurant|hotel|train|taxi|attraction|museum|cost|fee|travel time|can i|get|could you|would you)\b",
        raw,
    )
    if re.search(r"\b(that'?s all|that is all|that will be all|all i need(?:ed)?|everything i need(?:ed)?|that should be it|will be all|that was all i needed)\b", raw):
        return None if strong_info else "closing_only"
    if lower in {"hi", "hello", "hey", "good morning", "good afternoon", "good evening"}:
        return "greeting_only"
    if re.fullmatch(r"(great\s+)?thanks( so much)?( a lot)?( for your help( today)?)?", lower):
        return "thanks_only"
    if re.match(r"^(thank you|thanks|no thanks|no thank you|awesome thanks|great thanks)\b", lower) and not strong_info:
        return "thanks_only"
    if lower in {"goodbye", "bye", "see you", "see you later", "have a nice day", "have a great day"}:
        return "closing_only"
    if lower in {"ok", "okay", "alright", "sure", "sounds good", "fine", "got it", "really", "who", "what", "wow"}:
        return "backchannel_only" if lower in {"ok", "okay", "alright", "sure", "sounds good", "fine", "got it"} else "low_information"
    if lower in {"um", "uh", "hmm", "well", "let me see"}:
        return "filler_only"
    if lower in {"youre welcome", "you re welcome", "you're welcome", "you are welcome"}:
        return "acknowledgement_only"
    if re.fullmatch(r"(please|sorry|excuse me)[.!]?", raw.strip()):
        return "politeness_only"
    if word_count(text) <= 2 and not re.search(r"\b(book|yes|no|where|when|phone|address|cost|fee)\b", raw):
        return "low_information"
    return None


def is_closing_or_thanks(text: str) -> bool:
    return skip_reason_for_text(text) in {"thanks_only", "closing_only", "politeness_only"}


def is_meaningful_short_chunk(text: str) -> bool:
    lower = normalize(text)
    return lower in {"yes", "no", "ok", "okay", "thanks", "bye", "hello", "hi"} or bool(re.search(r"\b(stop|wait|leave|book|call|go|pay|wash|rinse|wipe|unplug)\b", lower))


def is_fragment_chunk(text: str) -> bool:
    stripped = clean_text(text, max_chars=80).strip()
    if not stripped:
        return True
    wc = word_count(stripped)
    if wc == 0:
        return True
    if wc <= 2 and re.fullmatch(r"[\W_]+", stripped):
        return True
    if re.fullmatch(r"(Mr|Mrs|Ms|Dr|Prof)\.?", stripped):
        return True
    if normalize(stripped) == "macmillan":
        return True
    if skip_reason_for_text(stripped) or is_meaningful_short_chunk(stripped):
        return False
    if wc <= 2 and re.fullmatch(r"[A-Z][a-z]+\.?", stripped):
        return True
    return False


def merge_fragments(chunks: list[str]) -> tuple[list[str], bool]:
    merged: list[str] = []
    changed = False
    prefix = ""
    for chunk in chunks:
        chunk = clean_text(chunk, max_chars=360)
        if not chunk:
            continue
        if is_fragment_chunk(chunk):
            changed = True
            if merged:
                merged[-1] = finish_sentence(merged[-1].rstrip(".!?") + " " + chunk.strip())
            else:
                prefix = f"{prefix} {chunk}".strip()
            continue
        if prefix:
            chunk = finish_sentence(prefix + " " + chunk)
            prefix = ""
        if word_count(chunk) < 4 and merged and not is_meaningful_short_chunk(chunk):
            changed = True
            merged[-1] = finish_sentence(merged[-1].rstrip(".!?") + " " + chunk)
        else:
            merged.append(finish_sentence(chunk))
    if prefix and merged:
        merged[-1] = finish_sentence(merged[-1].rstrip(".!?") + " " + prefix)
    return merged, changed


def split_on_conjunctions(text: str, domain: str) -> list[str]:
    text = clean_text(text, max_chars=700)
    if word_count(text) <= 30:
        return [finish_sentence(text)]
    patterns = [r",\s+and\s+I\s+", r"\s+and\s+I\s+", r",\s+then\s+", r"\s+then\s+", r"\s+before\s+"]
    if domain == "emotional_support":
        patterns.extend([r"\s+because\s+", r",\s+but\s+", r"\s+but\s+"])
    regex = "|".join(f"(?:{pattern})" for pattern in patterns)
    pieces = [clean_text(piece, max_chars=260).strip(" ,;") for piece in re.split(regex, text) if clean_text(piece)]
    if len(pieces) <= 1:
        return [finish_sentence(text)]
    merged, _ = merge_fragments([finish_sentence(piece) for piece in pieces if word_count(piece) >= 3])
    return merged or [finish_sentence(text)]


def contains_term(text: str, term: str) -> bool:
    if " " in term:
        return term in text
    return bool(re.search(rf"\b{re.escape(term)}\b", text))


def extract_task_details(text: str) -> dict[str, list[str]]:
    if is_closing_or_thanks(text):
        return {}
    lower = text.lower()
    details: dict[str, list[str]] = defaultdict(list)
    domain_terms = {
        "restaurant": ["restaurant", "food", "eat", "dinner", "lunch", "breakfast", "cuisine"],
        "hotel": ["hotel", "guesthouse", "guest house", "room", "stay", "lodging"],
        "taxi": ["taxi", "cab", "pickup", "pick me up"],
        "train": ["train", "rail", "station"],
        "attraction": ["museum", "park", "theatre", "theater", "attraction", "gallery", "college", "arts"],
        "hospital": ["hospital", "clinic"],
    }
    for label, terms in domain_terms.items():
        if any(contains_term(lower, term) for term in terms):
            details["domain"].append(label)
    if re.search(r"\b(find|looking for|look for|need|want|search|assist|help|getting|get me)\b", lower):
        details["goal"].append("search")
    if re.search(r"\b(book|booking|reservation|reserve)\b", lower):
        details["goal"].append("booking")
    if re.search(r"\b(recommend|suggest|favorite|what about|how about)\b", lower):
        details["goal"].append("recommendation")
    if re.search(r"\b(different|another|alternative|instead|else)\b", lower):
        details["goal"].append("compare_alternative")
    if re.search(r"\b(change|switch|make it|same price|same pricerange|same area)\b", lower):
        details["goal"].append("modify_constraint")
    if re.search(r"\b(can i|get|give me|tell me|what is|what's|how much|phone|address|postcode|reference|travel time|fee|cost)\b", lower):
        details["goal"].append("request_info")
    if re.search(r"\b(yes|that works|perfect|sounds good|that will be fine)\b", lower) and re.search(r"\b(book|reservation|option|one)\b", lower):
        details["goal"].append("confirm_booking")
    for price in ["cheap", "moderate", "expensive", "affordable", "budget", "not too expensive", "same pricerange", "same price"]:
        if price in lower:
            details["price"].append("affordable" if price == "budget" else price.replace("same pricerange", "same price range"))
    for area in ["north", "south", "east", "west", "centre", "center", "downtown", "campus"]:
        if re.search(rf"\b{re.escape(area)}\b", lower):
            details["area"].append("centre" if area == "center" else area)
    for cuisine in ["italian", "chinese", "indian", "korean", "thai", "french", "mexican", "japanese", "british", "vegetarian", "seafood", "danish", "persian", "european", "turkish"]:
        if re.search(rf"\b{cuisine}\b", lower):
            details["food"].append(cuisine)
    for day in ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", "tomorrow"]:
        if re.search(rf"\b{day}\b", lower):
            details["day"].append(day)
    if re.search(r"\btoday\b", lower) and not is_closing_or_thanks(text):
        details["day"].append("today")
    for match in re.finditer(r"\b\d{1,2}(?::\d{2})?\s?(?:am|pm)?\b", lower):
        token = match.group(0).strip()
        window = lower[max(0, match.start() - 28) : min(len(lower), match.end() + 28)]
        if ":" in token or "am" in token or "pm" in token or re.search(r"\b(at|after|before|around|by|leave|arrive|time|starting)\b", window):
            details["time"].append(token)
    people_match = re.search(r"\b(?:for|party of|it would be|there will be|we are)\s+(\d+)\s+(?:people|guests|persons)\b", lower)
    if people_match:
        details["party_size"].append(f"{people_match.group(1)} people")
    else:
        bare_people_match = re.search(r"\b(\d+)\s+(?:people|guests|persons)\b", lower)
        if bare_people_match:
            details["party_size"].append(f"{bare_people_match.group(1)} people")
    if not details.get("party_size"):
        phrase_match = re.search(r"\bfor\s+the\s+(\w+)\s+of\s+us\b", lower)
        if phrase_match and phrase_match.group(1) in NUMBER_WORDS:
            details["party_size"].append(f"{NUMBER_WORDS[phrase_match.group(1)]} people")
    if not details.get("party_size"):
        for word, number in NUMBER_WORDS.items():
            if re.search(rf"\b{word}\b[^.?!]{{0,20}}\b(people|guests|of us)\b", lower):
                details["party_size"].append(f"{number} people")
                break
    stay_match = re.search(r"\b(\d+)\s+nights?\b", lower)
    if stay_match:
        details["stay_length"].append(f"{stay_match.group(1)} nights")
    star_match = re.search(r"\b(\d+)\s*stars?\b", lower)
    if star_match:
        details["stars"].append(f"{star_match.group(1)} stars")
    for amenity in ["parking", "wifi", "internet", "free parking", "pool", "breakfast"]:
        if amenity in lower:
            details["amenities"].append(amenity)
    if "guesthouse" in lower or "guest house" in lower:
        details["hotel_type"].append("guesthouse")
    if "hotel" in lower:
        details["hotel_type"].append("hotel")
    route_match = re.search(r"\bfrom\s+(.+?)\s+(?:to|going to)\s+([^,.?]+)", lower)
    if route_match:
        details["departure"].append(re.sub(r"\b(going|on|at|after|before)\b.*$", "", route_match.group(1)).strip())
        destination = re.sub(r"\b(on|at|after|before)\b.*$", "", route_match.group(2)).strip()
        details["destination"].append(destination)
    depart_match = re.search(r"\bdepart(?:ing)? from\s+([^,.?]+)", lower)
    if depart_match:
        details["departure"].append(depart_match.group(1).strip())
    dest_match = re.search(r"\b(?:going to|heading to|arrive at|to)\s+([A-Z]?[a-z][^,.?]{2,40})", text)
    if dest_match and " from " not in lower and " to " not in lower[:8]:
        candidate = clean_text(dest_match.group(1), max_chars=60).lower()
        if not any(stop in candidate for stop in ["get ", "see ", "help", "book"]):
            details["destination"].append(candidate)
    if "no area preference" in lower or "any area" in lower:
        details["area"].append("any")
    if re.search(r"\bpark\b", lower):
        details["domain"].append("attraction")
        details["type"].append("park")
    info_map = [
        ("address", "address"),
        ("phone", "phone"),
        ("telephone", "phone"),
        ("postcode", "postcode"),
        ("post code", "postcode"),
        ("postal code", "postcode"),
        ("reference", "reference_number"),
        ("travel time", "travel_time"),
        ("entrance fee", "entrance_fee"),
        ("admission", "entrance_fee"),
        ("cost", "price"),
        ("price", "price"),
        ("recommendation", "recommendation"),
    ]
    requestish = bool(re.search(r"\b(can you|could you|tell me|give me|what is|what's|how much|how long|need|need a|need an|i'll need|get a|get the)\b", lower))
    for needle, label in info_map:
        if re.search(rf"\b{re.escape(needle)}\b", lower):
            always_info = label in {"phone", "address", "postcode", "reference_number", "travel_time", "entrance_fee"}
            if always_info or requestish:
                details["requested_info"].append(label)
    if re.search(r"\bhow long\b.*\b(journey|trip|travel|take)\b|\bjourney take\b", lower):
        details["requested_info"].append("travel_time")
    if re.search(r"\bfine arts?\b", lower):
        details["type"].append("fine_arts_museum")
    if re.search(r"\bsports?\b", lower):
        details["type"].append("sports")
    return {key: list(dict.fromkeys(values)) for key, values in details.items()}


def semantic_split_task(text: str) -> list[str]:
    if is_closing_or_thanks(text):
        return split_plain_sentences(text)
    details = extract_task_details(text)
    slot_count = sum(len(values) for key, values in details.items() if key not in {"goal"})
    if word_count(text) >= 18 and slot_count >= 4:
        chunks: list[str] = []
        domains = details.get("domain", [])
        if "restaurant" in domains:
            desc = " ".join(part for part in [details.get("price", [""])[0], details.get("food", [""])[0], "restaurant"] if part)
            chunks.append(f"I want to find a {desc}.")
        elif "hotel" in domains:
            desc = " ".join(part for part in [details.get("price", [""])[0], details.get("hotel_type", ["hotel"])[0]] if part)
            chunks.append(f"I want to find a {desc}.")
        elif domains:
            chunks.append(f"I need help with {domains[0]}.")
        if details.get("area"):
            chunks.append(f"It should be in the {details['area'][0]} part of town.")
        if details.get("party_size"):
            chunks.append(f"It is for {details['party_size'][0]}.")
        if details.get("day") or details.get("time"):
            when = compact_join(details.get("day", []) + details.get("time", []))
            chunks.append(f"The time is {when}.")
        if details.get("goal") and "booking" in details["goal"]:
            chunks.append("Please make a booking.")
        for info in details.get("requested_info", []):
            chunks.append(f"I also need the {info.replace('_', ' ')}.")
        if len(chunks) >= 2:
            return chunks
    out: list[str] = []
    for sentence in split_plain_sentences(text):
        if word_count(sentence) > 30:
            out.extend(split_on_conjunctions(sentence, "task_oriented_assistant"))
        else:
            out.append(sentence)
    return out


def semantic_split_emotional(text: str) -> list[str]:
    text = clean_text(text, max_chars=700)
    if word_count(text) <= 25:
        return split_plain_sentences(text)
    pieces = re.split(r"(?<=[.!?])\s+|,\s+and\s+I\s+|\s+and\s+I\s+|,\s+because\s+|\s+because\s+|,\s+but\s+|\s+but\s+", text, flags=re.IGNORECASE)
    pieces = [finish_sentence(piece.strip(" ,;")) for piece in pieces if word_count(piece) >= 4]
    return pieces if len(pieces) > 1 else split_plain_sentences(text)


def semantic_split_daily(text: str) -> list[str]:
    out: list[str] = []
    for sentence in split_plain_sentences(text):
        if word_count(sentence) > 30:
            out.extend(split_on_conjunctions(sentence, "daily_dialogue"))
        else:
            out.append(sentence)
    return out


def semantic_split_how_to(text: str) -> list[str]:
    text = clean_text(text, max_chars=700)
    if text.lower().startswith("task:") or word_count(text) <= 30:
        return [finish_sentence(text)]
    pieces = re.split(r"(?<=[.!?])\s+|;\s+|,\s+then\s+|,\s+before\s+|\s+then\s+|\s+before\s+", text, flags=re.IGNORECASE)
    pieces = [finish_sentence(piece.strip(" ,;")) for piece in pieces if word_count(piece) >= 4]
    return pieces if len(pieces) > 1 else [finish_sentence(text)]


def semantic_split_utterance(text: str, domain: str) -> tuple[list[str], bool]:
    text = clean_text(text, max_chars=700)
    if not text:
        return [], False
    if domain == "task_oriented_assistant":
        chunks = semantic_split_task(text)
    elif domain == "emotional_support":
        chunks = semantic_split_emotional(text)
    elif domain == "how_to_guidance":
        chunks = semantic_split_how_to(text)
    else:
        chunks = semantic_split_daily(text)
    merged, changed = merge_fragments(chunks)
    return merged or [finish_sentence(text)], changed


def detect_emotion(text: str) -> str:
    lower = text.lower()
    rules = [
        ("proud", ["proud", "accomplished", "achievement", "graduated", "promotion"]),
        ("happy", ["happy", "excited", "glad", "thrilled", "relieved", "wonderful"]),
        ("stressed", ["stressed", "stress", "overwhelmed", "burned out", "too much", "busy"]),
        ("anxious", ["anxious", "nervous", "panic", "afraid", "scared", "scary", "freaked", "embarrassing", "embarrassed"]),
        ("worried", ["worried", "worry", "concerned"]),
        ("sad", ["sad", "upset", "cry", "heartbroken", "grief"]),
        ("disappointed", ["disappointed", "let down", "failed", "badly", "poorly"]),
        ("frustrated", ["frustrated", "furious", "angry", "mad", "annoyed"]),
        ("lonely", ["lonely", "alone", "miss her", "miss him", "miss them"]),
        ("confused", ["confused", "unsure", "not sure", "don't know", "dont know"]),
    ]
    for label, words in rules:
        if any(word in lower for word in words):
            return label
    return "neutral"


def clean_cause_phrase(phrase: str) -> str:
    phrase = clean_text(phrase, max_chars=180).strip(" .")
    phrase = re.sub(r"^(i am|i'm|i feel|i felt|i get|i was|because|when|after)\s+", "", phrase, flags=re.IGNORECASE)
    phrase = re.sub(r"\b(stressed|anxious|worried|sad|happy|excited|disappointed|frustrated|furious|angry|lonely|confused|proud|scared|scary|embarrassed|embarrassing)\b", "", phrase, flags=re.IGNORECASE)
    phrase = re.sub(r"\bi\s+(?:was|am|feel|felt)\s*$", "", phrase, flags=re.IGNORECASE)
    phrase = re.sub(r"\s+", " ", phrase).strip(" ,.")
    words = phrase.split()
    if len(words) > 12:
        phrase = " ".join(words[:12])
    return phrase


def extract_emotional_cause(text: str) -> str:
    lower = text.lower()
    if re.search(r"\b(that must have been|i bet you|you'll be fine|did they|what game|what language|would'?ve freaked|would have freaked)\b", lower):
        return ""
    won_match = re.search(r"\bwhen\s+(.+?)\s+i\s+(?:was|felt)\s+(?:happy|excited|proud|glad|thrilled)\b", text, flags=re.IGNORECASE)
    if won_match:
        phrase = clean_cause_phrase(won_match.group(1))
        if word_count(phrase) >= 3:
            return phrase
    patterns = [
        r"\bbecause\s+(.+?)(?:[.!?]|$)",
        r"\bafter\s+(.+?)(?:[.!?]|$)",
        r"\bwhen\s+(.+?)(?:[.!?]|$)",
        r"\babout\s+(.+?)(?:[.!?]|$)",
    ]
    for pattern in patterns:
        match = re.search(pattern, text, flags=re.IGNORECASE)
        if match:
            phrase = clean_cause_phrase(match.group(1))
            if word_count(phrase) >= 3:
                return phrase
    if re.search(r"\bstudied\b.*\b(exam|test)\b", lower):
        return "studied hard but the exam went poorly"
    if re.search(r"\bcar\b.{0,40}\b(died|broke down|stopped)\b", lower):
        return "car broke down at night"
    if re.search(r"\btripped\b", lower):
        return "tripped in front of other people"
    if re.search(r"\bforeign language class\b", lower):
        return "worried about a required foreign language class"
    if re.search(r"\bspeak it in front of others\b", lower):
        return "worried about speaking in front of others"
    if re.search(r"\btime\b.*\b(flying|goes by|faster)\b", lower):
        return "time seems to be passing quickly"
    if re.search(r"\bvacation request\b", lower):
        return "vacation request may be denied"
    if re.search(r"\b(passed away|died)\b", lower) and not re.search(r"\b(car|phone|battery|engine|lights?)\b", lower):
        return "someone important passed away"
    if re.search(r"\bfriend|relationship|family|brother|sister|parent|grandmother|grandpa\b", lower):
        return clean_cause_phrase(text) or "a relationship or family situation"
    phrase = clean_cause_phrase(text)
    if word_count(phrase) >= 3 and re.search(r"\b(i|my|we|our)\b", lower) and detect_emotion(text) != "neutral":
        return phrase
    return ""


def detect_user_need(text: str, emotion: str, cause: str) -> str:
    lower = text.lower()
    if re.search(r"\b(what should|how do|how can|advice|help me|catch up|plan)\b", lower):
        return "planning_help" if "plan" in lower or "catch up" in lower else "practical_next_step"
    if "?" in text:
        return "clarification"
    if emotion in {"happy", "proud"}:
        return "celebration"
    if emotion in {"anxious", "worried", "confused"}:
        return "reassurance"
    if emotion in {"sad", "disappointed", "frustrated", "lonely", "stressed"}:
        return "validation"
    return "encouragement" if cause else "validation"


def classify_chunk(chunk: str, previous_chunks: list[str], domain: str, state: dict[str, Any]) -> tuple[str, str]:
    lower = chunk.lower().strip()
    base_skip = skip_reason_for_text(chunk)
    if re.fullmatch(r"(okay|ok)[.!]?", lower):
        return "skip", base_skip or "backchannel_only"
    if re.fullmatch(r"(yes|yeah|yep|sure|sounds good)[.!]?", lower):
        if state.get("proposal_pending") or state.get("booking_intent") or "book" in " ".join(previous_chunks).lower():
            return "reason", "booking_confirmation" if domain == "task_oriented_assistant" else "decision_point"
        return "skip", base_skip or "acknowledgement_only"
    if re.fullmatch(r"(no|nope|nah)[.!]?", lower):
        if state.get("proposal_pending") or state.get("booking_intent") or re.search(r"\b(anything else|more|book|confirm)\b", " ".join(previous_chunks).lower()):
            return "reason", "decision_point"
        return "skip", "acknowledgement_only"
    if base_skip:
        return "skip", base_skip
    terms = salient_terms(chunk, 5)
    seen = set(state.get("seen_terms", []))
    if terms and set(terms).issubset(seen) and word_count(chunk) <= 26:
        return "skip", "repeated_information"
    if domain == "task_oriented_assistant":
        details = extract_task_details(chunk)
        if details.get("goal") or details.get("domain") or details.get("requested_info"):
            return "reason", details.get("goal", ["new_constraint"])[0]
        return "reason", "new_constraint"
    if domain == "emotional_support":
        emotion = detect_emotion(chunk)
        if emotion != "neutral":
            return "reason", "new_emotion"
        if extract_emotional_cause(chunk):
            return "reason", "new_cause"
        return "reason", "new_request" if "?" in chunk else "task_progress_update"
    if domain == "how_to_guidance":
        return "reason", "safety_or_order_constraint" if re.search(r"\b(turn off|unplug|avoid|careful|before|do not|don't)\b", lower) else "task_progress_update"
    return "reason", "daily_state_update"


def state_add(state: dict[str, Any], key: str, values: list[str]) -> list[str]:
    state.setdefault(key, [])
    added: list[str] = []
    for value in values:
        if value and value not in state[key]:
            state[key].append(value)
            added.append(value)
    return added


def update_seen_terms(state: dict[str, Any], chunk: str) -> None:
    seen = state.setdefault("seen_terms", [])
    for term in salient_terms(chunk, 5):
        if term not in seen:
            seen.append(term)


def task_update(chunk: str, state: dict[str, Any]) -> str:
    details = extract_task_details(chunk)
    if is_closing_or_thanks(chunk):
        state["closing_detected"] = True
        return "goal=closing"
    pieces: list[str] = []
    for key in ["domain", "goal", "area", "food", "price", "time", "day", "party_size", "stay_length", "hotel_type", "stars", "amenities", "destination", "departure", "requested_info", "type"]:
        added = state_add(state, key, details.get(key, []))
        if not added:
            continue
        label = "cuisine" if key == "food" else key
        if key == "goal" and "booking" in added:
            state["booking_intent"] = True
        if key == "requested_info":
            pieces.append(f"requested_info+={compact_join(added)}")
        elif key == "domain":
            pieces.append(f"domain={added[-1]}")
        elif key == "goal":
            pieces.append(f"goal={added[-1]}")
        else:
            pieces.append(f"{label}+={compact_join(added)}")
    if re.search(r"\b(yes|perfect|sounds good|that works|that will be fine)\b", chunk.lower()):
        if state.get("booking_intent"):
            pieces.append("goal=confirm_booking")
        else:
            pieces.append("acceptance=selected_option")
    if "not picky" in chunk.lower() or "isn't important" in chunk.lower():
        pieces.append("preference=flexible")
    if not pieces:
        if "?" in chunk:
            pieces.append("goal=request_info")
        elif re.search(r"\b(no|not|instead|second thought)\b", chunk.lower()):
            pieces.append("goal=modify_constraint")
        else:
            pieces.append("intent=context_update")
    return "; ".join(pieces)


def emotional_update(chunk: str, state: dict[str, Any]) -> str:
    emotion = detect_emotion(chunk)
    cause = extract_emotional_cause(chunk)
    need = detect_user_need(chunk, emotion, cause)
    pieces: list[str] = []
    if emotion != "neutral":
        state["emotion"] = emotion
        pieces.append(f"emotion={emotion}")
    if cause and (not state.get("cause") or emotion != "neutral" or cause.startswith("worried about speaking")):
        state["cause"] = cause
        if emotion in {"happy", "proud"}:
            pieces.append(f"event={cause}")
        else:
            pieces.append(f"cause={cause}")
    stable_needs = {"reassurance", "celebration", "planning_help", "practical_next_step"}
    if (
        need
        and need != state.get("user_need")
        and (emotion != "neutral" or cause or not state.get("user_need"))
        and not (emotion == "neutral" and state.get("user_need") in stable_needs and need in {"encouragement", "validation"})
    ):
        state["user_need"] = need
        pieces.append(f"need={need}")
    if not pieces:
        return "support_signal=received"
    return "; ".join(pieces)


def daily_label_and_value(chunk: str, state: dict[str, Any]) -> str:
    lower = chunk.lower()
    if re.search(r"\b(drive safely|safe drive|icy roads?|ice on the roads?|be careful)\b", lower):
        state["safety_reminder"] = True
        return "safety_reminder=icy_roads" if "ice" in lower or "icy" in lower else "safety_reminder=true"
    if re.search(r"\b(have to|must|had better|need to)\s+(go|leave|head off|be going)\b|\bi'?m afraid i have to go\b", lower):
        state["closing"] = True
        return "leaving_reason=needs_to_go"
    dinner_plan = re.search(r"\b(?:i'?m|i am|we'?re|we are)\s+(?:meeting|going to meet)\s+(.+?)\s+for\s+dinner\b", lower)
    if dinner_plan:
        person = clean_text(dinner_plan.group(1), max_chars=50).replace("my ", "")
        state["plan_update"] = True
        return f"plan_update=dinner_with_{normalize(person).replace(' ', '_') or 'someone'}"
    if re.search(r"\b(would you like(?:\s+to|\s+a|\s+some)?|do you want to|want to come|invite you|join me|come with me)\b", lower):
        state["proposal_pending"] = True
        state["invitation"] = True
        return "invitation=true"
    if re.search(r"\b(can you|could you|may i|would you)\b", lower) or "?" in chunk:
        state["question"] = True
        return "question=true"
    if re.search(r"\b(i'll keep it in mind|keep that in mind|thanks for the advice|advice)\b", lower):
        state["advice_received"] = True
        return "advice_received=true"
    if re.search(r"\b(can't|cannot|busy|appointment|schedule conflict|have to work|at work|in class)\b", lower):
        state["schedule_conflict"] = True
        return "schedule_conflict=true"
    if re.search(r"\b(yes|sure|sounds good|why not|ok|okay)\b", lower) and state.get("proposal_pending"):
        state["acceptance"] = True
        return "acceptance=true"
    if re.search(r"\b(no|can't|cannot|not possible)\b", lower) and state.get("proposal_pending"):
        state["refusal"] = True
        return "refusal=true"
    if re.search(r"\b(prefer|like|would rather|favorite)\b", lower):
        state["preference"] = True
        return "preference=true"
    if is_closing_or_thanks(chunk):
        state["closing"] = True
        return "closing=true"
    terms = salient_terms(chunk, 3)
    state_add(state, "casual_terms", terms[:2])
    return f"casual_comment={compact_join(terms[:2], 'context')}"


def action_label(chunk: str) -> str:
    text = re.sub(r"^Task:\s*", "", clean_text(chunk, max_chars=180), flags=re.IGNORECASE)
    text = re.sub(r"[•*]+", " ", text)
    words = text.strip(" .").split()
    if not words:
        return "continue"
    return "_".join(re.sub(r"[^a-z0-9]+", "", word.lower()) for word in words[:4]).strip("_") or "continue"


def action_text(chunk: str, max_words: int = 10) -> str:
    text = re.sub(r"^Task:\s*", "", clean_text(chunk, max_chars=260), flags=re.IGNORECASE)
    text = re.sub(r"[•*]+", " ", text)
    text = re.sub(r"\([^)]{0,80}\)", " ", text)
    text = re.sub(r"\s+", " ", text).strip(" .;:-")
    return " ".join(text.split()[:max_words]) or "continue"


def how_to_update(chunk: str, state: dict[str, Any], idx: int) -> str:
    lower = chunk.lower()
    if lower.startswith("task:") or (idx == 1 and not state.get("task")):
        state["task"] = action_label(chunk)
        state["task_text"] = action_text(chunk, 8)
        return f"task={state['task']}"
    label = action_label(chunk)
    state_add(state, "steps", [label])
    state_add(state, "step_texts", [action_text(chunk)])
    if re.search(r"\b(turn off|unplug|avoid|careful|before|do not|don't|must)\b", lower):
        state_add(state, "safety", [label])
        return f"step={label}; safety=true"
    return f"step={label}"


def build_reasoning(domain: str, chunks: list[str]) -> tuple[str, str, list[str], list[int], dict[str, str], dict[str, Any]]:
    state: dict[str, Any] = {}
    parts: list[str] = []
    labels: list[str] = []
    skip_chunks: list[int] = []
    skip_reasons: dict[str, str] = {}
    previous: list[str] = []
    for idx, chunk in enumerate(chunks, start=1):
        label, reason = classify_chunk(chunk, previous, domain, state)
        if label == "skip":
            labels.append("skip")
            skip_chunks.append(idx)
            skip_reasons[str(idx)] = reason
            if reason in {"closing_only", "thanks_only"}:
                state["closing_detected" if domain == "task_oriented_assistant" else "closing"] = True
            parts.append(f"C{idx} [SKIP: {reason}].")
        else:
            labels.append("reason")
            if domain == "task_oriented_assistant":
                update = task_update(chunk, state)
            elif domain == "emotional_support":
                update = emotional_update(chunk, state)
            elif domain == "how_to_guidance":
                update = how_to_update(chunk, state, idx)
            else:
                update = daily_label_and_value(chunk, state)
            parts.append(f"C{idx} {update}.")
        update_seen_terms(state, chunk)
        previous.append(chunk)
    streaming = " ".join(parts)
    deep = build_deep_reasoning(domain, state, chunks)
    return streaming, deep, labels, skip_chunks, skip_reasons, state


def build_deep_reasoning(domain: str, state: dict[str, Any], chunks: list[str]) -> str:
    if domain == "task_oriented_assistant":
        bits: list[str] = []
        if state.get("domain"):
            bits.append(f"domain={compact_join(state['domain'])}")
        if state.get("goal"):
            bits.append(f"goal={compact_join(state['goal'])}")
        for key in ["area", "food", "price", "party_size", "stay_length", "stars", "amenities", "destination", "departure", "requested_info"]:
            if state.get(key):
                bits.append(f"{key}={compact_join(state[key])}")
        when = state.get("day", []) + state.get("time", [])
        if when:
            bits.append(f"when={compact_join(when)}")
        if state.get("closing_detected"):
            bits.append("closing_detected")
        return "Need " + "; ".join(bits) + "." if bits else "Need more concrete task details before acting."
    if domain == "emotional_support":
        emotion = state.get("emotion", "neutral")
        cause = state.get("cause", "the situation")
        need = state.get("user_need", "validation")
        if emotion == "neutral":
            return f"User is processing {cause} and needs {need}."
        if emotion in {"happy", "proud"}:
            return f"User feels {emotion} because {cause} and needs {need}."
        return f"User feels {emotion} after {cause} and needs {need}."
    if domain == "how_to_guidance":
        task = state.get("task_text") or (state.get("task") or action_label(chunks[0] if chunks else "task")).replace("_", " ")
        steps = compact_join(state.get("step_texts", [])[:5], "ordered steps")
        safety = "; keep safety/order constraints" if state.get("safety") else ""
        return f"Procedure for {task}: {steps}{safety}."
    if state.get("safety_reminder"):
        return "Conversation is closing with a safety reminder; answer politely and acknowledge caution."
    if state.get("closing"):
        return "Conversation is closing; answer politely without adding a new task."
    daily_bits: list[str] = []
    if state.get("invitation"):
        daily_bits.append("invitation")
    if state.get("question"):
        daily_bits.append("question")
    if state.get("plan_update"):
        daily_bits.append("plan update")
    if state.get("schedule_conflict"):
        daily_bits.append("schedule conflict")
    if state.get("preference"):
        daily_bits.append("preference")
    if state.get("advice_received"):
        daily_bits.append("advice received")
    topic = compact_join(state.get("casual_terms", [])[:4], "current topic")
    if daily_bits:
        return f"Dialogue state: {compact_join(daily_bits)} around {topic}; respond briefly."
    return f"Dialogue state: casual exchange about {topic}; respond briefly."


def missing_task_slots(state: dict[str, Any]) -> list[str]:
    domains = set(state.get("domain", []))
    missing: list[str] = []
    if "restaurant" in domains:
        for key, label in [("area", "area"), ("food", "cuisine"), ("price", "price range")]:
            if not state.get(key):
                missing.append(label)
    if "hotel" in domains:
        for key, label in [("area", "area"), ("price", "price range"), ("day", "date"), ("party_size", "guests")]:
            if not state.get(key):
                missing.append(label)
    if domains & {"taxi", "train"}:
        for key, label in [("destination", "destination"), ("departure", "departure"), ("day", "date"), ("time", "time")]:
            if not state.get(key):
                missing.append(label)
    return missing[:2]


def build_task_answer(state: dict[str, Any]) -> str:
    if state.get("closing_detected"):
        return "You're welcome. Glad I could help; have a great day."
    if state.get("requested_info"):
        return f"I can help with that and include the {compact_join(state['requested_info']).replace('_', ' ')} once I find the matching option."
    missing = missing_task_slots(state)
    if missing:
        return f"What {compact_join(missing)} should I use for the search?"
    pieces = []
    if state.get("domain"):
        pieces.append(compact_join(state["domain"]))
    for key in ["area", "food", "price", "party_size"]:
        if state.get(key):
            pieces.append(compact_join(state[key]))
    if state.get("day") or state.get("time"):
        pieces.append(compact_join(state.get("day", []) + state.get("time", [])))
    return f"Got it. I will use {compact_join(pieces, 'those details')} and move the task forward."


def build_emotional_answer(state: dict[str, Any]) -> str:
    emotion = state.get("emotion", "neutral")
    cause = state.get("cause", "what happened")
    need = state.get("user_need", "validation")
    if emotion == "neutral":
        return f"That sounds like a lot to process, especially with {cause}. Start with one small next step and give yourself room to sort it out."
    if emotion in {"happy", "proud"}:
        return f"That is worth celebrating, especially because {cause}. Take a moment to enjoy it and share the good news with someone who will be happy for you."
    if need in {"planning_help", "practical_next_step"}:
        return f"That is frustrating, especially after {cause}. Start with one concrete next step, then focus your energy on the part you can control today."
    if need == "reassurance":
        return f"It makes sense to feel {emotion} after {cause}. Slow down, check what is actually known, and take one small step before deciding what comes next."
    return f"It makes sense to feel {emotion} after {cause}. Give yourself a moment, then choose one manageable action instead of trying to solve everything at once."


def build_how_to_answer(state: dict[str, Any], chunks: list[str]) -> str:
    task = state.get("task_text") or (state.get("task") or action_label(chunks[0] if chunks else "task")).replace("_", " ")
    steps = state.get("step_texts", [])[:4] or [action_text(chunk) for chunk in chunks[:4]]
    caution = " Keep the order and pause if a step seems unsafe." if state.get("safety") else ""
    return f"For {task}, follow the steps in order: {compact_join(steps)}.{caution}".strip()


def build_daily_answer(state: dict[str, Any], chunks: list[str]) -> str:
    if state.get("safety_reminder"):
        return "Thanks, I'll be careful. See you next time."
    if state.get("closing"):
        return "Sounds good. Take care, and see you next time."
    joined = " ".join(chunks).lower()
    if state.get("invitation"):
        return "That sounds nice. I can join; what time should I be there?"
    if state.get("question"):
        topic = compact_join(salient_terms(" ".join(chunks), 4), "the situation")
        return f"Good question. The main topic is {topic}, so I would answer that directly first."
    if "dinner" in joined and "meeting" in joined:
        return "Thanks, I should head out for dinner now. See you next time."
    topic = compact_join(salient_terms(" ".join(chunks), 4), "the situation")
    return f"Got it. The main point is {topic}, so I will keep the reply brief and clear."


def build_answer(domain: str, state: dict[str, Any], chunks: list[str]) -> str:
    if domain == "task_oriented_assistant":
        answer = build_task_answer(state)
    elif domain == "emotional_support":
        answer = build_emotional_answer(state)
    elif domain == "how_to_guidance":
        answer = build_how_to_answer(state, chunks)
    else:
        answer = build_daily_answer(state, chunks)
    return " ".join(re.split(r"(?<=[.!?])\s+", finish_sentence(answer))[:3]).strip()


def copied_ratio(answer: str, source_answer: str | None) -> float:
    source = normalize(source_answer or "")
    generated = normalize(answer)
    if not source or not generated:
        return 0.0
    if source in generated or generated in source:
        return 1.0
    return difflib.SequenceMatcher(None, source, generated).ratio()


def has_forbidden_phrase(*texts: str) -> bool:
    joined = "\n".join(texts).lower()
    return any(phrase in joined for phrase in FORBIDDEN_GENERIC_PHRASES)


def is_safe_example(chunks: list[str], answer: str) -> bool:
    joined = " ".join(chunks + [answer]).lower()
    if any(term in joined for term in BLOCKLIST):
        return False
    if "[email removed]" in joined or "[phone removed]" in joined:
        return False
    return sum(word_count(chunk) for chunk in chunks) >= 8 and word_count(answer) >= 3


def is_undesired_how_to(chunks: list[str]) -> bool:
    joined = " ".join(chunks).lower()
    off_topic = [
        "windows movie maker",
        "movie maker",
        "inshot",
        "pinterest",
        "ipod",
        "jailbreak",
        "slackline",
        "bonfire",
        "lighter fluid",
        "synthetic coon",
        "manga",
        "runescape",
        "minecraft",
        "photoshop",
        "illustrator",
        "html",
        "css",
        "javascript",
        "server",
        "login",
        "paypal",
        "twitter",
        "instagram",
        "tiktok",
    ]
    return any(term in joined for term in off_topic)


def compute_quality_flags(
    domain: str,
    chunks: list[str],
    labels: list[str],
    state: dict[str, Any],
    source_answer: str | None,
    streaming_reasoning: str,
    deep_reasoning: str,
    answer: str,
    merged_fragments: bool,
) -> list[str]:
    flags: list[str] = []
    if word_count(streaming_reasoning) > 160:
        flags.append("long_streaming_reasoning")
    if word_count(deep_reasoning) > 60:
        flags.append("long_deep_reasoning")
    if any(skip_reason_for_text(chunk) for chunk in chunks) and "skip" not in labels:
        flags.append("no_skip_labels")
    if labels and labels.count("skip") / len(labels) > 0.70:
        flags.append("too_many_skips")
    avg_chunk_words = statistics.mean(word_count(chunk) for chunk in chunks) if chunks else 0
    if avg_chunk_words < 4 or len(chunks) > 12:
        flags.append("excessive_chunking")
    if any(is_fragment_chunk(chunk) for chunk in chunks):
        flags.append("fragment_chunk")
    if merged_fragments:
        flags.append("merged_fragments")
    if has_forbidden_phrase(streaming_reasoning, deep_reasoning, answer):
        flags.append("generic_reasoning")
    if copied_ratio(answer, source_answer) >= 0.72:
        flags.append("copied_source_response")
    if word_count(answer) < 5:
        flags.append("short_answer")
    if len(chunks) < 2 or sum(word_count(chunk) for chunk in chunks) < 12:
        flags.append("weak_context")
    if is_closing_or_thanks(" ".join(chunks)) and "today" in state.get("day", []):
        flags.append("possible_slot_error")
    if (state.get("closing_detected") or state.get("closing")) and re.search(r"\?|please confirm|what .*should|share .*", answer.lower()):
        flags.append("closing_mishandled")
    if domain == "task_oriented_assistant" and not any(state.get(key) for key in ["domain", "goal", "requested_info", "destination", "departure"]):
        flags.append("low_specificity")
    if domain == "emotional_support" and re.search(r"\b[a-z]+,\s+[a-z]+,\s+[a-z]+", deep_reasoning.lower()):
        flags.append("generic_reasoning")
    return list(dict.fromkeys(flags))


def compute_state_tracking_confidence(domain: str, state: dict[str, Any], flags: list[str]) -> float:
    score = 0.85
    if domain == "task_oriented_assistant":
        if state.get("domain"):
            score += 0.06
        if state.get("goal"):
            score += 0.05
        if state.get("requested_info"):
            score += 0.03
    elif domain == "emotional_support":
        if state.get("emotion") and state.get("emotion") != "neutral":
            score += 0.06
        if state.get("cause"):
            score += 0.05
        if state.get("user_need"):
            score += 0.03
    elif domain == "daily_dialogue":
        if state.get("closing") or state.get("safety_reminder") or state.get("proposal_pending"):
            score += 0.04
    else:
        if state.get("steps"):
            score += 0.06
    score -= 0.05 * len([flag for flag in flags if flag in SEVERE_FLAGS])
    return round(max(0.0, min(1.0, score)), 3)


def compute_quality_score(flags: list[str], streaming_reasoning: str, deep_reasoning: str) -> float:
    score = 1.0
    for flag in set(flags):
        score -= FLAG_PENALTIES.get(flag, 0.0)
    if word_count(streaming_reasoning) > 120:
        score -= 0.05
    if word_count(deep_reasoning) > 45:
        score -= 0.05
    return round(max(0.0, min(1.0, score)), 3)


def is_high_quality_row(row: dict[str, Any]) -> bool:
    flags = set(row.get("quality_flags", []))
    return (
        row.get("quality_score", 0) >= 0.85
        and not (flags & SEVERE_FLAGS)
        and word_count(row.get("streaming_reasoning", "")) <= 120
        and word_count(row.get("deep_reasoning", "")) <= 45
        and not has_forbidden_phrase(row.get("streaming_reasoning", ""), row.get("deep_reasoning", ""), row.get("answer", ""))
    )


def make_response(streaming_reasoning: str, deep_reasoning: str, answer: str) -> str:
    return f"Streaming reasoning: {streaming_reasoning}\n\nDeep reasoning: {deep_reasoning}\n\nAnswer: {answer}"


def make_messages(instruction: str, context: str, response: str) -> list[dict[str, str]]:
    return [
        {"role": "user", "content": f"Instruction: {instruction}\n\nContext:\n{context}"},
        {"role": "assistant", "content": response},
    ]


def make_text(messages: list[dict[str, str]]) -> str:
    return f"<|user|>\n{messages[0]['content']}\n<|assistant|>\n{messages[1]['content']}"


def transform_row(row: dict[str, Any]) -> dict[str, Any] | None:
    domain = str(row.get("domain") or "daily_dialogue")
    source_dataset = str(row.get("source_dataset") or "local_source")
    original_chunks = parse_context_chunks(row)
    if len(original_chunks) < 2:
        return None
    chunks: list[str] = []
    merged_fragments = False
    for chunk in original_chunks:
        split_chunks, changed = semantic_split_utterance(chunk, domain)
        chunks.extend(split_chunks)
        merged_fragments = merged_fragments or changed
    chunks, changed = merge_fragments(chunks)
    merged_fragments = merged_fragments or changed
    chunks = [clean_text(chunk, max_chars=340) for chunk in chunks if clean_text(chunk)]
    if len(chunks) < 2:
        return None
    if len(chunks) > 13:
        chunks = chunks[:13]
    if domain == "how_to_guidance" and is_undesired_how_to(chunks):
        return None
    streaming, deep, labels, skip_chunks, skip_reasons, state = build_reasoning(domain, chunks)
    answer = build_answer(domain, state, chunks)
    if not is_safe_example(chunks, answer):
        return None
    flags = compute_quality_flags(domain, chunks, labels, state, row.get("answer"), streaming, deep, answer, merged_fragments)
    quality_score = compute_quality_score(flags, streaming, deep)
    confidence = compute_state_tracking_confidence(domain, state, flags)
    context = build_context(chunks)
    response = make_response(streaming, deep, answer)
    messages = make_messages(INSTRUCTION, context, response)
    example = {
        "id": "",
        "domain": domain,
        "source_dataset": source_dataset,
        "instruction": INSTRUCTION,
        "context": context,
        "context_chunks": chunks,
        "streaming_reasoning": streaming,
        "deep_reasoning": deep,
        "answer": answer,
        "response": response,
        "messages": messages,
        "text": make_text(messages),
        "num_chunks": len(chunks),
        "language": "en",
        "split": "",
        "generation_method": GENERATION_METHOD,
        "quality_flags": flags,
        "version": DATASET_VERSION,
        "reasoning_policy": REASONING_POLICY,
        "chunking_method": CHUNKING_METHOD,
        "chunk_labels": labels,
        "skip_chunks": skip_chunks,
        "skip_reasons": skip_reasons,
        "reasoning_token_budget": REASONING_TOKEN_BUDGET,
        "original_num_chunks": len(original_chunks),
        "chunk_split_count": max(0, len(chunks) - len(original_chunks)),
        "quality_score": quality_score,
        "is_high_quality": False,
        "refinement_method": REFINEMENT_METHOD,
        "llm_augmented": False,
        "llm_augmentation_model": None,
        "rejected_reason": None,
        "state_tracking_confidence": confidence,
    }
    example["is_high_quality"] = is_high_quality_row(example)
    return example


def select_source_rows(rows: list[dict[str, Any]], max_examples: int, seed: int) -> list[dict[str, Any]]:
    groups: dict[str, list[dict[str, Any]]] = defaultdict(list)
    for row in rows:
        groups[str(row.get("domain") or "daily_dialogue")].append(row)
    rng = random.Random(seed)
    for group in groups.values():
        rng.shuffle(group)
    selected: list[dict[str, Any]] = []
    domains = sorted(groups)
    index = 0
    while len(selected) < max_examples:
        added = False
        for domain in domains:
            if index < len(groups[domain]):
                selected.append(groups[domain][index])
                added = True
                if len(selected) >= max_examples:
                    break
        if not added:
            break
        index += 1
    return selected


def deduplicate(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
    seen_texts: set[str] = set()
    unique: list[dict[str, Any]] = []
    for row in rows:
        key = normalize(row["text"])
        if not key or key in seen_texts:
            continue
        seen_texts.add(key)
        unique.append(row)
    return unique


def assign_ids_and_splits(rows: list[dict[str, Any]], seed: int) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
    rng = random.Random(seed)
    rng.shuffle(rows)
    split_at = max(1, int(len(rows) * 0.8))
    train_rows = rows[:split_at]
    eval_rows = rows[split_at:]
    if not eval_rows and len(train_rows) > 1:
        eval_rows = [train_rows.pop()]
    domain_counts: Counter[str] = Counter()
    for split_name, split_rows in [("train", train_rows), ("eval", eval_rows)]:
        for row in split_rows:
            domain_counts[row["domain"]] += 1
            slug = re.sub(r"[^a-z0-9]+", "_", row["domain"].lower()).strip("_")
            row["id"] = f"life_{slug}_{domain_counts[row['domain']]:06d}"
            row["split"] = split_name
            row["messages"] = make_messages(row["instruction"], row["context"], row["response"])
            row["text"] = make_text(row["messages"])
    return train_rows, eval_rows


def select_review_samples(rows: list[dict[str, Any]], sample_size: int = 120) -> list[dict[str, Any]]:
    by_domain: dict[str, list[dict[str, Any]]] = defaultdict(list)
    for row in rows:
        by_domain[row["domain"]].append(row)
    selected: list[dict[str, Any]] = []
    seen: set[str] = set()
    per_domain = 30
    for domain in ["task_oriented_assistant", "emotional_support", "daily_dialogue", "how_to_guidance"]:
        candidates = by_domain.get(domain, [])
        buckets = [
            [row for row in candidates if row.get("is_high_quality")],
            [row for row in candidates if row.get("skip_chunks")],
            [row for row in candidates if row.get("quality_flags")],
            candidates,
        ]
        picked = 0
        for bucket in buckets:
            for row in bucket:
                if row["id"] in seen:
                    continue
                selected.append(row)
                seen.add(row["id"])
                picked += 1
                if picked >= per_domain:
                    break
            if picked >= per_domain:
                break
    for row in rows:
        if len(selected) >= sample_size:
            break
        if row["id"] not in seen:
            selected.append(row)
            seen.add(row["id"])
    sample_fields = [
        "id",
        "domain",
        "context_chunks",
        "chunk_labels",
        "skip_reasons",
        "streaming_reasoning",
        "deep_reasoning",
        "answer",
        "quality_flags",
        "quality_score",
        "is_high_quality",
        "refinement_method",
        "split",
    ]
    return [{field: row.get(field) for field in sample_fields} for row in selected[:sample_size]]


def write_parquet(path: Path, rows: list[dict[str, Any]]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    pd.DataFrame(rows, columns=REQUIRED_FIELDS).to_parquet(path, index=False)


def source_summary(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
    counts = Counter(row["source_dataset"] for row in rows)
    domains: dict[str, set[str]] = defaultdict(set)
    for row in rows:
        domains[row["source_dataset"]].add(row["domain"])
    return [{"name": source, "domain": ",".join(sorted(domains[source])), "rows": count} for source, count in sorted(counts.items())]


def quality_counts(rows: list[dict[str, Any]]) -> dict[str, int]:
    return dict(sorted(Counter(flag for row in rows for flag in row.get("quality_flags", [])).items()))


def avg(values: list[float]) -> float:
    return statistics.mean(values) if values else 0.0


def build_dataset_info(train_rows: list[dict[str, Any]], eval_rows: list[dict[str, Any]], hq_train: list[dict[str, Any]], hq_eval: list[dict[str, Any]], skipped_sources: list[dict[str, str]]) -> dict[str, Any]:
    rows = train_rows + eval_rows
    total_chunks = sum(row["num_chunks"] for row in rows)
    skip_chunks = sum(len(row["skip_chunks"]) for row in rows)
    return {
        "dataset_name": DATASET_NAME,
        "repo_id": REPO_ID,
        "version": DATASET_VERSION,
        "created_by": "skyzhou06 with Codex",
        "generation_method": GENERATION_METHOD,
        "reasoning_policy": REASONING_POLICY,
        "chunking_method": CHUNKING_METHOD,
        "refinement_method": REFINEMENT_METHOD,
        "schema": {field: "required" for field in REQUIRED_FIELDS},
        "source_datasets_used": source_summary(rows),
        "skipped_source_datasets": skipped_sources,
        "total_rows": len(rows),
        "train_rows": len(train_rows),
        "eval_rows": len(eval_rows),
        "high_quality_train_rows": len(hq_train),
        "high_quality_eval_rows": len(hq_eval),
        "domains": dict(sorted(Counter(row["domain"] for row in rows).items())),
        "average_num_chunks": avg([row["num_chunks"] for row in rows]),
        "average_chunk_length": avg([word_count(chunk) for row in rows for chunk in row["context_chunks"]]),
        "average_original_num_chunks": avg([row["original_num_chunks"] for row in rows]),
        "average_chunk_split_count": avg([row["chunk_split_count"] for row in rows]),
        "average_streaming_reasoning_words": avg([word_count(row["streaming_reasoning"]) for row in rows]),
        "average_deep_reasoning_words": avg([word_count(row["deep_reasoning"]) for row in rows]),
        "average_quality_score": avg([row["quality_score"] for row in rows]),
        "high_quality_percentage": (len(hq_train) + len(hq_eval)) / len(rows) if rows else 0,
        "skip_chunk_ratio": skip_chunks / total_chunks if total_chunks else 0,
        "examples_with_at_least_one_skip": sum(1 for row in rows if row["skip_chunks"]),
        "quality_flags_distribution": quality_counts(rows),
        "llm_augmented_count": sum(1 for row in rows if row.get("llm_augmented")),
        "limitations": [
            "v0.4 is primarily rule-based unless optional LLM augmentation is run.",
            "The high-quality subset is recommended for serious SFT experiments.",
            "Some source datasets are dialogue-style and may not perfectly match ideal assistant behavior.",
            "The dataset is not intended for expert medical, legal, financial, emergency, or safety-critical advice.",
        ],
        "samples_for_review": "samples_for_review.jsonl",
    }


def dataset_card(info: dict[str, Any], example: dict[str, Any] | None) -> str:
    used = "\n".join(f"- `{item['name']}`: {item['rows']} rows, domain `{item['domain']}`" for item in info["source_datasets_used"]) or "- None"
    skipped = "\n".join(f"- `{item['name']}`: {item['reason']}" for item in info["skipped_source_datasets"]) or "- None"
    flags = "\n".join(f"- `{flag}`: {count}" for flag, count in info["quality_flags_distribution"].items()) or "- None"
    example_json = json.dumps(example or {}, ensure_ascii=False, indent=2)
    schema = "\n".join(f"- `{field}`" for field in REQUIRED_FIELDS)
    return f"""---
pretty_name: LifeStreamingCoT
language:
- en
license: apache-2.0
version: "{DATASET_VERSION}"
task_categories:
- text-generation
tags:
- streaming-reasoning
- selective-reasoning
- quality-refined
- supervised-fine-tuning
- sft
- dialogue
- task-oriented-dialogue
- life-assistant
- streamingthinker
size_categories:
- 1K<n<10K
---

# LifeStreamingCoT

Current version: v0.4: Quality-Refined Selective Streaming Reasoning

LifeStreamingCoT is a text-only, life-scenario adaptation of StreamingCoT-style data for StreamingThinker-style supervised fine-tuning. It keeps compatibility with earlier LifeStreamingCoT schemas while adding quality metadata and high-quality subset files.

## Version 0.4: Quality Refinement

v0.3 introduced selective concise streaming reasoning, semantic chunk splitting, skip labels, and chunk-level metadata. v0.4 improves quality by fixing keyword-stitching in emotional support examples, reducing daily-dialogue intent mistakes, replacing vague task-oriented updates, reducing fragment chunks, and adding `quality_score` plus `is_high_quality`.

v0.4 also provides high-quality subset files:

- `data/train_high_quality.jsonl`
- `data/eval_high_quality.jsonl`
- `data/train_high_quality.parquet`
- `data/eval_high_quality.parquet`

## Version History

| Version | Summary |
| --- | --- |
| v0.1 | Schema-complete source-grounded baseline |
| v0.2 | More specific rule-based reasoning and quality flags |
| v0.3 | Selective concise reasoning, skip labels, semantic chunking |
| v0.4 | Quality refinement, quality scores, high-quality subset |

## Recommended Usage

Full dataset:

```python
from datasets import load_dataset
ds = load_dataset("skyzhou06/LifeStreamingCoT")
```

Quality filtering:

```python
clean = ds.filter(lambda x: x["is_high_quality"] and x["quality_score"] >= 0.85)
```

Removing flagged data:

```python
clean = ds.filter(lambda x: len(x["quality_flags"]) == 0)
```

## Schema

{schema}

## Source Datasets

Used sources:

{used}

Skipped sources:

{skipped}

## Splits

- Train: {info['train_rows']}
- Eval: {info['eval_rows']}
- Total: {info['total_rows']}
- High-quality train: {info['high_quality_train_rows']}
- High-quality eval: {info['high_quality_eval_rows']}

## Statistics

- Average chunks: {info['average_num_chunks']:.2f}
- Average chunk length: {info['average_chunk_length']:.2f}
- Average streaming reasoning words: {info['average_streaming_reasoning_words']:.2f}
- Average deep reasoning words: {info['average_deep_reasoning_words']:.2f}
- Average quality score: {info['average_quality_score']:.3f}
- High-quality percentage: {info['high_quality_percentage']:.2%}
- Skip chunk ratio: {info['skip_chunk_ratio']:.4f}
- LLM augmented rows: {info['llm_augmented_count']}

## Quality Flags

{flags}

## Example

```json
{example_json}
```

## Limitations

- Still primarily rule-based unless optional LLM augmentation is run.
- Not expert advice.
- Some source datasets are dialogue-style and may not perfectly match assistant behavior.
- The high-quality subset is recommended for serious SFT experiments.
"""


def print_stats(rows: list[dict[str, Any]], train_rows: list[dict[str, Any]], eval_rows: list[dict[str, Any]], hq_train: list[dict[str, Any]], hq_eval: list[dict[str, Any]], skipped: list[dict[str, str]], llm_status: str) -> None:
    total_chunks = sum(row["num_chunks"] for row in rows)
    skip_chunks = sum(len(row["skip_chunks"]) for row in rows)
    print("\nBuild stats")
    print(f"total examples: {len(rows)}")
    print(f"train examples: {len(train_rows)}")
    print(f"eval examples: {len(eval_rows)}")
    print(f"high-quality train examples: {len(hq_train)}")
    print(f"high-quality eval examples: {len(hq_eval)}")
    print(f"domains: {dict(sorted(Counter(row['domain'] for row in rows).items()))}")
    print(f"source datasets: {dict(Counter(row['source_dataset'] for row in rows))}")
    print(f"average chunks: {avg([row['num_chunks'] for row in rows]):.2f}")
    print(f"average chunk length: {avg([word_count(chunk) for row in rows for chunk in row['context_chunks']]):.2f}")
    print(f"average streaming reasoning words: {avg([word_count(row['streaming_reasoning']) for row in rows]):.2f}")
    print(f"average deep reasoning words: {avg([word_count(row['deep_reasoning']) for row in rows]):.2f}")
    print(f"average quality score: {avg([row['quality_score'] for row in rows]):.3f}")
    print(f"high-quality percentage: {(len(hq_train) + len(hq_eval)) / len(rows) if rows else 0:.2%}")
    print(f"skip chunk ratio: {skip_chunks / total_chunks if total_chunks else 0:.4f}")
    print(f"quality flags: {quality_counts(rows)}")
    print(f"llm augmentation: {llm_status}")
    print(f"skipped source datasets: {skipped}")


def sync_scripts_to_dataset(output_dir: Path) -> None:
    script_dir = Path(__file__).resolve().parent
    target = output_dir / "scripts"
    target.mkdir(parents=True, exist_ok=True)
    for name in ["build_life_streaming_cot.py", "validate_dataset.py", "upload_to_hf.py", "augment_with_llm.py", "analyze_quality.py"]:
        src = script_dir / name
        if src.exists():
            shutil.copy2(src, target / name)


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--output-dir", default="life_streaming_cot_dataset")
    parser.add_argument("--max-examples", type=int, default=10000)
    parser.add_argument("--smoke-test", action="store_true")
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument("--llm-augment", action="store_true", help="Reserved hook for optional LLM augmentation.")
    args = parser.parse_args()

    output_dir = Path(args.output_dir)
    data_dir = output_dir / "data"
    data_dir.mkdir(parents=True, exist_ok=True)
    max_examples = min(args.max_examples, 300 if args.smoke_test else args.max_examples)

    source_rows, skipped_sources = load_source_rows(output_dir)
    if not source_rows:
        raise RuntimeError("No source rows were available.")
    source_rows = select_source_rows(source_rows, max_examples=max_examples * 5, seed=args.seed)

    rows: list[dict[str, Any]] = []
    for source_row in source_rows:
        example = transform_row(source_row)
        if example:
            rows.append(example)
            if len(rows) >= max_examples:
                break
    rows = deduplicate(rows)
    if len(rows) > max_examples:
        rows = rows[:max_examples]
    if len(rows) < min(5000, max_examples) and not args.smoke_test:
        raise RuntimeError(f"Only {len(rows)} examples were produced; expected at least {min(5000, max_examples)}.")
    if len(rows) < 10:
        raise RuntimeError("Fewer than 10 examples were produced.")

    llm_available = bool(os.getenv("OPENAI_API_KEY") or os.getenv("OPENAI_BASE_URL") or os.getenv("LOCAL_LLM_BASE_URL"))
    if args.llm_augment and llm_available:
        llm_status = "available but not run in build script; use scripts/augment_with_llm.py for explicit augmentation"
    elif args.llm_augment:
        llm_status = "skipped: no supported API key or local model endpoint found"
    else:
        llm_status = "skipped: optional LLM augmentation was not requested"

    train_rows, eval_rows = assign_ids_and_splits(rows, args.seed)
    all_rows = train_rows + eval_rows
    hq_train = [row for row in train_rows if row["is_high_quality"]]
    hq_eval = [row for row in eval_rows if row["is_high_quality"]]

    write_jsonl(data_dir / "train.jsonl", train_rows)
    write_jsonl(data_dir / "eval.jsonl", eval_rows)
    write_jsonl(data_dir / "train_high_quality.jsonl", hq_train)
    write_jsonl(data_dir / "eval_high_quality.jsonl", hq_eval)
    write_parquet(data_dir / "train.parquet", train_rows)
    write_parquet(data_dir / "eval.parquet", eval_rows)
    write_parquet(data_dir / "train_high_quality.parquet", hq_train)
    write_parquet(data_dir / "eval_high_quality.parquet", hq_eval)
    write_jsonl(output_dir / "samples_for_review.jsonl", select_review_samples(all_rows, sample_size=120))

    info = build_dataset_info(train_rows, eval_rows, hq_train, hq_eval, skipped_sources)
    (output_dir / "dataset_info.json").write_text(json.dumps(info, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    (output_dir / "README.md").write_text(dataset_card(info, hq_train[0] if hq_train else train_rows[0]), encoding="utf-8")
    (output_dir / "requirements.txt").write_text(Path("requirements.txt").read_text(encoding="utf-8"), encoding="utf-8")
    sync_scripts_to_dataset(output_dir)
    print_stats(all_rows, train_rows, eval_rows, hq_train, hq_eval, skipped_sources, llm_status)


if __name__ == "__main__":
    main()