File size: 103,840 Bytes
d739b1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');

function filterAndCapGraphData(nodes, edges, safeParse) {
  const MAX_NODES = 5000;
  const MAX_EDGES = 10000;

  let finalNodes = nodes;
  if (finalNodes.length > MAX_NODES) {
    const typePriority = { 'session': 0, 'wiki': 1, 'note': 1, 'tool': 2, 'file': 3, 'code': 4, 'library': 5 };
    finalNodes.sort((a, b) => {
      const priA = typePriority[a.type] !== undefined ? typePriority[a.type] : 6;
      const priB = typePriority[b.type] !== undefined ? typePriority[b.type] : 6;
      return priA - priB;
    });
    finalNodes = finalNodes.slice(0, MAX_NODES);
  }

  const nodeIds = new Set(finalNodes.map(n => n.id));
  let finalEdges = edges.filter(e => nodeIds.has(e.source) && nodeIds.has(e.target));
  if (finalEdges.length > MAX_EDGES) {
    finalEdges = finalEdges.slice(0, MAX_EDGES);
  }

  return {
    nodes: finalNodes.map(n => ({ ...n, properties: safeParse(n.properties) })),
    edges: finalEdges.map(e => ({ ...e, properties: safeParse(e.properties) }))
  };
}

class SqliteDb {
  constructor(db) {
    this.db = db;
    this.attachedDbs = new Set();
    this.initTables();
  }

  getDecisionGate(id) { return require('./decision-gate-record').decode(this.db.prepare('SELECT gate_json FROM decision_gates WHERE id = ?').get(id)?.gate_json); }
  // docs/specs/bong-ui-artifacts.md v1.0.0. snapshot과 할당량을 같은 SQLite 트랜잭션에 고정한다.
  getUiArtifact(projectId,id){const r=require('./ui-artifact-record');r.query(projectId,id);return r.read(this.db.prepare('SELECT data_json FROM ui_artifacts WHERE project_id=? AND id=?').get(projectId,id)?.data_json,projectId,id);}
  listUiArtifacts(projectId){const r=require('./ui-artifact-record');r.query(projectId);return this.db.prepare('SELECT id,data_json FROM ui_artifacts WHERE project_id=? ORDER BY rowid DESC LIMIT 33').all(projectId).map(v=>r.read(v.data_json,projectId,v.id));}
  saveUiArtifact(projectId,value){return this.db.transaction(()=>{const r=require('./ui-artifact-record'),next=r.read(value,projectId,value.id),old=this.getUiArtifact(projectId,next.id);if(old){if(old.hash!==next.hash)r.fail();return old;}r.quota(this.listUiArtifacts(projectId),next);this.db.prepare('INSERT INTO ui_artifacts(project_id,id,data_json) VALUES (?,?,?)').run(projectId,next.id,JSON.stringify(next));return next;})();}
  deleteUiArtifact(projectId,id,hash){return this.db.transaction(()=>{const old=this.getUiArtifact(projectId,id);if(!old||old.hash!==hash)require('./ui-artifact-record').fail();this.db.prepare('DELETE FROM ui_artifacts WHERE project_id=? AND id=?').run(projectId,id);})();}
  listDecisionGates() { return this.db.prepare('SELECT gate_json FROM decision_gates ORDER BY rowid DESC LIMIT 100').all().map(row => require('./decision-gate-record').decode(row.gate_json)); }
  saveDecisionGate(gate, expectedRevision = null) {
    return this.db.transaction(() => {
      const records = require('./decision-gate-record');
      const next = records.prepare(gate, this.getDecisionGate(gate.id), expectedRevision);
      if (expectedRevision === null) this.db.prepare('INSERT INTO decision_gates (id, revision, gate_json) VALUES (?, ?, ?)').run(next.id, next.revision, JSON.stringify(next));
      else if (this.db.prepare('UPDATE decision_gates SET revision = ?, gate_json = ? WHERE id = ? AND revision = ?').run(next.revision, JSON.stringify(next), next.id, expectedRevision).changes !== 1) throw records.conflict();
      return next;
    })();
  }

  getRuntimeUsage(id) { return require('./runtime-usage-record').decode(this.db.prepare('SELECT data_json FROM runtime_usage WHERE run_id = ?').get(id)?.data_json); }
  getBatchCheckpoint(id) { return require('./batch-checkpoint-record').decode(this.db.prepare('SELECT data_json FROM batch_checkpoints WHERE run_id=?').get(id)?.data_json); }
  // 원래 checkpoint와 분리한 알림 journal: docs/specs/batch-publication-review.md v1.0.0
  getBatchLoopPublicationActions(runId) { return require('./batch-publication-action-record').decode(this,runId,this.db.prepare('SELECT data_json FROM batch_publication_actions WHERE run_id=?').get(runId)?.data_json); }
  appendBatchLoopPublicationAction(runId,value,expectedHash,verify) { return this.db.transaction(()=>{const next=require('./batch-publication-action-record').append(this,runId,value,this.getBatchLoopPublicationActions(runId),expectedHash,verify);this.db.prepare('INSERT INTO batch_publication_actions(run_id,data_json) VALUES (?,?) ON CONFLICT(run_id) DO UPDATE SET data_json=excluded.data_json').run(runId,JSON.stringify(next));return next;})(); }
  getBatchLoopObservations(runId,eventKey) { return require('./batch-loop-observation-record').decode(this,runId,eventKey,this.db.prepare('SELECT data_json FROM batch_loop_observations WHERE run_id=? AND event_key=?').get(runId,eventKey)?.data_json); }
  hasBatchLoopObservations(runId) { if(typeof runId!=='string'||!/^[-\w]{1,256}$/.test(runId))throw Error('Invalid batch run ID');return !!this.db.prepare('SELECT 1 FROM batch_loop_observations WHERE run_id=? LIMIT 1').get(runId); }
  appendBatchLoopObservation(runId,eventKey,value,expectedHash) { return this.db.transaction(()=>{const next=require('./batch-loop-observation-record').append(this,runId,eventKey,value,this.getBatchLoopObservations(runId,eventKey),expectedHash);this.db.prepare('INSERT INTO batch_loop_observations(run_id,event_key,data_json) VALUES (?,?,?) ON CONFLICT(run_id,event_key) DO UPDATE SET data_json=excluded.data_json').run(runId,eventKey,JSON.stringify(next));return next;})(); }
  saveBatchCheckpoint(record,revision=null,verify) { return this.db.transaction(()=>{const next=require('./batch-checkpoint-record').prepare(record,this.getBatchCheckpoint(record.runId),revision,verify);this.db.prepare('INSERT INTO batch_checkpoints (run_id,data_json) VALUES (?,?) ON CONFLICT(run_id) DO UPDATE SET data_json=excluded.data_json').run(next.runId,JSON.stringify(next));return next;})(); }
  transitionBatchRun(id,expected,status) { return this.db.transaction(()=>{const row=this.getBatchRun(id),hash=require('../services/bong-browser-resolution').hash;if(!['paused','running','aborted'].includes(status)||hash(row)!==hash(expected)||['running','aborted'].includes(status)&&row?.status!=='paused'||status==='paused'&&!['failed','aborted'].includes(row?.status))throw Error('Batch continuation row changed');const result=this.db.prepare('UPDATE batch_runs SET status=?,error_message=?,completed_at=? WHERE run_id=?').run(status,status==='aborted'?'사용자 복구 준비 철회':null,status==='aborted'?new Date().toISOString():null,id);if(result.changes!==1)throw Error('Batch continuation row missing');return this.getBatchRun(id);})(); }
  getGoalProcedure(projectId,id){require('./goal-state-record').query(projectId,id);return require('./goal-procedure-record').read(this.db.prepare('SELECT data_json FROM goal_procedures WHERE project_id=? AND id=?').get(projectId,id)?.data_json,projectId,id);}
  listGoalProcedures(projectId,limit=20){require('./goal-state-record').query(projectId);if(!Number.isSafeInteger(limit)||limit<1||limit>21)throw Error('Invalid procedure limit');return this.db.prepare('SELECT id,data_json FROM goal_procedures WHERE project_id=? ORDER BY rowid DESC LIMIT ?').all(projectId,limit).map(r=>require('./goal-procedure-record').read(r.data_json,projectId,r.id));}
  saveGoalProcedure(projectId,id,value,revision,verify){return this.db.transaction(()=>{const r=require('./goal-procedure-record'),next=r.prepare(projectId,id,value,this.getGoalProcedure(projectId,id),revision,verify);if(revision===null){if(this.db.prepare('SELECT COUNT(*) AS count FROM goal_procedures WHERE project_id=?').get(projectId).count>=64)throw r.fail();this.db.prepare('INSERT INTO goal_procedures(project_id,id,data_json) VALUES (?,?,?)').run(projectId,id,JSON.stringify(next));}else this.db.prepare('UPDATE goal_procedures SET data_json=? WHERE project_id=? AND id=?').run(JSON.stringify(next),projectId,id);return next;})();}
  getGoalState(projectId,id) { const r=require('./goal-state-record');r.query(projectId,id);return r.decode(this.db.prepare('SELECT data_json FROM goal_states WHERE project_id=? AND id=?').get(projectId,id)?.data_json); }
  listGoalStates(projectId,limit=20) { const r=require('./goal-state-record');r.query(projectId);if(!Number.isSafeInteger(limit)||limit<1||limit>21)throw Error('Invalid goal limit');return this.db.prepare('SELECT data_json FROM goal_states WHERE project_id=? ORDER BY rowid DESC LIMIT ?').all(projectId,limit).map(row=>r.decode(row.data_json)); }
  appendGoalEvent(projectId,id,event,expectedRevision) {
    return this.db.transaction(()=>{const next=require('./goal-state-record').apply(this.getGoalState(projectId,id),projectId,id,event,expectedRevision);
      this.db.prepare('INSERT INTO goal_states (project_id,id,data_json) VALUES (?,?,?) ON CONFLICT(project_id,id) DO UPDATE SET data_json=excluded.data_json').run(projectId,id,JSON.stringify(next));require('../services/goal-event-feed').changed(this,projectId,'goal',id,next.runId,id,next.revision,next);return next;
    })();
  }
  saveRuntimeUsage(record) {
    return this.db.transaction(()=>{const json = require('./runtime-usage-record').encode(record);
    this.db.prepare('INSERT INTO runtime_usage (run_id, data_json) VALUES (?, ?) ON CONFLICT(run_id) DO UPDATE SET data_json=excluded.data_json').run(record.runId, json);require('../services/goal-event-feed').usageChanged(this,record);})();
  }

  getGoalFulfillment(projectId,id) { require('./goal-state-record').query(projectId,id);return require('./goal-fulfillment-record').decode(this.db.prepare('SELECT data_json FROM goal_fulfillments WHERE project_id=? AND id=?').get(projectId,id)?.data_json); }
  saveGoalFulfillment(projectId,id,input,revision) {
    return this.db.transaction(()=>{const next=require('./goal-fulfillment-record').prepare(this,projectId,id,input,this.getGoalFulfillment(projectId,id),revision);
      this.db.prepare('INSERT INTO goal_fulfillments (project_id,id,data_json) VALUES (?,?,?) ON CONFLICT(project_id,id) DO UPDATE SET data_json=excluded.data_json').run(projectId,id,JSON.stringify(next));require('../services/goal-event-feed').changed(this,projectId,'confirmation',id,next.confirmations.at(-1).runId,id,next.revision,next);return next;
    })();
  }
  getHarnessRunsForWorkflow(projectId,harnessId,runId) { this.getHarnessRunsForProject(projectId,harnessId,1);return this.db.prepare('SELECT * FROM harness_runs WHERE harness_id=? AND workflow_run_id=? ORDER BY created_at DESC,rowid DESC LIMIT 1').all(harnessId,runId); }

  getGoalFeed(projectId) { require('./goal-state-record').query(projectId);return require('./goal-feed-record').decode(this.db.prepare('SELECT data_json FROM goal_feeds WHERE project_id=?').get(projectId)?.data_json); }
  appendGoalFeed(projectId,event) { return this.db.transaction(()=>{const next=require('./goal-feed-record').append(this.getGoalFeed(projectId),projectId,event);this.db.prepare('INSERT INTO goal_feeds (project_id,data_json) VALUES (?,?) ON CONFLICT(project_id) DO UPDATE SET data_json=excluded.data_json').run(projectId,JSON.stringify(next));return next;})(); }

  getGoalPlanningCheckpoint(projectId,id) {
    require('./goal-state-record').query(projectId,id);
    return require('../services/goal-planning-checkpoint').decode(this.db.prepare('SELECT data_json FROM goal_planning_checkpoints WHERE project_id=? AND id=?').get(projectId,id)?.data_json);
  }
  saveGoalPlanningCheckpoint(projectId,id,value,revision) {
    return this.db.transaction(()=>{const next=require('../services/goal-planning-checkpoint').prepare(projectId,id,value,this.getGoalPlanningCheckpoint(projectId,id),revision);
      this.db.prepare('INSERT INTO goal_planning_checkpoints (project_id,id,data_json) VALUES (?,?,?) ON CONFLICT(project_id,id) DO UPDATE SET data_json=excluded.data_json').run(projectId,id,JSON.stringify(next));require('../services/goal-event-feed').changed(this,projectId,'preparation',id,null,id,next.revision,next);return next;
    })();
  }

  appendPolicyEvent(event) {
    const next=require('./policy-event-record').prepare(event);
    return this.db.transaction(()=>{
      this.db.prepare('INSERT INTO policy_events (id,project_id,data_json) VALUES (?,?,?)').run(next.id,next.projectId,JSON.stringify(next));
      this.db.prepare('DELETE FROM policy_events WHERE project_id=? AND id NOT IN (SELECT id FROM policy_events WHERE project_id=? ORDER BY rowid DESC LIMIT 1000)').run(next.projectId,next.projectId);
      return next;
    })();
  }
  listPolicyEvents(projectId,limit=20) {
    const records=require('./policy-event-record');records.query(projectId,limit);
    return this.db.prepare('SELECT data_json FROM policy_events WHERE project_id=? ORDER BY rowid DESC LIMIT ?').all(projectId,limit).map(row=>records.prepare(JSON.parse(row.data_json)));
  }

  initTables() {
    this.db.prepare('CREATE TABLE IF NOT EXISTS batch_publication_actions (run_id TEXT PRIMARY KEY,data_json TEXT NOT NULL)').run();
    this.db.prepare('CREATE TABLE IF NOT EXISTS batch_loop_observations (run_id TEXT NOT NULL,event_key TEXT NOT NULL,data_json TEXT NOT NULL,PRIMARY KEY(run_id,event_key))').run();
    this.db.prepare('CREATE TABLE IF NOT EXISTS ui_artifacts (project_id TEXT NOT NULL,id TEXT NOT NULL,data_json TEXT NOT NULL,PRIMARY KEY(project_id,id))').run();
    this.db.prepare('CREATE TABLE IF NOT EXISTS goal_feeds (project_id TEXT PRIMARY KEY,data_json TEXT NOT NULL)').run();
    this.db.prepare('CREATE TABLE IF NOT EXISTS goal_procedures (project_id TEXT NOT NULL,id TEXT NOT NULL,data_json TEXT NOT NULL,PRIMARY KEY(project_id,id))').run();
    this.db.prepare('CREATE TABLE IF NOT EXISTS goal_fulfillments (project_id TEXT NOT NULL,id TEXT NOT NULL,data_json TEXT NOT NULL,PRIMARY KEY(project_id,id))').run();
    this.db.prepare('CREATE TABLE IF NOT EXISTS goal_planning_checkpoints (project_id TEXT NOT NULL,id TEXT NOT NULL,data_json TEXT NOT NULL,PRIMARY KEY(project_id,id))').run();
    this.db.prepare('CREATE TABLE IF NOT EXISTS goal_states (project_id TEXT NOT NULL,id TEXT NOT NULL,data_json TEXT NOT NULL,PRIMARY KEY(project_id,id))').run();
    this.db.prepare('CREATE TABLE IF NOT EXISTS policy_events (id TEXT PRIMARY KEY, project_id TEXT NOT NULL, data_json TEXT NOT NULL)').run();
    this.db.prepare('CREATE INDEX IF NOT EXISTS policy_events_project ON policy_events(project_id)').run();
    this.db.prepare('CREATE TABLE IF NOT EXISTS runtime_usage (run_id TEXT PRIMARY KEY, data_json TEXT NOT NULL)').run();
    this.db.prepare('CREATE TABLE IF NOT EXISTS batch_checkpoints (run_id TEXT PRIMARY KEY, data_json TEXT NOT NULL)').run();
    this.db.prepare('CREATE TABLE IF NOT EXISTS decision_gates (id TEXT PRIMARY KEY, revision INTEGER NOT NULL, gate_json TEXT NOT NULL)').run();
    // 1. Nodes Table
    this.db.prepare(`
      CREATE TABLE IF NOT EXISTS nodes (
        id TEXT NOT NULL,
        project_id TEXT NOT NULL,
        type TEXT NOT NULL,
        label TEXT NOT NULL,
        properties TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id, project_id)
      )
    `).run();

    // 2. Edges Table
    this.db.prepare(`
      CREATE TABLE IF NOT EXISTS edges (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        project_id TEXT NOT NULL,
        source TEXT NOT NULL,
        target TEXT NOT NULL,
        label TEXT NOT NULL,
        properties TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        UNIQUE(project_id, source, target, label)
      )
    `).run();

    // Indexing
    this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_nodes_proj ON nodes (project_id)`).run();
    this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_edges_proj ON edges (project_id)`).run();
    this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_edges_nodes ON edges (source, target)`).run();

    // 3. FTS5 Virtual Table for nodes search
    this.db.prepare(`
      CREATE VIRTUAL TABLE IF NOT EXISTS nodes_fts USING fts5(
        id UNINDEXED,
        project_id,
        type,
        label,
        properties,
        tokenize='porter'
      )
    `).run();

    // Triggers to sync INSERT, UPDATE, DELETE to FTS5
    this.db.prepare(`
      CREATE TRIGGER IF NOT EXISTS trg_nodes_fts_insert AFTER INSERT ON nodes BEGIN
        INSERT INTO nodes_fts (id, project_id, type, label, properties)
        VALUES (new.id, new.project_id, new.type, new.label, new.properties);
      END
    `).run();

    this.db.prepare(`
      CREATE TRIGGER IF NOT EXISTS trg_nodes_fts_update AFTER UPDATE ON nodes BEGIN
        UPDATE nodes_fts SET
          id = new.id,
          project_id = new.project_id,
          type = new.type,
          label = new.label,
          properties = new.properties
        WHERE id = old.id AND project_id = old.project_id;
      END
    `).run();

    this.db.prepare(`
      CREATE TRIGGER IF NOT EXISTS trg_nodes_fts_delete AFTER DELETE ON nodes BEGIN
        DELETE FROM nodes_fts WHERE id = old.id AND project_id = old.project_id;
      END
    `).run();

    // Seed/migrate existing nodes data into FTS5 table
    this.db.prepare(`
      INSERT INTO nodes_fts (id, project_id, type, label, properties)
      SELECT id, project_id, type, label, properties FROM nodes
      WHERE NOT EXISTS (
        SELECT 1 FROM nodes_fts 
        WHERE nodes_fts.id = nodes.id AND nodes_fts.project_id = nodes.project_id
      )
    `).run();

    // 4. Batch Tasks Table
    this.db.prepare(`
      CREATE TABLE IF NOT EXISTS batch_tasks (
        id TEXT PRIMARY KEY,
        project_id TEXT NOT NULL,
        name TEXT NOT NULL,
        prompt TEXT NOT NULL,
        cron_expr TEXT NOT NULL,
        max_turns INTEGER DEFAULT 30,
        is_active INTEGER DEFAULT 0,
        steps_json TEXT,
        is_tested_success INTEGER DEFAULT 0,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
      )
    `).run();

    // Migration/Add column check for steps_json and is_tested_success
    if (!this.db.pragma('table_info(batch_tasks)').some(column => column.name === 'timezone')) {
      this.db.prepare('ALTER TABLE batch_tasks ADD COLUMN timezone TEXT').run();
    }
    if (!this.db.pragma('table_info(batch_tasks)').some(column => column.name === 'tested_fingerprint')) {
      this.db.prepare('ALTER TABLE batch_tasks ADD COLUMN tested_fingerprint TEXT').run();
    }
    try {
      const pragma = this.db.pragma("table_info(batch_tasks)");
      const hasStepsJson = pragma.some(c => c.name === 'steps_json');
      const hasIsTestedSuccess = pragma.some(c => c.name === 'is_tested_success');
      const hasLoopConfig = pragma.some(c => c.name === 'loop_config');
      if (!hasStepsJson) {
        this.db.prepare(`ALTER TABLE batch_tasks ADD COLUMN steps_json TEXT`).run();
      }
      if (!hasIsTestedSuccess) {
        this.db.prepare(`ALTER TABLE batch_tasks ADD COLUMN is_tested_success INTEGER DEFAULT 0`).run();
      }
      if (!hasLoopConfig) {
        this.db.prepare(`ALTER TABLE batch_tasks ADD COLUMN loop_config TEXT`).run();
      }
      
      const existing = this.db.prepare(`SELECT * FROM batch_tasks`).all();
      for (const row of existing) {
        if (!row.steps_json) {
          const steps = [{
            id: 'step_1',
            name: 'Claude Agent Task',
            type: 'pty_agent',
            config: {
              prompt: row.prompt || '',
              max_turns: row.max_turns || 30
            },
            on_failure: 'abort'
          }];
          this.db.prepare(`UPDATE batch_tasks SET steps_json = ? WHERE id = ?`).run(JSON.stringify(steps), row.id);
        }
      }
    } catch (e) {
      console.error('[KnowledgeDB] Migration of batch_tasks columns failed:', e);
    }

    // 5. Batch Runs Table
    this.db.prepare(`
      CREATE TABLE IF NOT EXISTS batch_runs (
        run_id TEXT PRIMARY KEY,
        task_id TEXT NOT NULL,
        status TEXT NOT NULL,
        started_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        completed_at DATETIME,
        log_path TEXT,
        error_message TEXT,
        FOREIGN KEY(task_id) REFERENCES batch_tasks(id) ON DELETE CASCADE
      )
    `).run();

    // 6. Workflows Table
    if (!this.db.prepare('PRAGMA table_info(batch_runs)').all().some(column => column.name === 'work_dir')) {
      this.db.prepare('ALTER TABLE batch_runs ADD COLUMN work_dir TEXT').run();
    }
    this.db.prepare(`
      CREATE TABLE IF NOT EXISTS workflows (
        id TEXT PRIMARY KEY,
        project_id TEXT NOT NULL,
        name TEXT NOT NULL,
        description TEXT,
        graph_json TEXT NOT NULL,
        is_active INTEGER DEFAULT 1,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
      )
    `).run();

    // 7. Workflow Runs Table
    this.db.prepare(`
      CREATE TABLE IF NOT EXISTS workflow_runs (
        run_id TEXT PRIMARY KEY,
        workflow_id TEXT NOT NULL,
        status TEXT NOT NULL,
        current_node_id TEXT,
        run_data TEXT NOT NULL,
        log_path TEXT,
        started_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        completed_at DATETIME,
        FOREIGN KEY(workflow_id) REFERENCES workflows(id) ON DELETE CASCADE
      )
    `).run();

    // 8. Workflow Tasks Table (SQLite Embedded Queue)
    this.db.prepare(`
      CREATE TABLE IF NOT EXISTS workflow_tasks (
        task_id TEXT PRIMARY KEY,
        run_id TEXT NOT NULL,
        node_id TEXT NOT NULL,
        agent_id TEXT NOT NULL,
        payload TEXT,
        status TEXT NOT NULL,
        result TEXT,
        error TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
      )
    `).run();

    // 9. Harnesses Table
    this.db.prepare(`
      CREATE TABLE IF NOT EXISTS harnesses (
        id TEXT PRIMARY KEY,
        project_id TEXT NOT NULL,
        name TEXT NOT NULL,
        description TEXT,
        trigger_pattern TEXT,
        validation_command TEXT NOT NULL,
        computer_use_enabled INTEGER DEFAULT 0,
        max_retries INTEGER DEFAULT 3,
        success_criteria TEXT,
        tool_chain TEXT,
        stages TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
      )
    `).run();

    // 10. Harness Runs Table
    this.db.prepare(`
      CREATE TABLE IF NOT EXISTS harness_runs (
        run_id TEXT PRIMARY KEY,
        harness_id TEXT NOT NULL,
        workflow_run_id TEXT,
        status TEXT NOT NULL,
        retry_count INTEGER DEFAULT 0,
        logs TEXT,
        tool_chain TEXT,
        stage_results TEXT,
        receipt_summary TEXT,
        definition_hash TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        completed_at DATETIME,
        FOREIGN KEY(harness_id) REFERENCES harnesses(id) ON DELETE CASCADE
      )
    `).run();

    // 11. Triage Items Table
    this.db.prepare(`
      CREATE TABLE IF NOT EXISTS triage_items (
        id TEXT PRIMARY KEY,
        project_id TEXT NOT NULL,
        run_id TEXT NOT NULL,
        source_type TEXT NOT NULL,
        error_message TEXT,
        ai_analysis TEXT,
        status TEXT DEFAULT 'pending',
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
      )
    `).run();

    // 12. Workflow Provenance Table (NiFi Data Provenance 벤치마킹)
    this.db.prepare(`
      CREATE TABLE IF NOT EXISTS workflow_provenance (
        id TEXT PRIMARY KEY,
        run_id TEXT NOT NULL,
        node_id TEXT NOT NULL,
        parent_node_ids TEXT,
        input_flow_file TEXT NOT NULL,
        output_flow_file TEXT,
        status TEXT NOT NULL,
        started_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        ended_at DATETIME,
        retry_count INTEGER DEFAULT 0,
        FOREIGN KEY(run_id) REFERENCES workflow_runs(run_id) ON DELETE CASCADE
      )
    `).run();

    // Indices for foreign keys and queries
    this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_wf_runs_wf ON workflow_runs (workflow_id)`).run();
    this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_wf_tasks_run ON workflow_tasks (run_id)`).run();
    this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_harness_runs_harness ON harness_runs (harness_id)`).run();
    this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_triage_items_proj ON triage_items (project_id)`).run();

    // Migration(B1): 기존 harnesses 테이블에 stages 컬럼 안전 추가(다단계 검증 게이트).
    // WHY: 이전 버전 DB 파일을 가진 사용자도 앱 재시작 시 자동으로 컬럼이 생겨야 한다.
    //      (batch_tasks / loop_runs 마이그레이션과 동일한 pragma("table_info")+ALTER 패턴)
    try {
      const harnessesPragma = this.db.pragma("table_info(harnesses)");
      const hasStages = harnessesPragma.some(c => c.name === 'stages');
      if (!hasStages) {
        this.db.prepare(`ALTER TABLE harnesses ADD COLUMN stages TEXT`).run();
      }
    } catch (migErr) {
      console.error('[SqliteDb] harnesses stages 마이그레이션 오류:', migErr.message);
    }

    // 화면 검증 선택이 저장 중 사라져 HTTP 검사로 바뀌지 않도록 보존한다.
    // docs/specs/remote-harness-validation.md v1.0.0
    if (!this.db.pragma('table_info(harnesses)').some(c => c.name === 'computer_use_enabled')) {
      this.db.prepare('ALTER TABLE harnesses ADD COLUMN computer_use_enabled INTEGER DEFAULT 0').run();
    }

    // Migration(B2): 기존 harness_runs 테이블에 stage_results/receipt_summary 컬럼 안전 추가.
    // WHY: 이전 버전 DB 파일을 가진 사용자도 앱 재시작 시 자동으로 컬럼이 생겨야 한다.
    //      (harnesses.stages / loop_runs.receipt_summary 마이그레이션과 동일한 pragma("table_info")+ALTER 패턴)
    try {
      const harnessRunsPragma = this.db.pragma("table_info(harness_runs)");
      if (!harnessRunsPragma.some(c=>c.name==='goal_evidence')) this.db.prepare('ALTER TABLE harness_runs ADD COLUMN goal_evidence TEXT').run();
      const hasStageResults = harnessRunsPragma.some(c => c.name === 'stage_results');
      if (!hasStageResults) {
        this.db.prepare(`ALTER TABLE harness_runs ADD COLUMN stage_results TEXT`).run();
      }
      const hasReceiptSummary = harnessRunsPragma.some(c => c.name === 'receipt_summary');
      if (!hasReceiptSummary) {
        this.db.prepare(`ALTER TABLE harness_runs ADD COLUMN receipt_summary TEXT`).run();
      }
      // 기존 성공은 NULL로 유지하며 현재 정의의 해시를 소급해서 채우지 않는다.
      // docs/specs/bong-harness-proof.md v1.0.0
      if (!harnessRunsPragma.some(c=>c.name==='definition_hash')) {
        this.db.prepare(`ALTER TABLE harness_runs ADD COLUMN definition_hash TEXT`).run();
      }
    } catch (migErr) {
      console.error('[SqliteDb] harness_runs stage_results/receipt_summary 마이그레이션 오류:', migErr.message);
    }
    this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_wf_prov_run ON workflow_provenance (run_id)`).run();
    // 같은 실행의 최신 검증만 읽는다. 과거 50건 제한 때문에 현재 근거가 사라지지 않게 한다.
    // docs/specs/bong-goal-fulfillment.md v1.0.0
    this.db.prepare('CREATE INDEX IF NOT EXISTS idx_harness_workflow ON harness_runs (harness_id,workflow_run_id,created_at)').run();

    // 13. Troubleshoot Entries Table
    this.db.prepare(`
      CREATE TABLE IF NOT EXISTS troubleshoot_entries (
        id TEXT PRIMARY KEY,
        project_id TEXT NOT NULL,
        error_pattern TEXT NOT NULL,
        error_type TEXT,
        root_cause TEXT,
        solution TEXT NOT NULL,
        affected_files TEXT,
        tags TEXT,
        hit_count INTEGER DEFAULT 1,
        last_hit_at DATETIME,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
      )
    `).run();

    // 14. Dev Preferences Table
    this.db.prepare(`
      CREATE TABLE IF NOT EXISTS dev_preferences (
        id TEXT PRIMARY KEY,
        project_id TEXT NOT NULL,
        category TEXT NOT NULL,
        preference_key TEXT NOT NULL,
        preference_value TEXT NOT NULL,
        confidence REAL DEFAULT 0.5,
        source TEXT,
        occurrence_count INTEGER DEFAULT 1,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        UNIQUE(project_id, category, preference_key)
      )
    `).run();

    this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_ts_entries_proj ON troubleshoot_entries (project_id)`).run();
    this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_dev_pref_proj ON dev_preferences (project_id)`).run();

    // 15. Favorite Prompts Table
    this.db.prepare(`
      CREATE TABLE IF NOT EXISTS favorite_prompts (
        id TEXT PRIMARY KEY,
        title TEXT NOT NULL,
        prompt_text TEXT NOT NULL,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
      )
    `).run();

    // 16. Loop Goals Table (루프 목표 정의)
    this.db.prepare(`
      CREATE TABLE IF NOT EXISTS loop_goals (
        id TEXT PRIMARY KEY,
        project_id TEXT NOT NULL,
        task_id TEXT,                    -- batch_tasks FK (nullable)
        workflow_id TEXT,                -- workflows FK (nullable)
        name TEXT NOT NULL,
        goal_expression TEXT NOT NULL,   -- 평가식 JSON
        max_iterations INTEGER DEFAULT 10,
        token_budget REAL DEFAULT 5.0,   -- USD
        max_wall_time INTEGER DEFAULT 3600,
        consecutive_failure_threshold INTEGER DEFAULT 3,
        worktree_isolation INTEGER DEFAULT 0,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
      )
    `).run();

    // 17. Loop Runs Table (루프 실행 기록)
    this.db.prepare(`
      CREATE TABLE IF NOT EXISTS loop_runs (
        run_id TEXT PRIMARY KEY,
        goal_id TEXT NOT NULL,
        parent_run_id TEXT,
        status TEXT NOT NULL,  -- running|completed|failed|circuit_broken|aborted
        total_iterations INTEGER DEFAULT 0,
        total_tokens_used INTEGER DEFAULT 0,
        total_cost REAL DEFAULT 0,
        goal_met INTEGER DEFAULT 0,
        break_reason TEXT,
        receipt_summary TEXT,
        started_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        completed_at DATETIME,
        FOREIGN KEY(goal_id) REFERENCES loop_goals(id) ON DELETE CASCADE
      )
    `).run();

    // Migration: 기존 loop_runs 테이블에 receipt_summary 컬럼 안전 추가.
    // WHY: 이전 버전 DB 파일을 가진 사용자도 앱 재시작 시 자동으로 컬럼이 생겨야 한다.
    //      (batch_tasks 마이그레이션과 동일한 pragma+ALTER 패턴)
    try {
      const loopRunsPragma = this.db.pragma("table_info(loop_runs)");
      const hasReceiptSummary = loopRunsPragma.some(c => c.name === 'receipt_summary');
      if (!hasReceiptSummary) {
        this.db.prepare(`ALTER TABLE loop_runs ADD COLUMN receipt_summary TEXT`).run();
      }
    } catch (migErr) {
      console.error('[SqliteDb] loop_runs receipt_summary 마이그레이션 오류:', migErr.message);
    }

    // 18. Loop Iterations Table (루프 이터레이션 상세 기록)
    this.db.prepare(`
      CREATE TABLE IF NOT EXISTS loop_iterations (
        id TEXT PRIMARY KEY,
        loop_run_id TEXT NOT NULL,
        iteration_number INTEGER NOT NULL,
        status TEXT NOT NULL,  -- running|success|failed
        step_outputs TEXT,     -- JSON snapshot
        goal_evaluation_result INTEGER,
        tokens_used INTEGER DEFAULT 0,
        cost REAL DEFAULT 0,
        worktree_branch TEXT,
        error_message TEXT,
        started_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        completed_at DATETIME,
        FOREIGN KEY(loop_run_id) REFERENCES loop_runs(run_id) ON DELETE CASCADE
      )
    `).run();

    // 19. Loop Messages Table (서브에이전트 메시지 로그)
    this.db.prepare(`
      CREATE TABLE IF NOT EXISTS loop_messages (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        loop_run_id TEXT NOT NULL,
        iteration_number INTEGER,
        sender_agent_id TEXT NOT NULL,
        receiver_agent_id TEXT NOT NULL,
        message_type TEXT NOT NULL,
        content TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY(loop_run_id) REFERENCES loop_runs(run_id) ON DELETE CASCADE
      )
    `).run();

    // 19-b. Loop Templates Table (프로젝트 비종속 재사용 템플릿)
    // WHY: 특정 프로젝트에서 검증된 루프 설정(목표식+파라미터+에이전트 스텝)을
    //      project_id/task_id 등 종속 필드 없이 저장해 다른 프로젝트에서 재사용(인스턴스화)한다.
    //      source_* 컬럼은 "어디서 왔는지" 참고용 기록일 뿐 종속 관계는 아니다.
    //      CREATE TABLE IF NOT EXISTS 이므로 반복 초기화에도 idempotent 하다.
    this.db.prepare(`
      CREATE TABLE IF NOT EXISTS loop_templates (
        id TEXT PRIMARY KEY,
        name TEXT NOT NULL,
        description TEXT,
        goal_expression TEXT NOT NULL,   -- 평가식 JSON (loop_goals와 동일 스키마)
        max_iterations INTEGER DEFAULT 10,
        token_budget REAL DEFAULT 5.0,   -- USD
        max_wall_time INTEGER DEFAULT 3600,
        consecutive_failure_threshold INTEGER DEFAULT 3,
        worktree_isolation INTEGER DEFAULT 0,
        steps_json TEXT,                 -- 에이전트 프롬프트/엔진/모델 스텝 (batch_tasks.steps_json 복제본)
        source_project_name TEXT,        -- 참고용: 어느 프로젝트에서 복제됐는지 기록만
        source_task_name TEXT,           -- 참고용: 원본 batch_task 이름
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
      )
    `).run();

    // 20. Worktree State Table (격리 워크트리 상태 관리)
    this.db.prepare(`
      CREATE TABLE IF NOT EXISTS worktree_state (
        id TEXT PRIMARY KEY,
        run_id TEXT NOT NULL,
        node_id TEXT NOT NULL,
        wt_path TEXT NOT NULL,
        branch_name TEXT NOT NULL,
        status TEXT NOT NULL,  -- active|merged|discarded|orphaned
        created_at TEXT DEFAULT (datetime('now', 'localtime')),
        completed_at TEXT
      )
    `).run();

    // Indices for Loop Tables
    this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_loop_runs_goal ON loop_runs(goal_id)`).run();
    this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_loop_iters_run ON loop_iterations(loop_run_id)`).run();
    this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_loop_msgs_run ON loop_messages(loop_run_id)`).run();
    this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_wt_state_run ON worktree_state(run_id)`).run();

    // 21. Headroom Metrics Table (보안 마스킹 및 감사 통계 지표)
    this.db.prepare(`
      CREATE TABLE IF NOT EXISTS headroom_metrics (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        session_id TEXT,
        provider TEXT,
        timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
        rule_id TEXT,
        rule_name TEXT,
        match_count INTEGER,
        original_tokens INTEGER,
        compressed_tokens INTEGER,
        cost_saved REAL
      )
    `).run();
    this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_headroom_metrics_rule ON headroom_metrics(rule_id)`).run();
    this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_headroom_metrics_time ON headroom_metrics(timestamp)`).run();

    // 22. Swarm Blackboard Table (SPEC-INNOV-001 v1.0.0)
    this.db.prepare(`
      CREATE TABLE IF NOT EXISTS blackboard_entries (
        entry_id TEXT PRIMARY KEY,
        project_id TEXT NOT NULL DEFAULT 'default',
        topic TEXT NOT NULL,
        author_agent TEXT NOT NULL,
        payload TEXT NOT NULL,
        salience REAL DEFAULT 0.5,
        claimed_by TEXT,
        claimed_until INTEGER,
        created_at INTEGER NOT NULL,
        updated_at INTEGER NOT NULL
      )
    `).run();
    this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_bb_topic ON blackboard_entries(project_id, topic)`).run();
    this.db.prepare(`CREATE INDEX IF NOT EXISTS idx_bb_claim ON blackboard_entries(claimed_until)`).run();
  }

  saveHeadroomMetric(metric) {
    try {
      const stmt = this.db.prepare(`
        INSERT INTO headroom_metrics (session_id, provider, rule_id, rule_name, match_count, original_tokens, compressed_tokens, cost_saved)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
      `);
      return stmt.run(
        metric.sessionId || null,
        metric.provider || null,
        metric.ruleId || null,
        metric.ruleName || null,
        metric.matchCount || 0,
        metric.originalTokens || 0,
        metric.compressedTokens || 0,
        metric.costSaved || 0.0
      );
    } catch (e) {
      console.error('[sqlite-db] Failed to saveHeadroomMetric:', e);
      return null;
    }
  }

  getHeadroomStats(days = 7) {
    const limitDays = parseInt(days, 10) || 7;
    const query = `
      SELECT 
        date(timestamp, 'localtime') as date_label,
        rule_name,
        sum(match_count) as total_matches,
        sum(original_tokens) as total_orig_tokens,
        sum(compressed_tokens) as total_comp_tokens,
        sum(cost_saved) as total_cost_saved
      FROM headroom_metrics
      WHERE timestamp >= datetime('now', '-${limitDays} days', 'localtime')
      GROUP BY date_label, rule_name
      ORDER BY date_label ASC, total_matches DESC
    `;
    try {
      return this.db.prepare(query).all();
    } catch (e) {
      console.error('[sqlite-db] Failed to getHeadroomStats:', e);
      return [];
    }
  }

  saveNode(projectId, node) {
    const propertiesStr = typeof node.properties === 'string' ? node.properties : JSON.stringify(node.properties || {});
    const stmt = this.db.prepare(`
      INSERT INTO nodes (id, project_id, type, label, properties, created_at)
      VALUES (?, ?, ?, ?, ?, ?)
      ON CONFLICT(id, project_id) DO UPDATE SET
        type = excluded.type,
        label = excluded.label,
        properties = excluded.properties
    `);
    stmt.run(node.id, projectId, node.type, node.label, propertiesStr, node.created_at || new Date().toISOString());
  }

  saveEdge(projectId, edge) {
    const propertiesStr = typeof edge.properties === 'string' ? edge.properties : JSON.stringify(edge.properties || {});
    const stmt = this.db.prepare(`
      INSERT INTO edges (project_id, source, target, label, properties, created_at)
      VALUES (?, ?, ?, ?, ?, ?)
      ON CONFLICT(project_id, source, target, label) DO UPDATE SET
        properties = excluded.properties
    `);
    stmt.run(projectId, edge.source, edge.target, edge.label, propertiesStr, edge.created_at || new Date().toISOString());
  }

  replaceVaultEdges(projectId, vaultRoot, edges) {
    return this.db.transaction(() => {
      const old = this.db.prepare('SELECT source,target,label,properties FROM edges WHERE project_id = ?').all(projectId);
      const remove = this.db.prepare('DELETE FROM edges WHERE project_id = ? AND source = ? AND target = ? AND label = ?');
      const retained = new Set();
      const key = edge => JSON.stringify([edge.source, edge.target, edge.label]);
      for (const edge of old) {
        const props = JSON.parse(edge.properties || '{}');
        if (props.owner === 'bada-vault-links-v1' && props.vaultRoot === vaultRoot) remove.run(projectId, edge.source, edge.target, edge.label);
        else retained.add(key(edge));
      }
      for (const edge of edges) if (!retained.has(key(edge))) this.saveEdge(projectId, { ...edge, properties: { owner: 'bada-vault-links-v1', vaultRoot } });
    })();
  }

  getGraphData(projectId, days) {
    const cutoff = days ? new Date(Date.now() - days * 86400000).toISOString() : null;

    // 1. 해당 프로젝트 전체 노드/엣지 로딩
    const nodes = this.db.prepare(`SELECT * FROM nodes WHERE project_id = ?`).all(projectId);
    const edges = this.db.prepare(`SELECT * FROM edges WHERE project_id = ?`).all(projectId);

    // 2. 날짜 필터링에 의한 세션 추출
    let activeSessionIdsQuery = `SELECT id FROM nodes WHERE project_id = ? AND type = 'session'`;
    const params = [projectId];
    if (cutoff) {
      activeSessionIdsQuery += ` AND created_at >= ?`;
      params.push(cutoff);
    }
    const activeSessionRows = this.db.prepare(activeSessionIdsQuery).all(...params);
    const activeSessionIds = new Set(activeSessionRows.map(r => r.id));

    if (activeSessionIds.size > 0) {
      // 세션과 연결된 엣지 및 co-modified 엣지
      const sessionEdges = edges.filter(e => 
        activeSessionIds.has(e.source) || activeSessionIds.has(e.target) || 
        (e.label === 'co-modified' && (!cutoff || !e.created_at || e.created_at >= cutoff))
      );

      // 도구 엣지가 없는 텍스트 전용 세션도 대화 조회 대상으로 남긴다.
      const activeNodeIds = new Set(activeSessionIds);
      const activeFileIds = [];
      sessionEdges.forEach(e => {
        activeNodeIds.add(e.source);
        activeNodeIds.add(e.target);
        if (e.source.startsWith('file-')) activeFileIds.push(e.source);
        if (e.target.startsWith('file-')) activeFileIds.push(e.target);
      });

      const allEdges = [...sessionEdges];
      if (activeFileIds.length > 0) {
        const uniqueFileIds = new Set(activeFileIds);
        // 파일들과 결합된 온톨로지 구조 엣지들
        const ontologyEdges = edges.filter(e => 
          uniqueFileIds.has(e.source) && 
          ['defines_class', 'defines_function', 'imports', 'depends_on'].includes(e.label)
        );
        ontologyEdges.forEach(e => {
          activeNodeIds.add(e.source);
          activeNodeIds.add(e.target);
          allEdges.push(e);
        });
      }

      // 노드 목록 필터링
      const filteredNodes = nodes.filter(n => 
        activeNodeIds.has(n.id) || 
        n.type === 'wiki' ||
        n.type === 'note' ||
        n.type === 'ghost'
      );

      return filterAndCapGraphData(filteredNodes, allEdges, this._safeParse.bind(this));
    } else {
      // 세션이 없는 경우: Wiki 노드와 그 엣지만 로딩
      const wikiNodes = nodes.filter(n => n.type === 'wiki' || n.type === 'note' || n.type === 'ghost');
      const wikiNodeIds = new Set(wikiNodes.map(n => n.id));
      const wikiEdges = edges.filter(e => wikiNodeIds.has(e.source) && wikiNodeIds.has(e.target));
      return filterAndCapGraphData(wikiNodes, wikiEdges, this._safeParse.bind(this));
    }
  }

  // 코드맵 전용 그래프 데이터 — 세션 필터 없이 file/code/library 노드와 그 엣지만 반환한다.
  // (getGraphData 는 세션 중심이라 세션 노드가 없는 순수 코드 분석 결과를 표시하지 못함)
  getCodeGraphData(projectId) {
    const nodes = this.db.prepare(
      `SELECT * FROM nodes WHERE project_id = ? AND type IN ('file','code','library')`
    ).all(projectId);
    const edges = this.db.prepare(`SELECT * FROM edges WHERE project_id = ?`).all(projectId);
    return filterAndCapGraphData(nodes, edges, this._safeParse.bind(this));
  }

  // FTS tokenizer/표시 제목과 무관하게 같은 프로젝트의 정확한 교훈 유형을 읽는다.
  // 설명 문서: docs/specs/goal-replan-lessons.md v1.0.0
  getReplanLessons(projectId) {
    return this.db.prepare("SELECT * FROM nodes WHERE project_id = ? AND type = 'replan_lesson'")
      .all(projectId).map(n => ({ ...n, properties: this._safeParse(n.properties) }));
  }

  searchNodes(projectId, query) {
    const ftsQuery = query.replace(/["]/g, '').split(/\s+/).filter(Boolean).map(term => `${term}*`).join(' AND ');
    if (!ftsQuery) return [];

    try {
      const rows = this.db.prepare(`
        SELECT n.* FROM nodes n
        JOIN nodes_fts f ON n.id = f.id AND n.project_id = f.project_id
        WHERE f.project_id = ? AND nodes_fts MATCH ?
      `).all(projectId, ftsQuery);
      return rows.map(r => ({ ...r, properties: this._safeParse(r.properties) }));
    } catch (e) {
      console.warn('[KnowledgeDB] FTS5 search failed, falling back to LIKE:', e.message);
      const sqlLike = `%${query}%`;
      const fallbackRows = this.db.prepare(`
        SELECT * FROM nodes 
        WHERE project_id = ? AND (label LIKE ? OR properties LIKE ?)
      `).all(projectId, sqlLike, sqlLike);
      return fallbackRows.map(r => ({ ...r, properties: this._safeParse(r.properties) }));
    }
  }

  getNodeDetail(nodeId, projectId) {
    const node = projectId
      ? this.db.prepare(`SELECT * FROM nodes WHERE id = ? AND project_id = ?`).get(nodeId, projectId)
      : this.db.prepare(`SELECT * FROM nodes WHERE id = ?`).get(nodeId);
    if (!node) return null;
    const scope = projectId || node.project_id;

    let edgeSql = `SELECT * FROM edges WHERE (source = ? OR target = ?)`;
    const edgeParams = [nodeId, nodeId];
    if (scope) {
      edgeSql += ` AND project_id = ?`;
      edgeParams.push(scope);
    }
    const connectedEdges = this.db.prepare(edgeSql).all(...edgeParams);

    const resolvedEdges = connectedEdges.map(e => {
      const otherId = e.source === nodeId ? e.target : e.source;
      const otherNode = this.db.prepare(`SELECT label, type FROM nodes WHERE id = ? AND project_id = ?`).get(otherId, scope);
      return {
        source: e.source,
        target: e.target,
        label: e.label,
        otherLabel: otherNode ? otherNode.label : otherId,
        otherType: otherNode ? otherNode.type : 'unknown'
      };
    });

    return {
      node: { ...node, properties: this._safeParse(node.properties) },
      edges: resolvedEdges
    };
  }

  getSessionNodes(projectId, limit) {
    // 봉의 목록은 DB 단계에서 제한한다. 기존 전체 동기화/마이그레이션 호출은 그대로 유지한다.
    if (limit !== undefined) {
      if (typeof projectId !== 'string' || !projectId || !Number.isSafeInteger(limit) || limit < 1 || limit > 100) throw new Error('Invalid session list limit');
      return this.db.prepare("SELECT * FROM nodes WHERE type = 'session' AND project_id = ? ORDER BY created_at DESC, id ASC LIMIT ?")
        .all(projectId, limit).map(n => ({ ...n, properties: this._safeParse(n.properties) }));
    }
    const rows = projectId ? this.db.prepare("SELECT * FROM nodes WHERE type = 'session' AND project_id = ?").all(projectId)
      : this.db.prepare("SELECT * FROM nodes WHERE type = 'session'").all();
    return rows.map(n => ({ ...n, properties: this._safeParse(n.properties) }));
  }

  renameSessionNode(projectId, oldId, newId, properties) {
    return this.db.transaction(() => {
      const old = this.db.prepare('SELECT type FROM nodes WHERE project_id = ? AND id = ?').get(projectId, oldId);
      const existing = this.db.prepare('SELECT id FROM nodes WHERE project_id = ? AND id = ?').get(projectId, newId);
      if (old?.type !== 'session' || existing) throw Object.assign(new Error('Session migration destination conflicts'), { code: 'SESSION_MIGRATION_CONFLICT' });
      this.db.prepare('UPDATE nodes SET id = ?, properties = ? WHERE project_id = ? AND id = ?').run(newId, JSON.stringify(properties), projectId, oldId);
      // UNIQUE 제약 충돌은 transaction 전체를 되돌려 노드·사용자 엣지를 함께 보존한다.
      this.db.prepare('UPDATE edges SET source = CASE WHEN source = ? THEN ? ELSE source END, target = CASE WHEN target = ? THEN ? ELSE target END WHERE project_id = ? AND (source = ? OR target = ?)')
        .run(oldId, newId, oldId, newId, projectId, oldId, oldId);
    })();
  }

  getDependencyTree(projectId, startNodeId) {
    return this.db.prepare(`
      SELECT e.source, e.target, 1 as depth, n.label as target_label, n.type as target_type
      FROM edges e
      JOIN nodes n ON e.target = n.id AND e.project_id = n.project_id
      WHERE e.project_id = ? AND e.source = ? AND e.label IN ('depends_on', 'imports')
    `).all(projectId, startNodeId);
  }

  clearProjectData(projectId) {
    this.db.prepare(`DELETE FROM nodes WHERE project_id = ?`).run(projectId);
    this.db.prepare(`DELETE FROM edges WHERE project_id = ?`).run(projectId);
    this.db.prepare(`DELETE FROM nodes_fts WHERE project_id = ?`).run(projectId);
  }

  exportProjectData(projectId) {
    const nodes = this.db.prepare(`SELECT * FROM nodes WHERE project_id = ?`).all(projectId);
    const edges = this.db.prepare(`SELECT * FROM edges WHERE project_id = ?`).all(projectId);
    return { nodes, edges };
  }

  importProjectData(projectId, data) {
    const plan = require('./graph-import-plan').prepareGraphImport(data);
    return this.db.transaction(() => {
      this.clearProjectData(projectId);
      const insertNode = this.db.prepare('INSERT INTO nodes (id, project_id, type, label, properties, created_at) VALUES (?, ?, ?, ?, ?, ?)');
      const insertEdge = this.db.prepare('INSERT INTO edges (project_id, source, target, label, properties, created_at) VALUES (?, ?, ?, ?, ?, ?)');
      // FTS는 nodes의 기존 trigger가 갱신한다. 별도 중복 삽입을 하지 않는다.
      for (const n of plan.nodes) insertNode.run(n.id, projectId, n.type, n.label, n.properties, n.created_at);
      for (const e of plan.edges) insertEdge.run(projectId, e.source, e.target, e.label, e.properties, e.created_at);
    })();
  }

  deleteNode(projectId, nodeId) {
    this.db.prepare(`DELETE FROM nodes WHERE project_id = ? AND id = ?`).run(projectId, nodeId);
    this.db.prepare(`DELETE FROM edges WHERE project_id = ? AND (source = ? OR target = ?)`).run(projectId, nodeId, nodeId);
  }

  saveBatchTask(projectId, task) {
    const existing = this.db.prepare('SELECT * FROM batch_tasks WHERE id = ?').get(task.id);
    if (existing && existing.project_id !== projectId) throw new Error('Batch task ID belongs to another project');
    const timezone = require('../utils/batch-timezone').batchTimezone(task.timezone, existing?.timezone);
    const stepsJson = typeof task.steps_json === 'string'
      ? task.steps_json
      : JSON.stringify(task.steps || []);
    const prompt = task.prompt || (task.steps && task.steps[0] && task.steps[0].config && task.steps[0].config.prompt) || '';
    const maxTurns = task.max_turns ?? (task.steps && task.steps[0] && task.steps[0].config && task.steps[0].config.max_turns) ?? 30;
    const loopConfig = task.loop_config || null;
    const certification = require('../utils/batch-definition').forSave(existing, { ...task, project_id: projectId });

    const stmt = this.db.prepare(`
      INSERT INTO batch_tasks (id, project_id, name, prompt, cron_expr, max_turns, is_active, steps_json, is_tested_success, loop_config, timezone, tested_fingerprint)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
      ON CONFLICT(id) DO UPDATE SET
        name = excluded.name,
        prompt = excluded.prompt,
        cron_expr = excluded.cron_expr,
        max_turns = excluded.max_turns,
        is_active = excluded.is_active,
        steps_json = excluded.steps_json,
        is_tested_success = excluded.is_tested_success,
        loop_config = excluded.loop_config,
        timezone = excluded.timezone,
        tested_fingerprint = excluded.tested_fingerprint
    `);
    stmt.run(task.id, projectId, task.name, prompt, task.cron_expr ?? '', maxTurns, task.is_active ?? 0, stepsJson, certification.is_tested_success, loopConfig, timezone, certification.tested_fingerprint);
  }

  getBatchTasks(projectId) {
    return this.db.prepare(`SELECT * FROM batch_tasks WHERE project_id = ? ORDER BY created_at DESC`).all(projectId)
      .map(task => ({ ...task, is_tested_success: require('../utils/batch-definition').certified(task) ? 1 : 0 }));
  }

  // 최근 사용한 폴더 목록과 무관하게 저장된 활성 예약 전체를 복원한다.
  getActiveBatchTasks() {
    return this.db.prepare('SELECT * FROM batch_tasks WHERE is_active = 1 ORDER BY created_at DESC, id').all()
      .map(task => ({ ...task, is_tested_success: require('../utils/batch-definition').certified(task) ? 1 : 0 }));
  }

  deleteBatchTask(projectId, taskId) {
    this.db.prepare(`DELETE FROM batch_tasks WHERE project_id = ? AND id = ?`).run(projectId, taskId);
  }

  updateBatchTaskTestStatus(taskId, isTestedSuccess, fingerprint) {
    const task = this.db.prepare('SELECT * FROM batch_tasks WHERE id = ?').get(taskId);
    if (!task) return;
    const status = require('../utils/batch-definition').testStatus(task, isTestedSuccess, fingerprint);
    this.db.prepare('UPDATE batch_tasks SET is_tested_success = ?, tested_fingerprint = ? WHERE id = ?').run(status.is_tested_success, status.tested_fingerprint, taskId);
  }

  setBatchRunWorkspace(runId, workDir) {
    const result = this.db.prepare("UPDATE batch_runs SET work_dir = ? WHERE run_id = ? AND status = 'running'").run(workDir, runId);
    if (result.changes !== 1) throw new Error('Running batch record not found');
  }

  startBatchRun(runId, taskId, logPath, workDir = null) {
    const stmt = this.db.prepare(`
      INSERT INTO batch_runs (run_id, task_id, status, log_path, started_at, work_dir)
      VALUES (?, ?, 'running', ?, ?, ?)
    `);
    stmt.run(runId, taskId, logPath, new Date().toISOString(), workDir);
  }

  completeBatchRun(runId, status, errorMessage) {
    const stmt = this.db.prepare(`
      UPDATE batch_runs SET status = ?, error_message = ?, completed_at = ? WHERE run_id = ?
    `);
    stmt.run(status, errorMessage || null, new Date().toISOString(), runId);
  }

  failStaleRuns() {
    // 다른 앱 프로세스의 실행까지 crashed로 바꾸지 않는다. 검토 복구 서비스가 종료를 판정한다.
    return { modified: 0 };
  }

  getUnfinishedBatchRuns(taskId) {
    return this.db.prepare("SELECT * FROM batch_runs WHERE task_id = ? AND status IN ('running', 'crashed', 'paused') ORDER BY run_id").all(taskId);
  }

  getLatestTaskRun(taskId) {
    try {
      return this.db.prepare(`
        SELECT * FROM batch_runs 
        WHERE task_id = ? 
        ORDER BY started_at DESC LIMIT 1
      `).get(taskId);
    } catch (e) {
      console.error('[KnowledgeDB] Failed to get latest task run:', e);
      return null;
    }
  }

  getBatchRuns(taskId) {
    return this.db.prepare(`SELECT * FROM batch_runs WHERE task_id = ? ORDER BY started_at DESC LIMIT 50`).all(taskId);
  }

  getBatchRun(runId) { return this.db.prepare('SELECT * FROM batch_runs WHERE run_id = ?').get(runId) || null; }

  saveWorkflow(projectId, workflow) {
    // 선행 SELECT와 저장 사이의 경합 없이 SQL 충돌 처리에서 소유권을 확인한다.
    // 설명 문서: docs/specs/mcp-session-boundary.md (v1.1.0)
    const stmt = this.db.prepare(`
      INSERT INTO workflows (id, project_id, name, description, graph_json)
      VALUES (?, ?, ?, ?, ?)
      ON CONFLICT(id) DO UPDATE SET
        name = excluded.name,
        description = excluded.description,
        graph_json = excluded.graph_json
      WHERE workflows.project_id = excluded.project_id
    `);
    const result = stmt.run(
      workflow.id,
      projectId,
      workflow.name,
      workflow.description || '',
      typeof workflow.graph_json === 'string' ? workflow.graph_json : JSON.stringify(workflow.graph || {})
    );
    if (result.changes === 0) throw new Error('Workflow ID belongs to another project');
  }

  getWorkflows(projectId, limit) {
    return this.db.prepare(`SELECT * FROM workflows WHERE project_id = ? ORDER BY created_at DESC LIMIT ?`).all(projectId, Number.isInteger(limit) && limit > 0 ? limit : -1);
  }

  // 설명 문서: docs/specs/bong-operations.md (v1.0.0). 사용량 재계산·실행 없이 체크포인트를 읽는다.
  getWorkflowRunsForProject(projectId, workflowId, limit = 3) {
    const owners = this.db.prepare(`SELECT project_id FROM workflows WHERE id = ?`).all(workflowId);
    if (owners.length !== 1 || owners[0].project_id !== projectId) throw new Error('Workflow ownership is unavailable');
    return this.db.prepare(`SELECT * FROM workflow_runs WHERE workflow_id = ? ORDER BY started_at DESC LIMIT ?`).all(workflowId, Math.max(1, Math.min(50, Number.isInteger(limit) ? limit : 3)));
  }

  deleteWorkflow(projectId, workflowId) {
    // 원래 cascade와 feed를 함께 rollback한다. docs/specs/bong-goal-events.md v1.1.0
    return this.db.transaction(()=>{
      const {changes}=this.db.prepare(`DELETE FROM workflows WHERE project_id = ? AND id = ?`).run(projectId, workflowId);
      if(changes)require('../services/goal-event-feed').removed(this,projectId,'workflow_removed',workflowId);
      return changes;
    })();
  }

  deleteWorkflowRun(runId) {
    return this.db.transaction(()=>{
      const feed=require('../services/goal-event-feed'),binding=feed.removalBinding(this,runId);
      const {changes}=this.db.prepare(`DELETE FROM workflow_runs WHERE run_id = ?`).run(runId);
      if(changes&&binding)feed.removed(this,binding.projectId,'run_removed',runId,binding);
      return changes;
    })();
  }

  clearAllWorkflowRuns(projectId) {
    return this.db.transaction(()=>{const {changes}=this.db.prepare(`
      DELETE FROM workflow_runs 
      WHERE workflow_id IN (SELECT id FROM workflows WHERE project_id = ?)
    `).run(projectId);
    if(changes)require('../services/goal-event-feed').removed(this,projectId,'runs_cleared','workflow_runs');
    return changes;})();
  }

  startWorkflowRun(runId, workflowId, logPath, initialData) {
    return this.db.transaction(()=>{
    const stmt = this.db.prepare(`
      INSERT INTO workflow_runs (run_id, workflow_id, status, run_data, log_path, started_at)
      VALUES (?, ?, 'running', ?, ?, ?)
    `);
    stmt.run(runId, workflowId, typeof initialData === 'string' ? initialData : JSON.stringify(initialData || {}), logPath, new Date().toISOString());
  require('../services/goal-event-feed').runChanged(this,runId,initialData);
    })();
  }

  checkpointWorkflowRun(runId, status, currentNodeId, runData) {
    return this.db.transaction(()=>{
    const binding=require('../services/goal-event-feed').bindRun(this,runId);
    const stmt = this.db.prepare(`
      UPDATE workflow_runs SET status = ?, current_node_id = ?, run_data = ?,
        completed_at = CASE WHEN ? IN ('running', 'paused') THEN NULL ELSE completed_at END WHERE run_id = ?
    `);
    stmt.run(status, currentNodeId || null, typeof runData === 'string' ? runData : JSON.stringify(runData || {}), status, runId);
  require('../services/goal-event-feed').runChanged(this,runId,runData,'run',runId,binding);
    })();
  }

  completeWorkflowRun(runId, status, runData) {
    return this.db.transaction(()=>{
    const binding=require('../services/goal-event-feed').bindRun(this,runId);
    const stmt = this.db.prepare(`
      UPDATE workflow_runs SET status = ?, run_data = ?, completed_at = ? WHERE run_id = ?
    `);
    stmt.run(status, typeof runData === 'string' ? runData : JSON.stringify(runData || {}), new Date().toISOString(), runId);
  require('../services/goal-event-feed').runChanged(this,runId,runData,'run',runId,binding);
    })();
  }

  getWorkflowRuns(workflowId) {
    return this.db.prepare(`SELECT * FROM workflow_runs WHERE workflow_id = ? ORDER BY started_at DESC LIMIT 50`).all(workflowId);
  }

  getWorkflow(workflowId) {
    return this.db.prepare(`SELECT * FROM workflows WHERE id = ?`).get(workflowId);
  }

  getWorkflowRun(runId) {
    return this.db.prepare(`SELECT * FROM workflow_runs WHERE run_id = ?`).get(runId);
  }

  enqueueWorkflowTask(taskId, runId, nodeId, agentId, payload) {
    const stmt = this.db.prepare(`
      INSERT INTO workflow_tasks (task_id, run_id, node_id, agent_id, payload, status)
      VALUES (?, ?, ?, ?, ?, 'queued')
    `);
    stmt.run(taskId, runId, nodeId, agentId, typeof payload === 'string' ? payload : JSON.stringify(payload || {}));
  }

  pollWorkflowQueue() {
    return this.db.transaction(() => {
      const task = this.db.prepare(`
        SELECT * FROM workflow_tasks WHERE status = 'queued' ORDER BY created_at ASC LIMIT 1
      `).get();
      if (task) {
        this.db.prepare(`
          UPDATE workflow_tasks SET status = 'processing', updated_at = ? WHERE task_id = ?
        `).run(new Date().toISOString(), task.task_id);
        task.status = 'processing';
        return task;
      }
      return null;
    }).immediate();
  }

  getWorkflowTask(taskId) {
    return this.db.prepare(`SELECT * FROM workflow_tasks WHERE task_id = ?`).get(taskId);
  }

  getWorkflowTasks(runId) {
    return this.db.prepare(`SELECT * FROM workflow_tasks WHERE run_id = ? ORDER BY created_at DESC`).all(runId);
  }

  completeWorkflowTask(taskId, status, result, error) {
    const stmt = this.db.prepare(`
      UPDATE workflow_tasks SET status = ?, result = ?, error = ?, updated_at = ? WHERE task_id = ?
    `);
    stmt.run(
      status,
      result ? (typeof result === 'string' ? result : JSON.stringify(result)) : null,
      error ? (typeof error === 'string' ? error : JSON.stringify(error)) : null,
      new Date().toISOString(),
      taskId
    );
  }

  saveHarness(projectId, harness) {
    return this.db.transaction(()=>{
    const successCriteria = typeof harness.success_criteria === 'string'
      ? harness.success_criteria
      : JSON.stringify(harness.success_criteria || {});
    const toolChain = typeof harness.tool_chain === 'string'
      ? harness.tool_chain
      : JSON.stringify(harness.tool_chain || []);
    // WHY: stages는 옵셔널. 미지정 시 null로 저장해야 getHarness가 null을 돌려주고
    //      실행부(parseStages)가 "기존 단일-커맨드 경로"로 분기한다(기존 하네스 동작 100% 보존).
    const stages = (harness.stages === null || harness.stages === undefined || harness.stages === '')
      ? null
      : (typeof harness.stages === 'string' ? harness.stages : JSON.stringify(harness.stages));

    const stmt = this.db.prepare(`
      INSERT INTO harnesses (id, project_id, name, description, trigger_pattern, validation_command, max_retries, success_criteria, tool_chain, stages, computer_use_enabled)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
      ON CONFLICT(id) DO UPDATE SET
        name = excluded.name,
        description = excluded.description,
        trigger_pattern = excluded.trigger_pattern,
        validation_command = excluded.validation_command,
        max_retries = excluded.max_retries,
        success_criteria = excluded.success_criteria,
        tool_chain = excluded.tool_chain,
        stages = excluded.stages,
        computer_use_enabled = excluded.computer_use_enabled
    `);
    stmt.run(
      harness.id,
      projectId,
      harness.name,
      harness.description || '',
      harness.trigger_pattern || '',
      // 단계만 있는 하네스는 NOT NULL 단일 명령 열을 빈 값으로 보존한다.
      // 실제 실행 전 prepareHarness가 활성 모드의 명령을 검사한다.
      harness.validation_command ?? '',
      harness.max_retries ?? 3,
      successCriteria,
      toolChain,
      stages,
      harness.computer_use_enabled === true ? 1 : harness.computer_use_enabled === false ? 0 : (harness.computer_use_enabled ?? 0)
    );
  require('../services/goal-event-feed').changed(this,projectId,'harness_definition',null,null,harness.id,0,this.getHarness(harness.id));
    })();
  }

  getHarnesses(projectId, limit) {
    return this.db.prepare(`SELECT * FROM harnesses WHERE project_id = ? ORDER BY created_at DESC LIMIT ?`).all(projectId, Number.isInteger(limit) && limit > 0 ? limit : -1);
  }

  getHarness(id) {
    return this.db.prepare(`SELECT * FROM harnesses WHERE id = ?`).get(id) || null;
  }

  deleteHarness(projectId, id) {
    return this.db.transaction(()=>{
      const {changes}=this.db.prepare(`DELETE FROM harnesses WHERE project_id = ? AND id = ?`).run(projectId, id);
      if(changes)require('../services/goal-event-feed').removed(this,projectId,'harness_removed',id);
      return changes;
    })();
  }

  saveHarnessRun(run) {
    return this.db.transaction(()=>{
    const toolChain = typeof run.tool_chain === 'string'
      ? run.tool_chain
      : JSON.stringify(run.tool_chain || []);
    // WHY(B2): stage_results는 B1의 다단계 stages 실행 결과(JSON 배열). 단일-커맨드 하네스는 null로 저장.
    const stageResults = (run.stage_results === null || run.stage_results === undefined || run.stage_results === '')
      ? null
      : (typeof run.stage_results === 'string' ? run.stage_results : JSON.stringify(run.stage_results));
    const receiptSummary = run.receipt_summary || null;

    // WHY(B2, COALESCE 미적용 근거): agent-runner.js의 runHarnessNode는 동일 run_id에 대해
    // saveHarnessRun을 정확히 2회만 호출한다 — ① 시작 시 INSERT(status:'running', stage_results/receipt_summary 미상 → null),
    // ② 종료 시 UPDATE(status:'success'|'failed', 이 시점엔 stagesResult/리시트가 전부 계산 완료된 "최종" 값).
    // loop-controller.js의 harness_pass 분기(goal 검증용 하네스 실행)는 db.saveHarnessRun을 전혀 호출하지 않는다(harness_runs에 기록 안 함).
    // 즉 동일 run_id를 재저장하며 stage_results/receipt_summary를 누락시키는 제3의 호출 경로가 없으므로,
    // A1(loop_runs.receipt_summary)과 달리 COALESCE 보존 시맨틱이 불필요하다 — 두 번째(최종) 호출값을 그대로 덮어쓰면 된다.
    const stmt = this.db.prepare(`
      INSERT INTO harness_runs (run_id, harness_id, workflow_run_id, status, retry_count, logs, tool_chain, stage_results, receipt_summary, definition_hash, goal_evidence, created_at, completed_at)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
      ON CONFLICT(run_id) DO UPDATE SET
        status = excluded.status,
        retry_count = excluded.retry_count,
        logs = excluded.logs,
        tool_chain = excluded.tool_chain,
        stage_results = excluded.stage_results,
        receipt_summary = excluded.receipt_summary,
        definition_hash = excluded.definition_hash,
        goal_evidence = excluded.goal_evidence,
        completed_at = excluded.completed_at
    `);
    stmt.run(
      run.run_id,
      run.harness_id,
      run.workflow_run_id || null,
      run.status,
      run.retry_count ?? 0,
      run.logs || '',
      toolChain,
      stageResults,
      receiptSummary,
      /^[a-f0-9]{64}$/.test(run.definition_hash) ? run.definition_hash : null,
      run.goal_evidence ? JSON.stringify(run.goal_evidence) : null,
      run.created_at || new Date().toISOString(),
      run.completed_at || null
    );
  if(run.workflow_run_id)require('../services/goal-event-feed').runChanged(this,run.workflow_run_id,run,'harness',run.run_id);
    })();
  }

  getHarnessRuns(harnessId) {
    return this.db.prepare(`SELECT * FROM harness_runs WHERE harness_id = ? ORDER BY created_at DESC LIMIT 50`).all(harnessId);
  }

  // 설명 문서: docs/specs/bong-operations.md (v1.0.0). 이력 조회 전에 소유권을 확인한다.
  getHarnessRunsForProject(projectId, harnessId, limit = 3) {
    const owners = this.db.prepare(`SELECT project_id FROM harnesses WHERE id = ?`).all(harnessId);
    if (owners.length !== 1 || owners[0].project_id !== projectId) throw new Error('Harness ownership is unavailable');
    return this.db.prepare(`SELECT * FROM harness_runs WHERE harness_id = ? ORDER BY created_at DESC LIMIT ?`).all(harnessId, Math.max(1, Math.min(50, Number.isInteger(limit) ? limit : 3)));
  }

  saveTriageItem(projectId, item) {
    const itemId = item.id || 'tr_' + Date.now() + '_' + Math.random().toString(36).substring(2, 7);
    const stmt = this.db.prepare(`
      INSERT INTO triage_items (id, project_id, run_id, source_type, error_message, ai_analysis, status, created_at, updated_at)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
      ON CONFLICT(id) DO UPDATE SET
        error_message = excluded.error_message,
        ai_analysis = excluded.ai_analysis,
        status = excluded.status,
        updated_at = excluded.updated_at
    `);
    const now = new Date().toISOString();
    stmt.run(
      itemId,
      projectId,
      item.run_id,
      item.source_type,
      item.error_message || '',
      item.ai_analysis || '',
      item.status || 'pending',
      item.created_at || now,
      now
    );
    return { id: itemId, project_id: projectId, ...item };
  }

  getTriageItems(projectId) {
    return this.db.prepare(`SELECT * FROM triage_items WHERE project_id = ? ORDER BY created_at DESC`).all(projectId);
  }

  resolveTriageItem(itemId) {
    const stmt = this.db.prepare(`UPDATE triage_items SET status = 'resolved', updated_at = ? WHERE id = ?`);
    const info = stmt.run(new Date().toISOString(), itemId);
    return info.changes > 0;
  }

  saveWorkflowProvenance(provenance) {
    const parentNodeIdsStr = typeof provenance.parent_node_ids === 'string' 
      ? provenance.parent_node_ids 
      : JSON.stringify(provenance.parent_node_ids || []);
    const inputFlowFileStr = typeof provenance.input_flow_file === 'string'
      ? provenance.input_flow_file
      : JSON.stringify(provenance.input_flow_file || {});
    const outputFlowFileStr = provenance.output_flow_file 
      ? (typeof provenance.output_flow_file === 'string' ? provenance.output_flow_file : JSON.stringify(provenance.output_flow_file))
      : null;

    const stmt = this.db.prepare(`
      INSERT INTO workflow_provenance (id, run_id, node_id, parent_node_ids, input_flow_file, output_flow_file, status, started_at, ended_at, retry_count)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
      ON CONFLICT(id) DO UPDATE SET
        output_flow_file = excluded.output_flow_file,
        status = excluded.status,
        ended_at = excluded.ended_at,
        retry_count = excluded.retry_count
    `);
    stmt.run(
      provenance.id,
      provenance.run_id,
      provenance.node_id,
      parentNodeIdsStr,
      inputFlowFileStr,
      outputFlowFileStr,
      provenance.status,
      provenance.started_at || new Date().toISOString(),
      provenance.ended_at || null,
      provenance.retry_count ?? 0
    );
  }

  getWorkflowProvenances(runId) {
    const rows = this.db.prepare(`SELECT * FROM workflow_provenance WHERE run_id = ? ORDER BY started_at ASC`).all(runId);
    return rows.map(r => ({
      ...r,
      parent_node_ids: this._safeParse(r.parent_node_ids),
      input_flow_file: this._safeParse(r.input_flow_file),
      output_flow_file: r.output_flow_file ? this._safeParse(r.output_flow_file) : null
    }));
  }

  getWorkflowProvenance(runId, nodeId) {
    const r = this.db.prepare(`SELECT * FROM workflow_provenance WHERE run_id = ? AND node_id = ? ORDER BY started_at DESC LIMIT 1`).get(runId, nodeId);
    if (!r) return null;
    return {
      ...r,
      parent_node_ids: this._safeParse(r.parent_node_ids),
      input_flow_file: this._safeParse(r.input_flow_file),
      output_flow_file: r.output_flow_file ? this._safeParse(r.output_flow_file) : null
    };
  }

  ensureProjectDbAttached(projectId) {
    if (!projectId) return 'main';
    const projectHash = crypto.createHash('md5').update(projectId).digest('hex').substring(0, 16);
    const dbAlias = `code_graph_${projectHash}`;
    
    if (this.attachedDbs.has(dbAlias)) {
      return dbAlias;
    }

    try {
      const databaseList = this.db.pragma('database_list');
      const isAttached = databaseList.some(d => d.name === dbAlias);
      
      const CLAUDE_DIR = path.join(require('os').homedir(), '.claude');
      if (!fs.existsSync(CLAUDE_DIR)) {
        fs.mkdirSync(CLAUDE_DIR, { recursive: true });
      }
      const dbPath = path.join(CLAUDE_DIR, `${dbAlias}.db`);

      if (!isAttached) {
        this.db.prepare(`ATTACH DATABASE ? AS ${dbAlias}`).run(dbPath);
      }

      this.db.prepare(`
        CREATE TABLE IF NOT EXISTS ${dbAlias}.code_symbols (
          id TEXT NOT NULL,
          project_id TEXT NOT NULL,
          symbol_type TEXT NOT NULL,
          name TEXT NOT NULL,
          file_path TEXT NOT NULL,
          start_line INTEGER,
          end_line INTEGER,
          signature TEXT,
          doc_comment TEXT,
          commit_hash TEXT,
          last_modified_commit TEXT,
          properties TEXT,
          created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
          updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
          PRIMARY KEY (id, project_id)
        )
      `).run();

      this.db.prepare(`
        CREATE TABLE IF NOT EXISTS ${dbAlias}.code_relations (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          project_id TEXT NOT NULL,
          source_symbol_id TEXT NOT NULL,
          target_symbol_id TEXT NOT NULL,
          relation_type TEXT NOT NULL,
          weight REAL DEFAULT 1.0,
          properties TEXT,
          UNIQUE(project_id, source_symbol_id, target_symbol_id, relation_type)
        )
      `).run();

      this.db.prepare(`
        CREATE TABLE IF NOT EXISTS ${dbAlias}.code_change_history (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          project_id TEXT NOT NULL,
          commit_hash TEXT NOT NULL,
          commit_message TEXT,
          commit_author TEXT,
          commit_timestamp DATETIME,
          changed_symbols TEXT,
          diff_summary TEXT,
          snapshot_json TEXT,
          created_at DATETIME DEFAULT CURRENT_TIMESTAMP
        )
      `).run();

      this.db.prepare(`CREATE INDEX IF NOT EXISTS ${dbAlias}.idx_cs_proj ON code_symbols (project_id)`).run();
      this.db.prepare(`CREATE INDEX IF NOT EXISTS ${dbAlias}.idx_cs_file ON code_symbols (file_path)`).run();
      this.db.prepare(`CREATE INDEX IF NOT EXISTS ${dbAlias}.idx_cr_proj ON code_relations (project_id)`).run();

      this.attachedDbs.add(dbAlias);
    } catch (e) {
      console.error(`[SqliteDb] ATTACH DATABASE failed for ${projectId}:`, e.message);
      try {
        this.db.prepare(`
          CREATE TABLE IF NOT EXISTS code_symbols (
            id TEXT NOT NULL,
            project_id TEXT NOT NULL,
            symbol_type TEXT NOT NULL,
            name TEXT NOT NULL,
            file_path TEXT NOT NULL,
            start_line INTEGER,
            end_line INTEGER,
            signature TEXT,
            doc_comment TEXT,
            commit_hash TEXT,
            last_modified_commit TEXT,
            properties TEXT,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id, project_id)
          )
        `).run();
        this.db.prepare(`
          CREATE TABLE IF NOT EXISTS code_relations (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            project_id TEXT NOT NULL,
            source_symbol_id TEXT NOT NULL,
            target_symbol_id TEXT NOT NULL,
            relation_type TEXT NOT NULL,
            weight REAL DEFAULT 1.0,
            properties TEXT,
            UNIQUE(project_id, source_symbol_id, target_symbol_id, relation_type)
          )
        `).run();
        this.db.prepare(`
          CREATE TABLE IF NOT EXISTS code_change_history (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            project_id TEXT NOT NULL,
            commit_hash TEXT NOT NULL,
            commit_message TEXT,
            commit_author TEXT,
            commit_timestamp DATETIME,
            changed_symbols TEXT,
            diff_summary TEXT,
            snapshot_json TEXT,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP
          )
        `).run();
        return 'main';
      } catch (innerError) {
        console.error(`[SqliteDb] Fallback creation failed:`, innerError.message);
      }
    }

    return dbAlias;
  }

  saveCodeSymbol(projectId, symbol) {
    const dbAlias = this.ensureProjectDbAttached(projectId);
    const propertiesStr = typeof symbol.properties === 'string' ? symbol.properties : JSON.stringify(symbol.properties || {});
    const stmt = this.db.prepare(`
      INSERT INTO ${dbAlias}.code_symbols (id, project_id, symbol_type, name, file_path, start_line, end_line, signature, doc_comment, commit_hash, last_modified_commit, properties, updated_at)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
      ON CONFLICT(id, project_id) DO UPDATE SET
        symbol_type = excluded.symbol_type,
        name = excluded.name,
        file_path = excluded.file_path,
        start_line = excluded.start_line,
        end_line = excluded.end_line,
        signature = excluded.signature,
        doc_comment = excluded.doc_comment,
        last_modified_commit = excluded.last_modified_commit,
        properties = excluded.properties,
        updated_at = excluded.updated_at
    `);
    stmt.run(
      symbol.id,
      projectId,
      symbol.symbol_type,
      symbol.name,
      symbol.file_path,
      symbol.start_line || null,
      symbol.end_line || null,
      symbol.signature || null,
      symbol.doc_comment || null,
      symbol.commit_hash || null,
      symbol.last_modified_commit || null,
      propertiesStr,
      new Date().toISOString()
    );
  }

  searchCodeSymbols(projectId, query) {
    const dbAlias = this.ensureProjectDbAttached(projectId);
    const sqlLike = `%${query}%`;
    const rows = this.db.prepare(`
      SELECT * FROM ${dbAlias}.code_symbols 
      WHERE project_id = ? AND (name LIKE ? OR file_path LIKE ?)
    `).all(projectId, sqlLike, sqlLike);
    return rows.map(r => ({ ...r, properties: this._safeParse(r.properties) }));
  }

  getCodeRelations(projectId, symbolId) {
    const dbAlias = this.ensureProjectDbAttached(projectId);
    const rows = this.db.prepare(`
      SELECT * FROM ${dbAlias}.code_relations
      WHERE project_id = ? AND (source_symbol_id = ? OR target_symbol_id = ?)
    `).all(projectId, symbolId, symbolId);
    return rows.map(r => ({ ...r, properties: this._safeParse(r.properties) }));
  }

  // 프로젝트의 모든 코드 관계 조회 (내보내기/익스포트용)
  getAllCodeRelations(projectId) {
    const dbAlias = this.ensureProjectDbAttached(projectId);
    const rows = this.db.prepare(`
      SELECT * FROM ${dbAlias}.code_relations WHERE project_id = ?
    `).all(projectId);
    return rows.map(r => ({ ...r, properties: this._safeParse(r.properties) }));
  }

  // 프로젝트의 인덱싱된 코드 데이터(심볼/관계/변경이력) 전체 삭제 (프로젝트 삭제용)
  deleteCodeProjectData(projectId) {
    const dbAlias = this.ensureProjectDbAttached(projectId);
    this.db.prepare(`DELETE FROM ${dbAlias}.code_symbols WHERE project_id = ?`).run(projectId);
    this.db.prepare(`DELETE FROM ${dbAlias}.code_relations WHERE project_id = ?`).run(projectId);
    this.db.prepare(`DELETE FROM ${dbAlias}.code_change_history WHERE project_id = ?`).run(projectId);
  }

  saveCodeRelation(projectId, relation) {
    const dbAlias = this.ensureProjectDbAttached(projectId);
    const propertiesStr = typeof relation.properties === 'string' ? relation.properties : JSON.stringify(relation.properties || {});
    const stmt = this.db.prepare(`
      INSERT INTO ${dbAlias}.code_relations (project_id, source_symbol_id, target_symbol_id, relation_type, weight, properties)
      VALUES (?, ?, ?, ?, ?, ?)
      ON CONFLICT(project_id, source_symbol_id, target_symbol_id, relation_type) DO UPDATE SET
        weight = excluded.weight,
        properties = excluded.properties
    `);
    stmt.run(
      projectId,
      relation.source_symbol_id,
      relation.target_symbol_id,
      relation.relation_type,
      relation.weight ?? 1.0,
      propertiesStr
    );
  }

  saveChangeHistory(projectId, entry) {
    const dbAlias = this.ensureProjectDbAttached(projectId);
    const changedSymbolsStr = typeof entry.changed_symbols === 'string' ? entry.changed_symbols : JSON.stringify(entry.changed_symbols || []);
    const diffSummaryStr = typeof entry.diff_summary === 'string' ? entry.diff_summary : JSON.stringify(entry.diff_summary || {});
    const stmt = this.db.prepare(`
      INSERT INTO ${dbAlias}.code_change_history (project_id, commit_hash, commit_message, commit_author, commit_timestamp, changed_symbols, diff_summary, snapshot_json)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    `);
    stmt.run(
      projectId,
      entry.commit_hash,
      entry.commit_message || null,
      entry.commit_author || null,
      entry.commit_timestamp || null,
      changedSymbolsStr,
      diffSummaryStr,
      entry.snapshot_json || null
    );
  }

  getChangeHistory(projectId, symbol) {
    const dbAlias = this.ensureProjectDbAttached(projectId);
    let rows;
    if (symbol) {
      const match = `%${symbol}%`;
      rows = this.db.prepare(`
        SELECT * FROM ${dbAlias}.code_change_history
        WHERE project_id = ? AND (changed_symbols LIKE ? OR commit_message LIKE ?)
        ORDER BY created_at DESC
      `).all(projectId, match, match);
    } else {
      rows = this.db.prepare(`
        SELECT * FROM ${dbAlias}.code_change_history
        WHERE project_id = ?
        ORDER BY created_at DESC
      `).all(projectId);
    }
    return rows.map(r => ({
      ...r,
      changed_symbols: this._safeParse(r.changed_symbols),
      diff_summary: this._safeParse(r.diff_summary)
    }));
  }

  saveTroubleshoot(projectId, entry) {
    const affectedFilesStr = typeof entry.affected_files === 'string' ? entry.affected_files : JSON.stringify(entry.affected_files || []);
    const tagsStr = typeof entry.tags === 'string' ? entry.tags : JSON.stringify(entry.tags || []);
    const entryId = entry.id || 'err_' + Date.now() + '_' + Math.random().toString(36).substring(2, 7);
    const stmt = this.db.prepare(`
      INSERT INTO troubleshoot_entries (id, project_id, error_pattern, error_type, root_cause, solution, affected_files, tags, hit_count, last_hit_at)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
      ON CONFLICT(id) DO UPDATE SET
        project_id = excluded.project_id,
        error_pattern = excluded.error_pattern,
        error_type = excluded.error_type,
        root_cause = excluded.root_cause,
        solution = excluded.solution,
        affected_files = excluded.affected_files,
        tags = excluded.tags,
        hit_count = troubleshoot_entries.hit_count + 1,
        last_hit_at = excluded.last_hit_at
    `);
    stmt.run(
      entryId,
      projectId,
      entry.error_pattern,
      entry.error_type || null,
      entry.root_cause || '',
      entry.solution,
      affectedFilesStr,
      tagsStr,
      entry.hit_count ?? 1,
      entry.last_hit_at || new Date().toISOString()
    );
    return { id: entryId, ...entry };
  }

  searchTroubleshoot(projectId, errorPattern) {
    const sqlLike = `%${errorPattern}%`;
    const rows = this.db.prepare(`
      SELECT * FROM troubleshoot_entries
      WHERE project_id = ? AND (error_pattern LIKE ? OR root_cause LIKE ? OR solution LIKE ?)
      ORDER BY hit_count DESC
    `).all(projectId, sqlLike, sqlLike, sqlLike);
    return rows.map(r => ({
      ...r,
      affected_files: this._safeParse(r.affected_files),
      tags: this._safeParse(r.tags)
    }));
  }

  incrementTroubleshootHit(entryId) {
    this.db.prepare(`
      UPDATE troubleshoot_entries
      SET hit_count = hit_count + 1, last_hit_at = ?
      WHERE id = ?
    `).run(new Date().toISOString(), entryId);
  }

  saveDevPreference(projectId, pref) {
    const entryId = pref.id || 'pref_' + Date.now() + '_' + Math.random().toString(36).substring(2, 7);
    const stmt = this.db.prepare(`
      INSERT INTO dev_preferences (id, project_id, category, preference_key, preference_value, confidence, source, occurrence_count)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?)
      ON CONFLICT(project_id, category, preference_key) DO UPDATE SET
        preference_value = excluded.preference_value,
        confidence = excluded.confidence,
        source = excluded.source,
        occurrence_count = dev_preferences.occurrence_count + 1,
        updated_at = CURRENT_TIMESTAMP
    `);
    stmt.run(
      entryId,
      projectId,
      pref.category,
      pref.preference_key,
      pref.preference_value,
      pref.confidence ?? 0.5,
      pref.source || 'auto_inferred',
      pref.occurrence_count ?? 1
    );
  }

  getDevPreferences(projectId, category) {
    let rows;
    if (category) {
      rows = this.db.prepare(`SELECT * FROM dev_preferences WHERE project_id = ? AND category = ?`).all(projectId, category);
    } else {
      rows = this.db.prepare(`SELECT * FROM dev_preferences WHERE project_id = ?`).all(projectId);
    }
    return rows;
  }

  // 개발 선호도 항목 삭제 (코드 인텔 프로젝트 등록 해제 등에서 사용)
  deleteDevPreference(projectId, category, preferenceKey) {
    this.db.prepare(`
      DELETE FROM dev_preferences WHERE project_id = ? AND category = ? AND preference_key = ?
    `).run(projectId, category, preferenceKey);
  }

  saveFavoritePrompt(prompt) {
    if (!prompt || typeof prompt !== 'object') {
      console.error('[SqliteDb] saveFavoritePrompt: 올바르지 않은 프롬프트 데이터 구조입니다.');
      return { success: false, error: '유효한 프롬프트 객체가 필요합니다.' };
    }
    if (!prompt.id || !prompt.title || !prompt.prompt_text) {
      console.error('[SqliteDb] saveFavoritePrompt: 필수 필드가 누락되었습니다.', prompt);
      return { success: false, error: 'ID, 제목, 프롬프트 내용은 필수 입력 항목입니다.' };
    }

    try {
      const stmt = this.db.prepare(`
        INSERT INTO favorite_prompts (id, title, prompt_text, created_at)
        VALUES (?, ?, ?, ?)
        ON CONFLICT(id) DO UPDATE SET
          title = excluded.title,
          prompt_text = excluded.prompt_text
      `);
      stmt.run(prompt.id, prompt.title, prompt.prompt_text, new Date().toISOString());
      return { success: true };
    } catch (error) {
      console.error('[SqliteDb] saveFavoritePrompt 실행 오류:', error.message);
      throw new Error(`데이터베이스 저장 실패: ${error.message}`, { cause: error });
    }
  }

  getFavoritePrompts() {
    try {
      const rows = this.db.prepare(`SELECT * FROM favorite_prompts ORDER BY created_at DESC`).all();
      return rows;
    } catch (error) {
      console.error('[SqliteDb] getFavoritePrompts 조회 오류:', error.message);
      throw new Error(`데이터베이스 조회 실패: ${error.message}`, { cause: error });
    }
  }

  deleteFavoritePrompt(id) {
    if (!id || typeof id !== 'string') {
      console.error('[SqliteDb] deleteFavoritePrompt: 유효하지 않은 ID입니다.', id);
      return { success: false, error: '유효한 ID가 필요합니다.' };
    }

    try {
      const stmt = this.db.prepare(`DELETE FROM favorite_prompts WHERE id = ?`);
      stmt.run(id);
      return { success: true };
    } catch (error) {
      console.error('[SqliteDb] deleteFavoritePrompt 삭제 오류:', error.message);
      throw new Error(`데이터베이스 삭제 실패: ${error.message}`, { cause: error });
    }
  }

  // ─── Loop Engineering CRUD Helper Methods ───

  getLoopGoals(projectId) {
    try {
      return this.db.prepare(`SELECT * FROM loop_goals WHERE project_id = ? ORDER BY created_at DESC`).all(projectId);
    } catch (error) {
      console.error('[SqliteDb] getLoopGoals 조회 오류:', error.message);
      throw error;
    }
  }

  saveLoopGoal(projectId, goal) {
    try {
      const goalExpressionStr = typeof goal.goal_expression === 'string'
        ? goal.goal_expression
        : JSON.stringify(goal.goal_expression || {});
      
      const stmt = this.db.prepare(`
        INSERT INTO loop_goals (
          id, project_id, task_id, workflow_id, name, goal_expression, 
          max_iterations, token_budget, max_wall_time, consecutive_failure_threshold, worktree_isolation
        )
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ON CONFLICT(id) DO UPDATE SET
          name = excluded.name,
          goal_expression = excluded.goal_expression,
          max_iterations = excluded.max_iterations,
          token_budget = excluded.token_budget,
          max_wall_time = excluded.max_wall_time,
          consecutive_failure_threshold = excluded.consecutive_failure_threshold,
          worktree_isolation = excluded.worktree_isolation,
          task_id = excluded.task_id,
          workflow_id = excluded.workflow_id,
          updated_at = CURRENT_TIMESTAMP
        WHERE loop_goals.project_id = excluded.project_id
      `);
      // 소유권 비교와 갱신을 같은 SQL 문으로 처리해 조회/쓰기 사이 경합을 피한다.
      // 설명 문서: docs/specs/loop-project-ownership.md (v1.0.0)
      const result = stmt.run(
        goal.id,
        projectId,
        goal.task_id || null,
        goal.workflow_id || null,
        goal.name,
        goalExpressionStr,
        goal.max_iterations ?? 10,
        goal.token_budget ?? 5.0,
        goal.max_wall_time ?? 3600,
        goal.consecutive_failure_threshold ?? 3,
        goal.worktree_isolation ?? 0
      );
      if (result.changes === 0) throw new Error('Loop goal ID belongs to another project');
    } catch (error) {
      console.error('[SqliteDb] saveLoopGoal 저장 오류:', error.message);
      throw error;
    }
  }

  deleteLoopGoal(goalId) {
    try {
      this.db.prepare(`DELETE FROM loop_goals WHERE id = ?`).run(goalId);
    } catch (error) {
      console.error('[SqliteDb] deleteLoopGoal 삭제 오류:', error.message);
      throw error;
    }
  }

  // ─── Loop Templates CRUD (프로젝트 비종속 재사용 템플릿) ───

  getLoopTemplates() {
    try {
      // WHY: project_id가 없는 전역 카탈로그이므로 필터 없이 최신순 전체 반환.
      return this.db.prepare(`SELECT * FROM loop_templates ORDER BY created_at DESC`).all();
    } catch (error) {
      console.error('[SqliteDb] getLoopTemplates 조회 오류:', error.message);
      throw error;
    }
  }

  saveLoopTemplate(template) {
    try {
      const goalExpressionStr = typeof template.goal_expression === 'string'
        ? template.goal_expression
        : JSON.stringify(template.goal_expression || {});
      const stepsJsonStr = typeof template.steps_json === 'string'
        ? template.steps_json
        : JSON.stringify(template.steps_json || []);

      const stmt = this.db.prepare(`
        INSERT INTO loop_templates (
          id, name, description, goal_expression,
          max_iterations, token_budget, max_wall_time, consecutive_failure_threshold, worktree_isolation,
          steps_json, source_project_name, source_task_name
        )
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ON CONFLICT(id) DO UPDATE SET
          name = excluded.name,
          description = excluded.description,
          goal_expression = excluded.goal_expression,
          max_iterations = excluded.max_iterations,
          token_budget = excluded.token_budget,
          max_wall_time = excluded.max_wall_time,
          consecutive_failure_threshold = excluded.consecutive_failure_threshold,
          worktree_isolation = excluded.worktree_isolation,
          steps_json = excluded.steps_json,
          source_project_name = excluded.source_project_name,
          source_task_name = excluded.source_task_name
      `);
      stmt.run(
        template.id,
        template.name,
        template.description || null,
        goalExpressionStr,
        template.max_iterations ?? 10,
        template.token_budget ?? 5.0,
        template.max_wall_time ?? 3600,
        template.consecutive_failure_threshold ?? 3,
        template.worktree_isolation ?? 0,
        stepsJsonStr,
        template.source_project_name || null,
        template.source_task_name || null
      );
    } catch (error) {
      console.error('[SqliteDb] saveLoopTemplate 저장 오류:', error.message);
      throw error;
    }
  }

  deleteLoopTemplate(templateId) {
    try {
      this.db.prepare(`DELETE FROM loop_templates WHERE id = ?`).run(templateId);
    } catch (error) {
      console.error('[SqliteDb] deleteLoopTemplate 삭제 오류:', error.message);
      throw error;
    }
  }

  getLoopRun(runId) {
    try {
      return this.db.prepare(`SELECT * FROM loop_runs WHERE run_id = ?`).get(runId) || null;
    } catch (error) {
      console.error('[SqliteDb] getLoopRun 조회 오류:', error.message);
      throw error;
    }
  }

  getLoopRuns(goalId) {
    try {
      return this.db.prepare(`SELECT * FROM loop_runs WHERE goal_id = ? ORDER BY started_at DESC`).all(goalId);
    } catch (error) {
      console.error('[SqliteDb] getLoopRuns 조회 오류:', error.message);
      throw error;
    }
  }

  // 원본은 승인 grant에 보존한다. docs/specs/batch-loop-ghost.md v1.0.0
  removeBatchLoopGhost(runId,grantId,verify) { if(!this.db.inTransaction)require('../services/batch-loop-ghost').fail();return this.db.transaction(()=>{const id=require('./batch-loop-ghost-record').verifyRemoval(this,runId,grantId,verify);if(this.db.prepare('DELETE FROM loop_iterations WHERE id=? AND loop_run_id=?').run(id,'looprun-'+runId).changes!==1)require('../services/batch-loop-ghost').fail();return id;})(); }

  getLoopIterations(loopRunId) {
    try {
      return this.db.prepare(`SELECT * FROM loop_iterations WHERE loop_run_id = ? ORDER BY iteration_number ASC`).all(loopRunId);
    } catch (error) {
      console.error('[SqliteDb] getLoopIterations 조회 오류:', error.message);
      throw error;
    }
  }

  getRecentLoopLearnings(projectId, limit = 5) {
    try {
      return this.db.prepare(`
        SELECT r.run_id, g.name as goal_name, r.status, r.total_iterations, r.total_cost, r.goal_met, r.break_reason, r.completed_at,
               (SELECT error_message FROM loop_iterations WHERE loop_run_id = r.run_id AND error_message IS NOT NULL AND error_message != '' ORDER BY iteration_number DESC LIMIT 1) as last_error
        FROM loop_runs r
        JOIN loop_goals g ON r.goal_id = g.id
        WHERE g.project_id = ? AND r.status IN ('completed', 'circuit_broken')
        ORDER BY r.completed_at DESC
        LIMIT ?
      `).all(projectId, limit);
    } catch (error) {
      console.error('[SqliteDb] getRecentLoopLearnings 조회 오류:', error.message);
      return [];
    }
  }

  saveLoopRun(run, options = {}) {
    try {
      const stmt = this.db.prepare(`
        INSERT INTO loop_runs (
          run_id, goal_id, parent_run_id, status, total_iterations, total_tokens_used, total_cost, goal_met, break_reason, receipt_summary, started_at, completed_at
        )
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ON CONFLICT(run_id) DO UPDATE SET
          status = excluded.status,
          total_iterations = excluded.total_iterations,
          total_tokens_used = excluded.total_tokens_used,
          total_cost = excluded.total_cost,
          goal_met = excluded.goal_met,
          break_reason = excluded.break_reason,
          receipt_summary = ${options.replaceReceipt === true ? 'excluded.receipt_summary' : 'COALESCE(excluded.receipt_summary, loop_runs.receipt_summary)'},
          completed_at = excluded.completed_at
      `);
      stmt.run(
        run.run_id,
        run.goal_id,
        run.parent_run_id || null,
        run.status,
        run.total_iterations ?? 0,
        run.total_tokens_used ?? 0,
        run.total_cost ?? 0.0,
        run.goal_met ?? 0,
        run.break_reason || null,
        run.receipt_summary || null,
        run.started_at || new Date().toISOString(),
        run.completed_at || null
      );
    } catch (error) {
      console.error('[SqliteDb] saveLoopRun 저장 오류:', error.message);
      throw error;
    }
  }

  saveLoopIteration(iter) {
    try {
      const stepOutputsStr = typeof iter.step_outputs === 'string'
        ? iter.step_outputs
        : JSON.stringify(iter.step_outputs || {});

      const stmt = this.db.prepare(`
        INSERT INTO loop_iterations (
          id, loop_run_id, iteration_number, status, step_outputs, goal_evaluation_result, tokens_used, cost, worktree_branch, error_message, started_at, completed_at
        )
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ON CONFLICT(id) DO UPDATE SET
          status = excluded.status,
          step_outputs = excluded.step_outputs,
          goal_evaluation_result = excluded.goal_evaluation_result,
          tokens_used = excluded.tokens_used,
          cost = excluded.cost,
          worktree_branch = excluded.worktree_branch,
          error_message = excluded.error_message,
          completed_at = excluded.completed_at
      `);
      stmt.run(
        iter.id,
        iter.loop_run_id,
        iter.iteration_number,
        iter.status,
        stepOutputsStr,
        iter.goal_evaluation_result ?? 0,
        iter.tokens_used ?? 0,
        iter.cost ?? 0.0,
        iter.worktree_branch || null,
        iter.error_message || null,
        iter.started_at || new Date().toISOString(),
        iter.completed_at || null
      );
    } catch (error) {
      console.error('[SqliteDb] saveLoopIteration 저장 오류:', error.message);
      throw error;
    }
  }

  saveLoopMessage(msg) {
    try {
      const stmt = this.db.prepare(`
        INSERT INTO loop_messages (
          loop_run_id, iteration_number, sender_agent_id, receiver_agent_id, message_type, content, created_at
        )
        VALUES (?, ?, ?, ?, ?, ?, ?)
      `);
      stmt.run(
        msg.loop_run_id,
        msg.iteration_number || null,
        msg.sender_agent_id,
        msg.receiver_agent_id,
        msg.message_type,
        msg.content,
        msg.created_at || new Date().toISOString()
      );
    } catch (error) {
      console.error('[SqliteDb] saveLoopMessage 저장 오류:', error.message);
      throw error;
    }
  }

  getLoopMessages(loopRunId) {
    try {
      return this.db.prepare(`SELECT * FROM loop_messages WHERE loop_run_id = ? ORDER BY created_at ASC`).all(loopRunId);
    } catch (error) {
      console.error('[SqliteDb] getLoopMessages 조회 오류:', error.message);
      throw error;
    }
  }

  saveWorktreeState(wtState) {
    try {
      const stmt = this.db.prepare(`
        INSERT OR REPLACE INTO worktree_state (id, run_id, node_id, wt_path, branch_name, status, created_at, completed_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
      `);
      stmt.run(
        wtState.id,
        wtState.run_id,
        wtState.node_id,
        wtState.wt_path,
        wtState.branch_name,
        wtState.status,
        wtState.created_at || new Date().toISOString(),
        wtState.completed_at || null
      );
      return true;
    } catch(e) {
      console.error('[SqliteDb] saveWorktreeState 저장 오류:', e.message);
      throw e;
    }
  }

  updateWorktreeStatus(id, status, completedAt) {
    try {
      const stmt = this.db.prepare(`
        UPDATE worktree_state 
        SET status = ?, completed_at = ?
        WHERE id = ?
      `);
      stmt.run(status, completedAt || new Date().toISOString(), id);
      return true;
    } catch(e) {
      console.error('[SqliteDb] updateWorktreeStatus 수정 오류:', e.message);
      throw e;
    }
  }

  getWorktreesByRunId(runId) {
    try {
      const stmt = this.db.prepare(`SELECT * FROM worktree_state WHERE run_id = ?`);
      return stmt.all(runId);
    } catch(e) {
      console.error('[SqliteDb] getWorktreesByRunId 조회 오류:', e.message);
      throw e;
    }
  }

  // ─── Swarm Blackboard Methods (SPEC-INNOV-001) ───
  saveBlackboardEntry(entry) {
    try {
      const now = Date.now();
      const payloadStr = typeof entry.payload === 'string' ? entry.payload : JSON.stringify(entry.payload || {});
      const stmt = this.db.prepare(`
        INSERT INTO blackboard_entries (
          entry_id, project_id, topic, author_agent, payload, salience, claimed_by, claimed_until, created_at, updated_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ON CONFLICT(entry_id) DO UPDATE SET
          payload = excluded.payload,
          salience = excluded.salience,
          claimed_by = excluded.claimed_by,
          claimed_until = excluded.claimed_until,
          updated_at = excluded.updated_at
      `);
      stmt.run(
        entry.entry_id,
        entry.project_id || 'default',
        entry.topic,
        entry.author_agent,
        payloadStr,
        entry.salience ?? 0.5,
        entry.claimed_by || null,
        entry.claimed_until || null,
        entry.created_at || now,
        now
      );
      return entry;
    } catch (e) {
      console.error('[SqliteDb] saveBlackboardEntry 오류:', e.message);
      throw e;
    }
  }

  getBlackboardEntry(entryId) {
    try {
      const row = this.db.prepare(`SELECT * FROM blackboard_entries WHERE entry_id = ?`).get(entryId);
      if (!row) return null;
      return { ...row, payload: this._safeParse(row.payload) };
    } catch (e) {
      console.error('[SqliteDb] getBlackboardEntry 오류:', e.message);
      throw e;
    }
  }

  listBlackboardEntries(topic, options = {}) {
    try {
      const projectId = options.projectId || 'default';
      const limit = Math.min(options.limit || 50, 200);
      let query = `SELECT * FROM blackboard_entries WHERE project_id = ?`;
      const params = [projectId];
      if (topic) {
        query += ` AND topic = ?`;
        params.push(topic);
      }
      query += ` ORDER BY created_at DESC LIMIT ?`;
      params.push(limit);
      const rows = this.db.prepare(query).all(...params);
      return rows.map(r => ({ ...r, payload: this._safeParse(r.payload) }));
    } catch (e) {
      console.error('[SqliteDb] listBlackboardEntries 오류:', e.message);
      throw e;
    }
  }

  claimBlackboardTask(entryId, agentId, ttlMs = 60000) {
    try {
      const now = Date.now();
      const claimedUntil = now + ttlMs;
      // 원자적 선점: 미선점 상태이거나 TTL이 만료된 경우에만 UPDATE
      const stmt = this.db.prepare(`
        UPDATE blackboard_entries
        SET claimed_by = ?, claimed_until = ?, updated_at = ?
        WHERE entry_id = ? AND (claimed_by IS NULL OR claimed_until < ? OR claimed_by = ?)
      `);
      const res = stmt.run(agentId, claimedUntil, now, entryId, now, agentId);
      return res.changes > 0;
    } catch (e) {
      console.error('[SqliteDb] claimBlackboardTask 오류:', e.message);
      throw e;
    }
  }

  releaseBlackboardTask(entryId, agentId, resultPayload = null) {
    try {
      const now = Date.now();
      // Zombie Writer 방지: 본인이 여전히 Claimer인 경우에만 해제/업데이트
      let query = `UPDATE blackboard_entries SET claimed_by = NULL, claimed_until = NULL, updated_at = ?`;
      const params = [now];
      if (resultPayload !== null) {
        const payloadStr = typeof resultPayload === 'string' ? resultPayload : JSON.stringify(resultPayload);
        query += `, payload = ?`;
        params.push(payloadStr);
      }
      // 시간 조건을 UPDATE에 포함해 조회와 기록 사이의 만료 경합을 제거한다.
      query += ` WHERE entry_id = ? AND claimed_by = ? AND claimed_until >= ?`;
      params.push(entryId, agentId, now);
      const res = this.db.prepare(query).run(...params);
      return res.changes > 0;
    } catch (e) {
      console.error('[SqliteDb] releaseBlackboardTask 오류:', e.message);
      throw e;
    }
  }

  deleteBlackboardEntry(entryId) {
    try {
      return this.db.prepare(`DELETE FROM blackboard_entries WHERE entry_id = ?`).run(entryId).changes > 0;
    } catch (e) {
      console.error('[SqliteDb] deleteBlackboardEntry 오류:', e.message);
      throw e;
    }
  }

  _safeParse(str) {
    try { return JSON.parse(str || '{}'); }
    catch(e) {
      if (str && str !== '{}') {
        console.warn('[KnowledgeDB] _safeParse failed to parse JSON string:', str, e.message);
      }
      return {};
    }
  }
}

module.exports = SqliteDb;