asurada 0.3.1

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

mod adapter;
mod ai;
mod api;
mod config;
mod core;
mod credentials;
mod db;
mod detect;
mod hook;
mod paths;
mod pattern;
mod signals;
mod sync;
mod synthesis;
mod voice;

use anyhow::Result;
use clap::{Parser, Subcommand};
use tracing_subscriber::{fmt, EnvFilter};

#[derive(Parser)]
#[command(
    name = "asurada",
    version,
    about = "Asurada — your AI partner that grows with you"
)]
struct Cli {
    #[command(subcommand)]
    cmd: Cmd,
}

#[derive(Subcommand)]
enum Cmd {
    /// Initialize ~/.asurada/brain.db (run once at install)
    Init,
    /// 신규 사용자 cold start — 5문항으로 초기 intent seed
    Onboard,
    /// Start the HTTP server (foreground; daemon-mode handled by launchd)
    Serve {
        #[arg(long, default_value_t = 7878)]
        port: u16,
        /// 자동 패턴/진화 스캔 간격 (초). 0 이면 비활성화. 기본 300 (5분).
        #[arg(long, default_value_t = 300)]
        auto_pattern_interval: u64,
        /// 진화 후보 임계치 — 사용 후 30분 내 교정 N회 이상 시 advice 생성.
        #[arg(long, default_value_t = 2)]
        auto_evolution_threshold: usize,
        /// redo 군집 임계치 — 같은 prompt 가 N회 이상 반복 시 advice 생성.
        #[arg(long, default_value_t = 3)]
        auto_redo_threshold: usize,
    },
    /// Print resolved paths
    Path,
    /// brain.db ↔ Supabase sync 작업
    #[command(subcommand)]
    Sync(SyncCmd),
    /// TTS — ElevenLabs 음성으로 어드바이스를 읽음
    #[command(subcommand)]
    Tts(TtsCmd),
    /// 설정 조회 / 변경
    #[command(subcommand)]
    Config(ConfigCmd),
    /// Claude Code hook 통합 — 사용자 행동 관찰 + 통제 layer
    #[command(subcommand)]
    Hook(HookCmd),
    /// 누적된 행동 신호 조회 (intervention / redo 등)
    #[command(subcommand)]
    Signals(SignalsCmd),
    /// Intent — 사용자 개인성을 의도로 저장/적용 (preference/principle/context)
    #[command(subcommand)]
    Intent(IntentCmd),
    /// 신호 군집 감지 → advice 자동 제안 (Asurada 셀프 호스팅)
    #[command(subcommand)]
    Detect(DetectCmd),
    /// Advice 큐 — 사용자 confirm/promote 워크플로우
    #[command(subcommand)]
    Advice(AdviceCmd),
    /// 패턴 자동 생성 — 누적 패턴 → .claude/skills/<slug>/SKILL.md
    #[command(subcommand)]
    Pattern(PatternCmd),
    /// 일회성 관리 작업 (마이그레이션, 정리 등)
    #[command(subcommand)]
    Admin(AdminCmd),
    /// 음성 표현 — 인사 / 프로젝트 상태 발화
    #[command(subcommand)]
    Voice(VoiceCmd),
    /// 프로젝트 brief — 최근 활동을 Claude 가 해석해 메모리로 저장
    Brief {
        /// 대상 프로젝트 (생략 시 모든 활성 프로젝트)
        #[arg(long)]
        project: Option<String>,
        /// 회고할 일 수
        #[arg(long, default_value_t = 1)]
        days: i64,
    },
    /// 통합 회고 — 모든 프로젝트 가로지른 흐름을 사용자 메모리로 저장
    Reflect {
        /// 회고 윈도우 (1=오늘 흐름, 7=이번 주 패턴)
        #[arg(long, default_value_t = 1)]
        days: i64,
    },
    /// 작업 단위 issue — 최근 활동을 하나의 issue 로 응결
    #[command(subcommand)]
    Issue(IssueCmd),
    /// 누적 메모리 — Asurada 의 raw 관찰 (Dashboard 비노출, 전문 조회용)
    #[command(subcommand)]
    Memory(MemoryCmd),
}

#[derive(Subcommand)]
enum MemoryCmd {
    /// 메모리 목록 (최신순)
    List {
        /// scope 필터 (user | project | tech)
        #[arg(long)]
        scope: Option<String>,
        #[arg(long, default_value_t = 20)]
        limit: usize,
    },
    /// 메모리 단건 상세 (id prefix 매칭)
    Get { id: String },
    /// FTS5 키워드 검색
    Search {
        query: String,
        #[arg(long, default_value_t = 20)]
        limit: usize,
    },
}

#[derive(Subcommand)]
enum IssueCmd {
    /// 마지막 issue 이후의 활동을 새 issue 로 압축 (Claude 가 title + summary 생성)
    Capture {
        /// 마지막 issue 가 없을 때 fallback (몇 시간 전부터 볼지)
        #[arg(long, default_value_t = 24)]
        hours: i64,
    },
    /// 등록된 issue 목록 (최근순)
    List {
        #[arg(long, default_value_t = 20)]
        limit: usize,
    },
    /// issue 단건 상세 (id prefix 매칭)
    Get { id: String },
}

#[derive(Subcommand)]
enum VoiceCmd {
    /// 일일 인사 즉시 시도 — 이미 했으면 skip, 할 말 없으면 침묵
    Greet {
        /// 발화 안 하고 텍스트만 출력
        #[arg(long)]
        dry_run: bool,
    },
    /// 등록된 프로젝트 상태 요약 (멈춤/활동/advice 개수)
    Survey,
    /// 마지막 인사 시각 + 오늘 인사했는지
    Status,
}

#[derive(Subcommand)]
enum AdminCmd {
    /// events 의 project 케이스 정규화 — projects 테이블 name 을 canonical 로
    NormalizeEvents {
        /// 실제 갱신 (없으면 dry-run)
        #[arg(long)]
        apply: bool,
    },
}

#[derive(Subcommand)]
enum PatternCmd {
    /// 누적 패턴에서 skill 미리보기 (디스크 변경 없음)
    Propose {
        #[arg(long)]
        project: Option<String>,
        #[arg(long, default_value_t = 3)]
        threshold: usize,
        #[arg(long, default_value_t = 30)]
        days: i64,
    },
    /// 패턴 → skill 파일 실제 생성. project 등록 path 사용
    Apply {
        /// 적용할 군집의 signature (asurada pattern propose 출력에 표시)
        #[arg(long)]
        signature: i64,
        /// 프로젝트 이름 (brain.db projects 테이블에서 path 조회)
        #[arg(long)]
        project: String,
        /// 기존 SKILL.md 덮어쓰기
        #[arg(long)]
        force: bool,
    },
    /// 해당 프로젝트의 Asurada 생성 패턴 목록 (DB 기준)
    List {
        #[arg(long)]
        project: String,
    },
    /// 패턴 단건 상세 — 만든 이유, 진화 로그, 사용 횟수
    Get { id: String },
    /// 패턴 진화 후보 스캔 (사용 vs 교정 비율)
    EvolveScan {
        #[arg(long, default_value_t = 2)]
        intervention_threshold: usize,
        #[arg(long, default_value_t = 30)]
        days: i64,
        /// advice 큐에 실제 주입
        #[arg(long)]
        propose: bool,
    },
}

#[derive(Subcommand)]
enum DetectCmd {
    /// 누적 신호 스캔 → 군집 미리보기 (디스크 변경 없음)
    Scan {
        #[arg(long)]
        project: Option<String>,
        /// 최소 반복 횟수 — 이 이상이면 군집으로 인정
        #[arg(long, default_value_t = 3)]
        threshold: usize,
        /// 며칠치 신호를 볼지
        #[arg(long, default_value_t = 30)]
        days: i64,
    },
    /// 스캔 결과를 advice 로 주입 (idempotent — 이미 제안된 건 skip)
    Propose {
        #[arg(long)]
        project: Option<String>,
        #[arg(long, default_value_t = 3)]
        threshold: usize,
        #[arg(long, default_value_t = 30)]
        days: i64,
    },
}

#[derive(Subcommand)]
enum AdviceCmd {
    /// 미확인 advice 목록
    List {
        #[arg(long)]
        project: Option<String>,
        #[arg(long, default_value_t = 20)]
        limit: usize,
    },
    /// advice 단건 조회 (proposed_intent 등 metadata 포함)
    Get { id: String },
    /// advice 를 confirm 하고 proposed_intent 가 있으면 intent 로 승격
    Promote { id: String },
    /// advice 를 confirm 하되 intent 승격은 안 함 (단순 dismiss)
    Dismiss { id: String },
}

#[derive(Subcommand)]
enum IntentCmd {
    /// 새 intent 추가
    Add {
        /// preference | principle | context
        #[arg(long)]
        strength: String,
        /// 의도 본문 (자연어)
        text: String,
        /// 적용 범위 — 특정 프로젝트 이름 (생략 시 전역)
        #[arg(long)]
        project: Option<String>,
        /// principle 한정: 매칭할 도구 이름 (예: Bash, Edit)
        #[arg(long)]
        tool: Option<String>,
        /// principle 한정: 도구 입력에 포함되어야 할 substring
        #[arg(long)]
        contains: Option<String>,
        /// principle 한정: 매칭 시 응답 (ask | deny). 기본 ask.
        #[arg(long, default_value = "ask")]
        decision: String,
    },
    /// intent 목록
    List {
        #[arg(long)]
        project: Option<String>,
        #[arg(long)]
        strength: Option<String>,
        /// 비활성(archived) 도 포함
        #[arg(long)]
        all: bool,
    },
    /// intent 단건 조회
    Get { id: String },
    /// intent 보관 (적용 중지)
    Archive { id: String },
    /// 활성 intent → Claude Code 형식으로 컴파일 (CLAUDE.md + gates.json)
    Compile {
        /// 디스크에 쓰기 전 미리보기
        #[arg(long)]
        dry_run: bool,
        /// 프로젝트 한정 컴파일 (project + 전역 모두 포함)
        #[arg(long)]
        project: Option<String>,
    },
}

#[derive(Subcommand)]
enum SignalsCmd {
    /// 최근 신호 목록 (signal.intervention / signal.redo)
    Recent {
        #[arg(long)]
        project: Option<String>,
        #[arg(long, default_value_t = 20)]
        limit: usize,
    },
    /// 신호 종류별 카운트 요약
    Summary {
        #[arg(long)]
        project: Option<String>,
    },
}

#[derive(Subcommand)]
enum HookCmd {
    /// (Claude Code 가 호출) stdin JSON 페이로드 → decision JSON.
    Check { event: String },
    /// `~/.claude/settings.json` 에 hook 자동 등록 (Phase 1: passthrough)
    Install,
    /// 등록된 asurada hook 제거
    Uninstall,
    /// 현재 hook 등록 상태 출력
    Status,
}

#[derive(Subcommand)]
enum ConfigCmd {
    /// 현재 config 출력 (비밀 mask)
    Show,
    /// config 파일 경로
    Path,
    /// 값 설정. 예: `asurada config set database.url 'postgresql://...'`
    Set { key: String, value: String },
}

#[derive(Subcommand)]
enum TtsCmd {
    /// TTS 활성화 (config.toml.tts.enabled = true)
    On,
    /// TTS 비활성화
    Off,
    /// TTS 상태 / 키 / voice 확인
    Status,
    /// 사용 가능한 voice 목록 (ElevenLabs 계정의 voice 들)
    Voices,
    /// 임의 텍스트 음성 합성 + 재생 (테스트용)
    Test { text: String },
    /// 미확인 어드바이스를 음성으로 읽기
    Speak {
        #[arg(long)]
        project: Option<String>,
        #[arg(long, default_value_t = 1)]
        limit: usize,
    },
}

#[derive(Subcommand)]
enum SyncCmd {
    /// brain.db → Supabase 한 번 push (모든 테이블)
    Push,
    /// Supabase → brain.db 한 번 pull (모든 테이블)
    Pull,
    /// push + pull 한 번씩 실행
    Run,
}

#[tokio::main]
async fn main() -> Result<()> {
    fmt()
        .with_env_filter(
            EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")),
        )
        .init();

    let cli = Cli::parse();
    match cli.cmd {
        Cmd::Init => cmd_init().await,
        Cmd::Onboard => cmd_onboard(),
        Cmd::Serve {
            port,
            auto_pattern_interval,
            auto_evolution_threshold,
            auto_redo_threshold,
        } => {
            cmd_serve(
                port,
                auto_pattern_interval,
                auto_evolution_threshold,
                auto_redo_threshold,
            )
            .await
        }
        Cmd::Path => cmd_path(),
        Cmd::Sync(sub) => match sub {
            SyncCmd::Push => cmd_sync_push().await,
            SyncCmd::Pull => cmd_sync_pull().await,
            SyncCmd::Run => cmd_sync_run().await,
        },
        Cmd::Tts(sub) => match sub {
            TtsCmd::On => cmd_tts_set(true).await,
            TtsCmd::Off => cmd_tts_set(false).await,
            TtsCmd::Status => cmd_tts_status().await,
            TtsCmd::Voices => cmd_tts_voices().await,
            TtsCmd::Test { text } => cmd_tts_test(text).await,
            TtsCmd::Speak { project, limit } => cmd_tts_speak(project, limit).await,
        },
        Cmd::Config(sub) => match sub {
            ConfigCmd::Show => cmd_config_show().await,
            ConfigCmd::Path => cmd_config_path(),
            ConfigCmd::Set { key, value } => cmd_config_set(key, value).await,
        },
        Cmd::Hook(sub) => match sub {
            HookCmd::Check { event } => {
                let evt = hook::HookEvent::parse(&event).ok_or_else(|| {
                    anyhow::anyhow!(
                        "unknown hook event: {} \
                         (expected pre-tool-use|post-tool-use|user-prompt-submit|stop|session-start|session-end)",
                        event
                    )
                })?;
                hook::cmd_check(evt)
            }
            HookCmd::Install => cmd_hook_install(),
            HookCmd::Uninstall => cmd_hook_uninstall(),
            HookCmd::Status => cmd_hook_status(),
        },
        Cmd::Signals(sub) => match sub {
            SignalsCmd::Recent { project, limit } => cmd_signals_recent(project, limit),
            SignalsCmd::Summary { project } => cmd_signals_summary(project),
        },
        Cmd::Intent(sub) => match sub {
            IntentCmd::Add {
                strength,
                text,
                project,
                tool,
                contains,
                decision,
            } => cmd_intent_add(strength, text, project, tool, contains, decision),
            IntentCmd::List {
                project,
                strength,
                all,
            } => cmd_intent_list(project, strength, all),
            IntentCmd::Get { id } => cmd_intent_get(id),
            IntentCmd::Archive { id } => cmd_intent_archive(id),
            IntentCmd::Compile { dry_run, project } => cmd_intent_compile(dry_run, project),
        },
        Cmd::Detect(sub) => match sub {
            DetectCmd::Scan {
                project,
                threshold,
                days,
            } => cmd_detect_scan(project, threshold, days, false),
            DetectCmd::Propose {
                project,
                threshold,
                days,
            } => cmd_detect_scan(project, threshold, days, true),
        },
        Cmd::Advice(sub) => match sub {
            AdviceCmd::List { project, limit } => cmd_advice_list(project, limit),
            AdviceCmd::Get { id } => cmd_advice_get(id),
            AdviceCmd::Promote { id } => cmd_advice_promote(id),
            AdviceCmd::Dismiss { id } => cmd_advice_dismiss(id),
        },
        Cmd::Admin(sub) => match sub {
            AdminCmd::NormalizeEvents { apply } => cmd_admin_normalize_events(apply),
        },
        Cmd::Voice(sub) => match sub {
            VoiceCmd::Greet { dry_run } => cmd_voice_greet(dry_run).await,
            VoiceCmd::Survey => cmd_voice_survey(),
            VoiceCmd::Status => cmd_voice_status(),
        },
        Cmd::Brief { project, days } => cmd_brief(project, days).await,
        Cmd::Reflect { days } => cmd_reflect(days).await,
        Cmd::Issue(sub) => match sub {
            IssueCmd::Capture { hours } => cmd_issue_capture(hours).await,
            IssueCmd::List { limit } => cmd_issue_list(limit),
            IssueCmd::Get { id } => cmd_issue_get(id),
        },
        Cmd::Memory(sub) => match sub {
            MemoryCmd::List { scope, limit } => cmd_memory_list(scope, limit),
            MemoryCmd::Get { id } => cmd_memory_get(id),
            MemoryCmd::Search { query, limit } => cmd_memory_search(query, limit),
        },
        Cmd::Pattern(sub) => match sub {
            PatternCmd::Propose {
                project,
                threshold,
                days,
            } => cmd_pattern_propose(project, threshold, days),
            PatternCmd::Apply {
                signature,
                project,
                force,
            } => cmd_pattern_apply(signature, project, force),
            PatternCmd::List { project } => cmd_pattern_list(project),
            PatternCmd::Get { id } => cmd_pattern_get(id),
            PatternCmd::EvolveScan {
                intervention_threshold,
                days,
                propose,
            } => cmd_pattern_evolve_scan(intervention_threshold, days, propose),
        },
    }
}

// ── Hook 명령 ───────────────────────────────────────────

fn cmd_hook_install() -> Result<()> {
    let report = hook::settings::install()?;
    println!("✓ hook 등록 완료");
    println!("  settings.json: {}", report.path.display());
    println!("  binary:        {}", report.bin);
    println!("  events:        {}", report.events.join(", "));
    println!();
    println!("Phase 1 passthrough — Claude Code 의 모든 도구 호출/프롬프트가");
    println!("brain.db 의 events 테이블에 기록됩니다 (차단 없음).");
    println!();
    println!("새 Claude Code 세션부터 적용됩니다.");
    Ok(())
}

fn cmd_hook_uninstall() -> Result<()> {
    let report = hook::settings::uninstall()?;
    if report.removed.is_empty() {
        println!(
            "등록된 asurada hook 이 없습니다 ({}).",
            report.path.display()
        );
    } else {
        println!("✓ hook 제거: {}", report.removed.join(", "));
        println!("  settings.json: {}", report.path.display());
    }
    Ok(())
}

fn cmd_hook_status() -> Result<()> {
    let path = hook::settings::settings_path()?;
    let active = hook::settings::status()?;
    if active.is_empty() {
        println!("hook 미등록 ({})", path.display());
        println!("  설치: asurada hook install");
    } else {
        println!("hook 등록됨 ({})", path.display());
        println!("  events: {}", active.join(", "));
    }
    Ok(())
}

// ── Signals 명령 ───────────────────────────────────────

fn cmd_signals_recent(project: Option<String>, limit: usize) -> Result<()> {
    use rusqlite::params;
    let cfg = load_config()?;
    let conn = db::open(&paths::brain_db()?)?;

    let sql = if project.is_some() {
        r#"SELECT created_at, event_type, project, payload
           FROM events
           WHERE user_id = ?1 AND project = ?2
             AND event_type IN ('signal.intervention', 'signal.redo')
           ORDER BY created_at DESC LIMIT ?3"#
    } else {
        r#"SELECT created_at, event_type, project, payload
           FROM events
           WHERE user_id = ?1
             AND event_type IN ('signal.intervention', 'signal.redo')
           ORDER BY created_at DESC LIMIT ?2"#
    };
    let mut stmt = conn.prepare(sql)?;
    let rows: Vec<(String, String, String, String)> = if let Some(p) = project.as_deref() {
        stmt.query_map(params![&cfg.user.id, p, limit as i64], |r| {
            Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?))
        })?
        .filter_map(|r| r.ok())
        .collect()
    } else {
        stmt.query_map(params![&cfg.user.id, limit as i64], |r| {
            Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?))
        })?
        .filter_map(|r| r.ok())
        .collect()
    };

    if rows.is_empty() {
        println!("(누적된 신호 없음)");
        return Ok(());
    }
    for (created, kind, proj, payload) in rows {
        let pv: serde_json::Value =
            serde_json::from_str(&payload).unwrap_or(serde_json::Value::Null);
        let detail = match kind.as_str() {
            "signal.intervention" => format!(
                "patterns={}",
                pv.get("patterns")
                    .map(|v| v.to_string())
                    .unwrap_or_default()
            ),
            "signal.redo" => format!(
                "prior={} | {}",
                pv.get("prior_count").and_then(|v| v.as_u64()).unwrap_or(0),
                pv.get("prompt_preview")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
            ),
            _ => "".into(),
        };
        println!("{}  [{}]  {:24}  {}", created, proj, kind, detail);
    }
    Ok(())
}

// ── Intent 명령 ────────────────────────────────────────

fn cmd_intent_add(
    strength: String,
    text: String,
    project: Option<String>,
    tool: Option<String>,
    contains: Option<String>,
    decision: String,
) -> Result<()> {
    let s = db::intent::Strength::parse(&strength).ok_or_else(|| {
        anyhow::anyhow!(
            "strength 는 preference|principle|context 중 하나여야 합니다 (입력: {})",
            strength
        )
    })?;
    if !matches!(decision.as_str(), "ask" | "deny" | "allow") {
        anyhow::bail!(
            "decision 은 ask|deny|allow 중 하나여야 합니다 (입력: {})",
            decision
        );
    }

    let cfg = load_config()?;
    let conn = db::open(&paths::brain_db()?)?;

    let mut metadata = serde_json::json!({});
    if s == db::intent::Strength::Principle && (tool.is_some() || contains.is_some()) {
        let mut trigger = serde_json::Map::new();
        if let Some(t) = tool {
            trigger.insert("tool".into(), serde_json::Value::String(t));
        }
        if let Some(c) = contains {
            trigger.insert("contains".into(), serde_json::Value::String(c));
        }
        metadata["trigger"] = serde_json::Value::Object(trigger);
        metadata["decision"] = serde_json::Value::String(decision);
    }

    let intent = db::intent::insert(
        &conn,
        db::intent::IntentInput {
            user_id: cfg.user.id,
            project,
            strength: s,
            intent_text: text,
            source: db::intent::Source::User,
            source_signal_ids: vec![],
            metadata,
        },
    )?;
    println!("✓ intent 추가됨: {}", intent.id);
    println!(
        "  strength: {} ({})",
        s.as_str(),
        adapter::strength_label(s)
    );
    println!("  text:     {}", intent.intent_text);
    if let Some(p) = &intent.project {
        println!("  project:  {}", p);
    } else {
        println!("  project:  (전역)");
    }
    println!();
    println!("적용하려면: asurada intent compile");
    Ok(())
}

fn cmd_intent_list(project: Option<String>, strength: Option<String>, all: bool) -> Result<()> {
    let cfg = load_config()?;
    let conn = db::open(&paths::brain_db()?)?;
    let strength_filter = strength.as_deref().and_then(db::intent::Strength::parse);

    let intents = if all {
        db::intent::list_all(&conn, &cfg.user.id)?
    } else {
        db::intent::list_active(&conn, &cfg.user.id, project.as_deref(), strength_filter)?
    };

    if intents.is_empty() {
        println!("(intent 없음)");
        return Ok(());
    }
    for it in intents {
        let scope = it.project.as_deref().unwrap_or("(전역)");
        println!(
            "{:8}  {:10}  {:14}  {}",
            &it.id[..8.min(it.id.len())],
            it.strength.as_str(),
            scope,
            it.intent_text.trim()
        );
    }
    Ok(())
}

fn cmd_intent_get(id: String) -> Result<()> {
    let cfg = load_config()?;
    let conn = db::open(&paths::brain_db()?)?;
    // 짧은 ID prefix 도 허용.
    let all = db::intent::list_all(&conn, &cfg.user.id)?;
    let found = all.iter().find(|i| i.id.starts_with(&id));
    let Some(it) = found else {
        anyhow::bail!("intent 없음: {}", id);
    };
    println!("id:        {}", it.id);
    println!(
        "strength:  {} ({})",
        it.strength.as_str(),
        adapter::strength_label(it.strength)
    );
    println!("status:    {}", it.status.as_str());
    println!("project:   {}", it.project.as_deref().unwrap_or("(전역)"));
    println!("source:    {}", it.source.as_str());
    println!("created:   {}", it.created_at);
    println!("text:");
    println!("  {}", it.intent_text);
    if !it.metadata.is_null() && it.metadata != serde_json::json!({}) {
        println!("metadata:");
        println!("  {}", serde_json::to_string_pretty(&it.metadata)?);
    }
    Ok(())
}

fn cmd_intent_archive(id: String) -> Result<()> {
    let cfg = load_config()?;
    let conn = db::open(&paths::brain_db()?)?;
    let all = db::intent::list_all(&conn, &cfg.user.id)?;
    let found = all.iter().find(|i| i.id.starts_with(&id));
    let Some(it) = found else {
        anyhow::bail!("intent 없음: {}", id);
    };
    db::intent::set_status(&conn, &it.id, db::intent::Status::Archived)?;
    println!("✓ intent 보관됨: {}", it.id);
    println!("  적용 중지하려면: asurada intent compile");
    Ok(())
}

fn cmd_intent_compile(dry_run: bool, project: Option<String>) -> Result<()> {
    use adapter::RuntimeAdapter;
    let cfg = load_config()?;
    let conn = db::open(&paths::brain_db()?)?;
    let intents = db::intent::list_active(&conn, &cfg.user.id, project.as_deref(), None)?;
    let patterns = db::pattern::list(&conn, &cfg.user.id, project.as_deref())?;

    if intents.is_empty() && patterns.is_empty() {
        println!("(활성 intent / 패턴 없음 — 컴파일할 게 없음)");
        return Ok(());
    }

    let ad = adapter::claude_code::ClaudeCodeAdapter::default()?;
    let artifacts = ad.compile(&intents, &patterns)?;

    println!("─ 컴파일 결과 ─────────────────────────");
    for block in &artifacts.text_blocks {
        let target_label = match &block.target {
            adapter::BlockTarget::GlobalClaudeMd => ad.global_claude_md.display().to_string(),
            adapter::BlockTarget::ProjectClaudeMd(p) => p.display().to_string(),
        };
        let line_count = block.body.lines().count();
        println!(
            "[block {} ({} 줄) → {}]",
            block.id, line_count, target_label
        );
        for line in block.body.lines() {
            println!("  {}", line);
        }
        println!();
    }
    for gf in &artifacts.files {
        let line_count = gf.body.lines().count();
        println!("[file ({} 줄) → {}]", line_count, gf.path.display());
        println!();
    }
    if !artifacts.gate_rules.is_empty() {
        println!("[gate rules → {}]", ad.gates_path.display());
        for r in &artifacts.gate_rules {
            println!(
                "  - {} ({}{}) → {}",
                r.reason,
                r.tool.as_deref().unwrap_or("*"),
                r.contains
                    .as_deref()
                    .map(|c| format!(" contains {:?}", c))
                    .unwrap_or_default(),
                r.decision
            );
        }
        println!();
    }

    if dry_run {
        println!("(dry-run — 디스크에 쓰지 않음. 적용하려면 --dry-run 제외)");
        return Ok(());
    }

    let report = ad.apply(&artifacts)?;
    println!("─ 적용 완료 ────────────────────────────");
    if !report.blocks_updated.is_empty() {
        println!("  blocks: {}", report.blocks_updated.join(", "));
    }
    println!("  gate rules: {}", report.gate_rules_count);
    println!("  files:");
    for f in &report.files_written {
        println!("    {}", f.display());
    }
    Ok(())
}

// ── Pattern / Advice 명령 ──────────────────────────────

fn cmd_detect_scan(
    project: Option<String>,
    threshold: usize,
    days: i64,
    apply: bool,
) -> Result<()> {
    let cfg = load_config()?;
    let conn = db::open(&paths::brain_db()?)?;
    let clusters =
        detect::scan_redo_clusters(&conn, &cfg.user.id, project.as_deref(), days, threshold)?;

    if clusters.is_empty() {
        println!("(군집 없음 — threshold={}, days={})", threshold, days);
        return Ok(());
    }

    println!("─ Redo 군집 ({}개) ─────────────────", clusters.len());
    for c in &clusters {
        let preview = c
            .prompt_preview
            .as_deref()
            .map(|p| {
                let s: String = p.chars().take(50).collect();
                if p.chars().count() > 50 {
                    format!("{}", s)
                } else {
                    s
                }
            })
            .unwrap_or_else(|| "(no preview)".into());
        println!(
            "  [{}회]  project={}  last={}  \"{}\"",
            c.count, c.project, c.last_seen, preview
        );
    }

    if !apply {
        println!();
        println!("실제로 advice 큐에 주입하려면: asurada pattern propose ...");
        return Ok(());
    }

    let added = detect::propose_from_clusters(&conn, &cfg.user.id, &clusters)?;
    let skipped = clusters.len() - added;
    println!();
    println!(
        "✓ advice 추가: {} (skip={} — 이미 제안된 군집)",
        added, skipped
    );
    if added > 0 {
        println!("검토: asurada advice list");
    }
    Ok(())
}

fn cmd_advice_list(project: Option<String>, limit: usize) -> Result<()> {
    let cfg = load_config()?;
    let conn = db::open(&paths::brain_db()?)?;
    let pending = db::advice::list_pending(&conn, &cfg.user.id, project.as_deref(), limit)?;
    if pending.is_empty() {
        println!("(미확인 advice 없음)");
        return Ok(());
    }
    for a in pending {
        let id_short = &a.id[..8.min(a.id.len())];
        let preview: String = a.text.chars().take(70).collect();
        let ellipsis = if a.text.chars().count() > 70 {
            ""
        } else {
            ""
        };
        let has_proposal = a.metadata.get("proposed_intent").is_some();
        let marker = if has_proposal { "[promotable]" } else { "" };
        println!(
            "{:8}  [{}]  {} {}{}",
            id_short, a.severity, marker, preview, ellipsis
        );
    }
    Ok(())
}

fn cmd_advice_get(id: String) -> Result<()> {
    let cfg = load_config()?;
    let conn = db::open(&paths::brain_db()?)?;
    let all = db::advice::list_pending(&conn, &cfg.user.id, None, 1000)?;
    let found = all.iter().find(|a| a.id.starts_with(&id));
    let Some(a) = found else {
        anyhow::bail!("advice 없음 (또는 이미 처리됨): {}", id);
    };
    println!("id:        {}", a.id);
    println!("project:   {}", a.project);
    println!("severity:  {}", a.severity);
    println!("state:     {}", a.state);
    println!("created:   {}", a.created_at);
    println!("text:");
    for line in a.text.lines() {
        println!("  {}", line);
    }
    if !a.metadata.is_null() && a.metadata != serde_json::json!({}) {
        println!("metadata:");
        println!("  {}", serde_json::to_string_pretty(&a.metadata)?);
    }
    if a.metadata.get("proposed_intent").is_some() {
        println!();
        println!("승격: asurada advice promote {}", a.id);
    }
    Ok(())
}

fn cmd_advice_promote(id: String) -> Result<()> {
    let cfg = load_config()?;
    let conn = db::open(&paths::brain_db()?)?;
    let pending = db::advice::list_pending(&conn, &cfg.user.id, None, 1000)?;
    let advice_id = pending
        .iter()
        .find(|a| a.id.starts_with(&id))
        .map(|a| a.id.clone())
        .ok_or_else(|| anyhow::anyhow!("미확인 advice 없음: {}", id))?;

    match detect::promote_advice(&conn, &cfg.user.id, &advice_id)? {
        detect::PromoteResult::NewIntent(it) => {
            println!("✓ advice → intent 승격");
            println!("  advice id: {}", advice_id);
            println!("  intent id: {}", it.id);
            println!("  strength:  {}", it.strength.as_str());
            println!("  text:      {}", it.intent_text);
            println!();
            println!("적용: asurada intent compile");
        }
        detect::PromoteResult::PatternEvolved {
            pattern_id,
            skill_path,
        } => {
            println!("✓ 패턴 진화 적용");
            println!("  advice id:   {}", advice_id);
            println!("  pattern id:  {}", pattern_id);
            println!("  갱신 파일:    {}", skill_path.display());
            println!();
            println!("진화 로그: asurada pattern get {}", pattern_id);
        }
    }
    Ok(())
}

fn cmd_advice_dismiss(id: String) -> Result<()> {
    let cfg = load_config()?;
    let conn = db::open(&paths::brain_db()?)?;
    let pending = db::advice::list_pending(&conn, &cfg.user.id, None, 1000)?;
    let advice_id = pending
        .iter()
        .find(|a| a.id.starts_with(&id))
        .map(|a| a.id.clone())
        .ok_or_else(|| anyhow::anyhow!("미확인 advice 없음: {}", id))?;
    db::advice::confirm(&conn, &cfg.user.id, &advice_id, "dismiss")?;
    db::advice::set_state(&conn, &cfg.user.id, &advice_id, "done")?;
    println!("✓ advice dismiss: {}", advice_id);
    Ok(())
}

// ── Pattern 명령 ────────────────────────────────────────

fn cmd_pattern_propose(project: Option<String>, threshold: usize, days: i64) -> Result<()> {
    let cfg = load_config()?;
    let conn = db::open(&paths::brain_db()?)?;
    let clusters =
        detect::scan_redo_clusters(&conn, &cfg.user.id, project.as_deref(), days, threshold)?;
    if clusters.is_empty() {
        println!("(군집 없음 — threshold={}, days={})", threshold, days);
        return Ok(());
    }
    println!("─ 패턴 제안 ({}개) ─────────────────", clusters.len());
    for c in &clusters {
        // 미리보기는 풀 proposal — 단, project_path 가 없는 경우도 있을 수 있어
        // 가짜 root 로 경로만 보여줌.
        let dummy_root = std::path::Path::new(".");
        let p = pattern::propose_full_pattern(&conn, &cfg.user.id, c, dummy_root)?;
        println!();
        println!(
            "[signature {}]  project={}  count={}",
            c.signature, c.project, c.count
        );
        println!("  제목:        {}", p.title);
        println!("  슬러그:      {}", p.slug);
        println!("  설명:        {}", p.description);
        println!("  생성될 파일:");
        println!("    {}", p.agent_path.display());
        println!("    {}", p.skill_path.display());
        println!("    {}", p.origin_ref_path.display());
        if !p.action_summary.is_empty() {
            println!(
                "  과거 도구 사용 (top {}): {}",
                p.action_summary.len().min(5),
                p.action_summary
                    .iter()
                    .take(5)
                    .map(|(t, n)| format!("{}({})", t, n))
                    .collect::<Vec<_>>()
                    .join(", ")
            );
        }
        println!(
            "  적용:        asurada pattern apply --signature {} --project {}",
            c.signature, c.project
        );
    }
    Ok(())
}

fn cmd_pattern_apply(signature: i64, project_name: String, force: bool) -> Result<()> {
    let cfg = load_config()?;
    let conn = db::open(&paths::brain_db()?)?;
    let project_path = pattern::resolve_project_path(&conn, &cfg.user.id, &project_name)?;

    // 해당 signature 의 군집 재조회 (프롬프트/카운트 최신화).
    let clusters = detect::scan_redo_clusters(&conn, &cfg.user.id, Some(&project_name), 365, 1)?;
    let cluster = clusters
        .into_iter()
        .find(|c| c.signature == signature)
        .ok_or_else(|| {
            anyhow::anyhow!(
                "signature {} 군집 없음 (project={}). asurada pattern propose 로 확인.",
                signature,
                project_name
            )
        })?;

    let proposal = pattern::propose_full_pattern(&conn, &cfg.user.id, &cluster, &project_path)?;
    let record = pattern::apply_full_pattern(&conn, &cfg.user.id, &project_path, &proposal, force)?;

    println!("✓ Full pattern 생성 완료");
    println!("  pattern id:  {}", record.id);
    println!("  제목:        {}", record.title);
    println!("  슬러그:      {}", record.slug);
    println!("  signature:   {:016x}", proposal.trigger_signature as u64);
    println!("  파일:");
    for f in &record.file_paths {
        println!("    {}/{}", project_path.display(), f);
    }
    println!();
    println!("다음 단계:");
    println!("  - 다음 Claude Code 세션에서 이 skill+agent 가 자동 트리거 후보가 됩니다");
    println!("  - 사용 시 사용량/진화 로그가 자동으로 누적됩니다");
    println!("  - `asurada pattern get {}` 로 진화 로그 확인", record.id);
    Ok(())
}

fn cmd_pattern_list(project_name: String) -> Result<()> {
    let cfg = load_config()?;
    let conn = db::open(&paths::brain_db()?)?;
    let records = db::pattern::list(&conn, &cfg.user.id, Some(&project_name))?;
    if records.is_empty() {
        println!("(이 프로젝트에 Asurada 생성 패턴 없음)");
        println!("  생성: asurada pattern propose / apply");
        return Ok(());
    }
    println!("{:8}  {:14}  {:6}  title", "id", "slug", "uses");
    for h in records {
        let id_short = &h.id[..8.min(h.id.len())];
        let slug_short: String = h.slug.chars().take(14).collect();
        println!(
            "{:8}  {:14}  {:6}  {}",
            id_short, slug_short, h.usage_count, h.title
        );
    }
    Ok(())
}

fn cmd_pattern_evolve_scan(threshold: usize, days: i64, propose: bool) -> Result<()> {
    let cfg = load_config()?;
    let conn = db::open(&paths::brain_db()?)?;
    let candidates =
        detect::scan_pattern_evolution_candidates(&conn, &cfg.user.id, threshold, days)?;
    if candidates.is_empty() {
        println!("(진화 후보 없음 — threshold={}, days={})", threshold, days);
        return Ok(());
    }
    println!("─ 진화 후보 ({}개) ─────────────────", candidates.len());
    for c in &candidates {
        println!();
        println!(
            "  [{}]  uses={}  교정={}",
            c.pattern_title, c.use_count, c.intervention_count
        );
        println!("  pattern: {} ({})", c.pattern_id, c.pattern_slug);
        if !c.recent_intervention_prompts.is_empty() {
            println!("  최근 교정 prompt:");
            for p in c.recent_intervention_prompts.iter().take(3) {
                let s: String = p.chars().take(60).collect();
                println!(
                    "    - \"{}{}\"",
                    s,
                    if p.chars().count() > 60 { "" } else { "" }
                );
            }
        }
    }
    if !propose {
        println!();
        println!("실제로 advice 큐에 주입하려면: --propose");
        return Ok(());
    }
    let mut added = 0usize;
    for c in &candidates {
        if detect::already_proposed_evolution(&conn, &cfg.user.id, &c.pattern_id)? {
            continue;
        }
        detect::propose_pattern_evolution(&conn, &cfg.user.id, c)?;
        added += 1;
    }
    println!();
    println!(
        "✓ 진화 advice 주입: {} (skip={} — 미확인 진화 advice 이미 있음)",
        added,
        candidates.len() - added
    );
    if added > 0 {
        println!("검토: asurada advice list");
    }
    Ok(())
}

fn cmd_pattern_get(id: String) -> Result<()> {
    let cfg = load_config()?;
    let conn = db::open(&paths::brain_db()?)?;
    let all = db::pattern::list(&conn, &cfg.user.id, None)?;
    let h = all
        .into_iter()
        .find(|h| h.id.starts_with(&id))
        .ok_or_else(|| anyhow::anyhow!("패턴 없음: {}", id))?;

    println!("id:           {}", h.id);
    println!("project:      {}", h.project);
    println!("slug:         {}", h.slug);
    println!("title:        {}", h.title);
    println!("description:  {}", h.description);
    println!("status:       {}", h.status);
    println!("usage_count:  {}", h.usage_count);
    if let Some(last) = &h.last_used_at {
        println!("last_used_at: {}", last);
    }
    println!("created:      {}", h.created_at);
    println!();
    println!("─ 만든 이유 ────────────────────────────");
    for line in h.reason.lines() {
        println!("{}", line);
    }
    println!();
    println!("─ 파일 ──────────────────────────────────");
    for f in &h.file_paths {
        println!("  {}", f);
    }
    println!();
    println!("─ 진화 로그 ────────────────────────────");
    for entry in &h.evolution_log {
        let advice = entry
            .source_advice_id
            .as_deref()
            .map(|a| format!(" (advice: {})", a))
            .unwrap_or_default();
        println!(
            "  {} [{}] {}{}",
            entry.at, entry.kind, entry.summary, advice
        );
    }
    Ok(())
}

fn cmd_signals_summary(project: Option<String>) -> Result<()> {
    use rusqlite::params;
    let cfg = load_config()?;
    let conn = db::open(&paths::brain_db()?)?;

    let (sql, has_project) = if project.is_some() {
        (
            r#"SELECT event_type, COUNT(*)
               FROM events
               WHERE user_id = ?1 AND project = ?2
                 AND event_type LIKE 'signal.%'
               GROUP BY event_type"#,
            true,
        )
    } else {
        (
            r#"SELECT event_type, COUNT(*)
               FROM events
               WHERE user_id = ?1
                 AND event_type LIKE 'signal.%'
               GROUP BY event_type"#,
            false,
        )
    };
    let mut stmt = conn.prepare(sql)?;
    let rows: Vec<(String, i64)> = if has_project {
        stmt.query_map(params![&cfg.user.id, project.as_deref().unwrap()], |r| {
            Ok((r.get(0)?, r.get(1)?))
        })?
        .filter_map(|r| r.ok())
        .collect()
    } else {
        stmt.query_map(params![&cfg.user.id], |r| Ok((r.get(0)?, r.get(1)?)))?
            .filter_map(|r| r.ok())
            .collect()
    };

    if rows.is_empty() {
        println!("(누적된 신호 없음)");
        return Ok(());
    }
    for (kind, count) in rows {
        println!("{:28}  {}", kind, count);
    }
    Ok(())
}

// ── Config 명령 ─────────────────────────────────────────

fn mask(s: &str) -> String {
    if s.len() <= 8 {
        return "***".into();
    }
    format!("{}{}", &s[..4], &s[s.len() - 4..])
}

async fn cmd_config_show() -> Result<()> {
    let cfg = config::Config::load(&paths::config_file()?)?;
    println!("[user]");
    println!("  id = {}", cfg.user.id);
    println!();
    println!("[database]");
    // password 부분 mask.
    let url_display = if let Some(at) = cfg.database.url.find('@') {
        let (creds, host) = cfg.database.url.split_at(at);
        if let Some(colon) = creds.rfind(':') {
            format!("{}:***{}", &creds[..colon], host)
        } else {
            cfg.database.url.clone()
        }
    } else {
        cfg.database.url.clone()
    };
    println!("  url = {}", url_display);
    println!();
    println!("[server]");
    println!("  port = {}", cfg.server.port);
    println!("  bind = {}", cfg.server.bind);
    println!();
    println!("[tts]");
    println!("  enabled  = {}", cfg.tts.enabled);
    println!(
        "  voice_id = {}",
        cfg.tts.voice_id.as_deref().unwrap_or("(not set)")
    );
    println!(
        "  api_key  = {}",
        cfg.tts
            .api_key
            .as_deref()
            .map(mask)
            .unwrap_or_else(|| "(not set)".into())
    );
    Ok(())
}

fn cmd_config_path() -> Result<()> {
    println!("{}", paths::config_file()?.display());
    Ok(())
}

async fn cmd_config_set(key: String, value: String) -> Result<()> {
    let path = paths::config_file()?;
    let mut cfg = config::Config::load(&path)?;
    match key.as_str() {
        "database.url" => {
            if !value.starts_with("postgres://") && !value.starts_with("postgresql://") {
                return Err(anyhow::anyhow!(
                    "URL 은 'postgresql://' 또는 'postgres://' 로 시작해야 합니다."
                ));
            }
            cfg.database.url = value;
        }
        "server.port" => {
            cfg.server.port = value
                .parse()
                .map_err(|_| anyhow::anyhow!("must be a number (1-65535)"))?
        }
        "server.bind" => cfg.server.bind = value,
        "tts.enabled" => {
            cfg.tts.enabled = value
                .parse()
                .map_err(|_| anyhow::anyhow!("must be true/false"))?
        }
        "tts.voice_id" => cfg.tts.voice_id = if value.is_empty() { None } else { Some(value) },
        "tts.api_key" => cfg.tts.api_key = if value.is_empty() { None } else { Some(value) },
        // user.id 보호 — 함부로 바꾸면 user_id 별 데이터 끊김.
        "user.id" => {
            return Err(anyhow::anyhow!(
                "user.id 는 직접 설정 불가.\n\
                 신규 발급은 config.toml 삭제 후 `asurada init` (기존 데이터 격리됨)"
            ));
        }
        _ => {
            return Err(anyhow::anyhow!(
                "Unknown key: {}\n\n\
                 사용 가능한 키:\n\
                 \tdatabase.url       Postgres connection string\n\
                 \tserver.port        HTTP API 포트 (기본 7878)\n\
                 \tserver.bind        bind 주소 (기본 127.0.0.1)\n\
                 \ttts.enabled        true | false\n\
                 \ttts.voice_id       ElevenLabs voice id\n\
                 \ttts.api_key        ElevenLabs API key\n\n\
                 read-only:\n\
                 \tuser.id            UUID (init 시 자동 발급, 변경 불가)",
                key
            ));
        }
    }
    cfg.save(&path)?;
    println!("{} 설정됨", key);
    if key.starts_with("database.") || key.starts_with("server.") {
        println!("  데몬 재시작 필요: launchctl kickstart -k gui/$(id -u)/dev.webchemist.asurada");
    }
    Ok(())
}

// ── TTS 명령 구현 ─────────────────────────────────────────

/// ElevenLabs API 키 로드 — env 우선, 그 다음 config.toml.
fn elevenlabs_key() -> Result<String> {
    if let Ok(k) = std::env::var("ASURADA_ELEVENLABS_API_KEY") {
        if !k.is_empty() {
            return Ok(k);
        }
    }
    let cfg = load_config()?;
    cfg.tts.api_key.clone().ok_or_else(|| {
        anyhow::anyhow!(
            "ElevenLabs API 키 미설정.\n\
             ASURADA_ELEVENLABS_API_KEY env 또는 config.toml [tts] api_key 에 설정.\n\
             https://elevenlabs.io 에서 발급."
        )
    })
}

fn load_config() -> Result<config::Config> {
    config::Config::load(&paths::config_file()?)
}

async fn cmd_tts_set(enabled: bool) -> Result<()> {
    let mut cfg = load_config()?;
    cfg.tts.enabled = enabled;
    cfg.save(&paths::config_file()?)?;
    println!("TTS {}", if enabled { "ON" } else { "OFF" });
    Ok(())
}

async fn cmd_tts_status() -> Result<()> {
    let cfg = load_config()?;
    println!("TTS:        {}", if cfg.tts.enabled { "ON" } else { "OFF" });

    // config 우선, env 보조 — `elevenlabs_key()` 와 같은 결정 로직.
    let key_set = cfg.tts.api_key.is_some()
        || std::env::var("ASURADA_ELEVENLABS_API_KEY")
            .map(|v| !v.is_empty())
            .unwrap_or(false);
    println!("API key:    {}", if key_set { "set" } else { "not set" });

    println!(
        "Voice ID:   {}",
        cfg.tts
            .voice_id
            .or_else(|| std::env::var("ASURADA_ELEVENLABS_VOICE_ID").ok())
            .unwrap_or_else(|| "(not configured)".into())
    );
    Ok(())
}

async fn cmd_tts_voices() -> Result<()> {
    let key = elevenlabs_key()?;
    let client = ai::elevenlabs::ElevenLabsClient::new(key)?;
    let voices = client.list_voices().await?;
    println!("ElevenLabs voices:");
    for v in &voices {
        println!("  {:32}  {}", v.name, v.voice_id);
    }
    println!();
    println!("Set with: ASURADA_ELEVENLABS_VOICE_ID=<voice_id>  또는 config.toml [tts] voice_id");
    Ok(())
}

async fn cmd_tts_test(text: String) -> Result<()> {
    let key = elevenlabs_key()?;
    let cfg = load_config()?;
    let voice_id = cfg
        .tts
        .voice_id
        .or_else(|| std::env::var("ASURADA_ELEVENLABS_VOICE_ID").ok())
        .ok_or_else(|| {
            anyhow::anyhow!("voice_id 가 설정되지 않음. `asurada tts voices` 로 조회 후 설정.")
        })?;
    let client = ai::elevenlabs::ElevenLabsClient::new(key)?;
    println!("[TTS] {}", text);
    client.speak(&text, &voice_id).await?;
    Ok(())
}

async fn cmd_tts_speak(project: Option<String>, limit: usize) -> Result<()> {
    let cfg = load_config()?;
    if !cfg.tts.enabled {
        println!("TTS OFF — `asurada tts on` 으로 활성화하세요.");
        return Ok(());
    }
    let key = elevenlabs_key()?;
    let voice_id = cfg
        .tts
        .voice_id
        .clone()
        .or_else(|| std::env::var("ASURADA_ELEVENLABS_VOICE_ID").ok())
        .ok_or_else(|| anyhow::anyhow!("voice_id 미설정. `asurada tts voices`"))?;

    // brain.db 에서 미확인 advice 조회.
    let user_id = std::env::var("ASURADA_USER_ID").unwrap_or_else(|_| "default".into());
    let brain_path = paths::brain_db()?;
    let conn = db::open(&brain_path)?;
    let pending = db::advice::list_pending(&conn, &user_id, project.as_deref(), limit)?;

    if pending.is_empty() {
        println!("읽을 미확인 어드바이스가 없습니다.");
        return Ok(());
    }

    let client = ai::elevenlabs::ElevenLabsClient::new(key)?;
    for adv in &pending {
        let speech = ai::speech::condense_for_speech(&adv.text, &adv.severity, &adv.project);
        println!("[{}] {}  {}", adv.severity, adv.project, speech);
        if let Err(e) = client.speak(&speech, &voice_id).await {
            tracing::warn!("speak failed: {}", e);
        }
    }
    Ok(())
}

async fn open_sync() -> Result<sync::Sync> {
    use std::sync::{Arc, Mutex};
    // config 우선, env 가 있으면 override (개발자 편의).
    let cfg = config::Config::load(&paths::config_file()?)?;
    let creds = credentials::Credentials {
        database_url: std::env::var("ASURADA_DATABASE_URL")
            .unwrap_or_else(|_| cfg.database.url.clone()),
        user_id: std::env::var("ASURADA_USER_ID").unwrap_or_else(|_| cfg.user.id.clone()),
    };
    let brain_path = paths::brain_db()?;
    let conn = db::open(&brain_path)?;
    let brain = Arc::new(Mutex::new(conn));
    sync::Sync::connect(brain, &creds).await
}

async fn cmd_sync_push() -> Result<()> {
    let s = open_sync().await?;
    let p = s.push_all().await?;
    println!(
        "push  events={} memories={} advice={} projects={} intents={} patterns={} issues={}",
        p.events, p.memories, p.advice, p.projects, p.intents, p.patterns, p.issues
    );
    Ok(())
}

async fn cmd_sync_pull() -> Result<()> {
    let s = open_sync().await?;
    let p = s.pull_all().await?;
    println!(
        "pull  events={} memories={} advice={} projects={} intents={} patterns={} issues={}",
        p.events, p.memories, p.advice, p.projects, p.intents, p.patterns, p.issues
    );
    Ok(())
}

async fn cmd_sync_run() -> Result<()> {
    let s = open_sync().await?;
    let pu = s.push_all().await?;
    let pl = s.pull_all().await?;
    println!(
        "push  events={} memories={} advice={} projects={} intents={} patterns={} issues={}",
        pu.events, pu.memories, pu.advice, pu.projects, pu.intents, pu.patterns, pu.issues
    );
    println!(
        "pull  events={} memories={} advice={} projects={} intents={} patterns={} issues={}",
        pl.events, pl.memories, pl.advice, pl.projects, pl.intents, pl.patterns, pl.issues
    );
    Ok(())
}

async fn cmd_init() -> Result<()> {
    let cfg_path = paths::config_file()?;
    let brain_path = paths::brain_db()?;
    if let Some(parent) = cfg_path.parent() {
        std::fs::create_dir_all(parent)?;
    }

    let existing = config::Config::load(&cfg_path).ok();
    let mut cfg = if let Some(prev) = existing {
        println!("─────────────────────────────────────────────────────");
        println!(" 기존 Asurada 발견");
        println!("─────────────────────────────────────────────────────");
        println!("  user.id  = {}", prev.user.id);
        println!("  config   = {}", cfg_path.display());
        println!();
        println!("기존 설정을 보존합니다. 변경하려면:");
        println!("  asurada config set <key> <value>");
        println!();
        prev
    } else {
        println!("═════════════════════════════════════════════════════");
        println!(" 아스라다 첫 설치");
        println!("═════════════════════════════════════════════════════");
        println!();
        println!("Asurada 는 사용자 본인의 Postgres 에 데이터를 저장합니다 (BYOK).");
        println!("자격증명은 binary 에 박히지 않으며, ~/.asurada/config.toml (chmod 600)");
        println!("에 평문 저장됩니다 — 사용자 본인만 읽기 가능.");
        println!();
        println!("─────────────────────────────────────────────────────");
        println!(" Step 1. Postgres 준비");
        println!("─────────────────────────────────────────────────────");
        println!();
        println!("[옵션 A] Supabase (추천 — 무료 500MB)");
        println!("  1. https://supabase.com 가입 / 로그인");
        println!("  2. New project 생성 (region: 가까운 곳)");
        println!("  3. 좌측 메뉴 → Project Settings → Database");
        println!("  4. Connection String → URI 탭 → 복사");
        println!("     예: postgresql://postgres:[YOUR-PASSWORD]@[host]:5432/postgres");
        println!("     [YOUR-PASSWORD] 부분은 본인이 설정한 DB 비밀번호로 교체");
        println!();
        println!("[옵션 B] 자체 Postgres (Neon / RDS / 로컬 등)");
        println!("  본인 인스턴스의 connection string 준비");
        println!();
        println!("─────────────────────────────────────────────────────");
        println!(" Step 2. URL 입력");
        println!("─────────────────────────────────────────────────────");
        println!();
        let url = prompt_or_env("Postgres URL: ", "ASURADA_DATABASE_URL")?;
        if url.is_empty() {
            anyhow::bail!(
                "database.url 은 필수입니다. https://supabase.com 에서 프로젝트 생성 후 다시 실행하세요."
            );
        }
        if !url.starts_with("postgres://") && !url.starts_with("postgresql://") {
            anyhow::bail!(
                "URL 형식 오류. 'postgresql://' 또는 'postgres://' 로 시작해야 합니다.\n입력값: {}",
                url
            );
        }
        config::Config::fresh(url)
    };

    if let Ok(url) = std::env::var("ASURADA_DATABASE_URL") {
        if !url.is_empty() && url != cfg.database.url {
            cfg.database.url = url;
        }
    }

    // TTS env 자동 채움.
    if cfg.tts.api_key.is_none() {
        if let Ok(k) = std::env::var("ASURADA_ELEVENLABS_API_KEY") {
            if !k.is_empty() {
                cfg.tts.api_key = Some(k);
            }
        }
    }
    if cfg.tts.voice_id.is_none() {
        if let Ok(v) = std::env::var("ASURADA_ELEVENLABS_VOICE_ID") {
            if !v.is_empty() {
                cfg.tts.voice_id = Some(v);
            }
        }
    }

    cfg.save(&cfg_path)?;
    let _conn = db::open(&brain_path)?;

    println!();
    println!("═════════════════════════════════════════════════════");
    println!(" ✓ 아스라다가 깨어났습니다 🌟");
    println!("═════════════════════════════════════════════════════");
    println!();
    println!("  user.id:  {}", cfg.user.id);
    println!("  config:   {}", cfg_path.display());
    println!("  brain.db: {}", brain_path.display());
    println!(
        "  tts:      {}",
        if cfg.tts.api_key.is_some() {
            "✓ configured"
        } else {
            "(not set — 아래 가이드 참고)"
        }
    );
    println!();
    println!("─────────────────────────────────────────────────────");
    println!(" 다음 단계");
    println!("─────────────────────────────────────────────────────");
    println!();
    println!("1. Postgres 측 스키마 마이그레이션 (1회):");
    println!("   psql \"$(asurada config show | awk '/url =/{{print $3}}')\" \\");
    println!("     -f /usr/local/share/asurada/migrations/0001_init.sql");
    println!("   또는 Supabase Studio SQL 에디터에서 실행");
    println!();
    println!("2. 데몬 등록 (launchd, 자동 시작):");
    println!("   asurada-install-launchd       # Homebrew 로 설치 시");
    println!("   또는 직접:");
    println!("   ./scripts/install-launchd.sh");
    println!();
    println!("3. (선택) TTS 활성화:");
    println!("   https://elevenlabs.io 에서 API 키 발급 후");
    println!("   asurada config set tts.api_key 'sk_...'");
    println!("   asurada tts voices                  # voice 선택");
    println!("   asurada config set tts.voice_id '...'");
    println!("   asurada tts on");
    println!();
    println!("4. 상태 확인:");
    println!("   asurada config show           # 전체 설정");
    println!("   asurada tts status            # TTS 상태");
    println!();
    Ok(())
}

// ── Brief 명령 ──────────────────────────────────────

async fn cmd_brief(project: Option<String>, days: i64) -> Result<()> {
    use std::sync::{Arc, Mutex};
    let cfg = load_config()?;
    let conn = db::open(&paths::brain_db()?)?;
    let brain = Arc::new(Mutex::new(conn));

    let projects: Vec<String> = match project {
        Some(p) => vec![p],
        None => {
            let conn = brain.lock().unwrap();
            db::project::list(&conn, &cfg.user.id)?
                .into_iter()
                .map(|p| p.name)
                .collect()
        }
    };

    if projects.is_empty() {
        println!("(등록된 프로젝트 없음)");
        return Ok(());
    }

    for p in projects {
        // 활동 없으면 skip — 사일런스 원칙
        let has_activity = {
            let conn = brain.lock().unwrap();
            synthesis::should_brief(&conn, &cfg.user.id, &p).unwrap_or(false)
        };
        if !has_activity {
            println!("[{}] 최근 활동 없음 또는 12h 내 brief 있음 → skip", p);
            continue;
        }

        println!("[{}] brief 생성 중... (claude -p, 최대 2분)", p);
        let result =
            synthesis::brief_project(brain.clone(), cfg.user.id.clone(), p.clone(), days).await;
        match result {
            Ok(Some(m)) => {
                println!("✓ memory 저장: {}", m.id);
                println!();
                for line in m.text.lines() {
                    println!("  {}", line);
                }
                println!();
            }
            Ok(None) => println!("[{}] 응답 없음 (skip)", p),
            Err(e) => println!("[{}] 실패: {}", p, e),
        }
    }
    Ok(())
}

// ── Issue 명령 ──────────────────────────────────────

async fn cmd_issue_capture(hours: i64) -> Result<()> {
    use std::sync::{Arc, Mutex};
    let cfg = load_config()?;
    let conn = db::open(&paths::brain_db()?)?;
    let brain = Arc::new(Mutex::new(conn));

    println!("issue capture 중... (claude -p, 최대 2분)");
    match synthesis::capture_issue(brain.clone(), cfg.user.id.clone(), hours).await {
        Ok(Some(issue)) => {
            println!("✓ issue 저장: {}", issue.id);
            println!();
            println!("  제목:        {}", issue.title);
            println!("  프로젝트들:  {}", issue.projects.join(", "));
            println!("  events:      {}", issue.event_count);
            println!("  시작:        {}", issue.started_at);
            println!(
                "  끝:          {}",
                issue.ended_at.as_deref().unwrap_or("-")
            );
            println!();
            println!("─ 요약 ────────────────────────");
            for line in issue.summary.lines() {
                println!("{}", line);
            }
        }
        Ok(None) => println!("(최근 활동 없음 — 캡처할 거리 없음)"),
        Err(e) => println!("실패: {}", e),
    }
    Ok(())
}

fn cmd_issue_list(limit: usize) -> Result<()> {
    let cfg = load_config()?;
    let conn = db::open(&paths::brain_db()?)?;
    let issues = db::issue::list(&conn, &cfg.user.id, limit)?;
    if issues.is_empty() {
        println!("(issue 없음 — `asurada issue capture` 로 첫 issue 만들기)");
        return Ok(());
    }
    println!("{:8}  {:16}  {:20}  title", "id", "started", "projects");
    for it in issues {
        let id_short = &it.id[..8.min(it.id.len())];
        let started: String = it.started_at.chars().take(16).collect();
        let projects: String = it.projects.join(", ").chars().take(20).collect();
        let title: String = it.title.chars().take(50).collect();
        println!("{:8}  {:16}  {:20}  {}", id_short, started, projects, title);
    }
    Ok(())
}

fn cmd_issue_get(id: String) -> Result<()> {
    let cfg = load_config()?;
    let conn = db::open(&paths::brain_db()?)?;
    let all = db::issue::list(&conn, &cfg.user.id, 1000)?;
    let it = all
        .into_iter()
        .find(|i| i.id.starts_with(&id))
        .ok_or_else(|| anyhow::anyhow!("issue 없음: {}", id))?;
    println!("id:           {}", it.id);
    println!("title:        {}", it.title);
    println!("projects:     {}", it.projects.join(", "));
    println!("status:       {}", it.status);
    println!("event_count:  {}", it.event_count);
    println!("started:      {}", it.started_at);
    println!("ended:        {}", it.ended_at.as_deref().unwrap_or("-"));
    println!();
    println!("─ summary ────────────────────");
    for line in it.summary.lines() {
        println!("{}", line);
    }
    Ok(())
}

// ── Memory 명령 (전문 조회 — Dashboard 비노출) ──────────────────

fn cmd_memory_list(scope: Option<String>, limit: usize) -> Result<()> {
    let cfg = load_config()?;
    let conn = db::open(&paths::brain_db()?)?;
    let memories = db::memory::list(&conn, &cfg.user.id, scope.as_deref(), limit)?;
    if memories.is_empty() {
        println!("(메모리 없음)");
        return Ok(());
    }
    println!(
        "{:8}  {:8}  {:11}  {:14}  text",
        "id", "scope", "priority", "project"
    );
    for m in memories {
        let id_short = &m.id[..8.min(m.id.len())];
        let project: String = m.project.unwrap_or_default().chars().take(14).collect();
        let text: String = m.text.replace('\n', " ").chars().take(60).collect();
        println!(
            "{:8}  {:8}  {:11}  {:14}  {}",
            id_short, m.scope, m.priority, project, text
        );
    }
    Ok(())
}

fn cmd_memory_get(id: String) -> Result<()> {
    let cfg = load_config()?;
    let conn = db::open(&paths::brain_db()?)?;
    let all = db::memory::list(&conn, &cfg.user.id, None, 5000)?;
    let m = all
        .into_iter()
        .find(|x| x.id.starts_with(&id))
        .ok_or_else(|| anyhow::anyhow!("메모리 없음: {}", id))?;
    println!("id:        {}", m.id);
    println!("scope:     {}", m.scope);
    println!("priority:  {}", m.priority);
    println!("source:    {}", m.source);
    println!("project:   {}", m.project.as_deref().unwrap_or("-"));
    println!("tech:      {}", m.tech.as_deref().unwrap_or("-"));
    println!("created:   {}", m.created_at);
    println!("updated:   {}", m.updated_at);
    println!();
    println!("─ text ────────────────────");
    for line in m.text.lines() {
        println!("{}", line);
    }
    Ok(())
}

fn cmd_memory_search(query: String, limit: usize) -> Result<()> {
    let cfg = load_config()?;
    let conn = db::open(&paths::brain_db()?)?;
    let memories = db::memory::search(&conn, &cfg.user.id, &query, limit)?;
    if memories.is_empty() {
        println!("(검색 결과 없음)");
        return Ok(());
    }
    println!(
        "{:8}  {:8}  {:11}  {:14}  text",
        "id", "scope", "priority", "project"
    );
    for m in memories {
        let id_short = &m.id[..8.min(m.id.len())];
        let project: String = m.project.unwrap_or_default().chars().take(14).collect();
        let text: String = m.text.replace('\n', " ").chars().take(60).collect();
        println!(
            "{:8}  {:8}  {:11}  {:14}  {}",
            id_short, m.scope, m.priority, project, text
        );
    }
    Ok(())
}

// ── Reflect 명령 (Layer B) ─────────────────────────

async fn cmd_reflect(days: i64) -> Result<()> {
    use std::sync::{Arc, Mutex};
    let cfg = load_config()?;
    let conn = db::open(&paths::brain_db()?)?;
    let brain = Arc::new(Mutex::new(conn));

    let label = if days <= 1 {
        "오늘 흐름"
    } else {
        "이번 주 패턴"
    };
    println!("[{}] 통합 회고 생성 중... (claude -p, 최대 2분)", label);

    match synthesis::reflect_recent(brain.clone(), cfg.user.id.clone(), days).await {
        Ok(Some(m)) => {
            println!("✓ memory 저장: {}", m.id);
            println!();
            for line in m.text.lines() {
                println!("  {}", line);
            }
        }
        Ok(None) => println!("(활동 없음 — 회고할 거리 없음)"),
        Err(e) => println!("실패: {}", e),
    }
    Ok(())
}

// ── Voice 명령 ──────────────────────────────────────

async fn cmd_voice_greet(dry_run: bool) -> Result<()> {
    let cfg = load_config()?;
    let conn = db::open(&paths::brain_db()?)?;

    let preview = voice::preview_greeting(&conn, &cfg.user.id)?;
    match &preview {
        None => {
            println!("(할 말 없음 — 모든 프로젝트 활동 중 + 보류 advice 0)");
            if !dry_run {
                // 침묵도 dedup 기록
                let _ = db::event::insert(
                    &conn,
                    db::event::EventInput {
                        user_id: cfg.user.id.clone(),
                        project: "_".into(),
                        event_type: "voice.greeting".into(),
                        path: None,
                        payload: serde_json::json!({"text": null, "skipped": "all_clear"}),
                    },
                );
            }
        }
        Some(text) => {
            println!("─ 인사 텍스트 ───────────────");
            println!("{}", text);
            println!();
            if dry_run {
                println!("(dry-run — 발화 안 함)");
                return Ok(());
            }
            if !cfg.tts.enabled {
                println!("(TTS off — 발화 안 함. `asurada tts on` 으로 활성화)");
                return Ok(());
            }
            // 직접 발화 (queue 우회 — CLI 일회성)
            let key = elevenlabs_key()?;
            let voice_id = cfg
                .tts
                .voice_id
                .clone()
                .ok_or_else(|| anyhow::anyhow!("voice_id 미설정"))?;
            let client = ai::elevenlabs::ElevenLabsClient::new(key)?;
            client.speak(text, &voice_id).await?;
            voice::mark_greeted(&conn, &cfg.user.id, text)?;
            println!("✓ 발화됨");
        }
    }
    Ok(())
}

fn cmd_voice_survey() -> Result<()> {
    let cfg = load_config()?;
    let conn = db::open(&paths::brain_db()?)?;
    let insights = voice::survey_projects(&conn, &cfg.user.id)?;
    if insights.is_empty() {
        println!("(등록된 프로젝트 없음)");
        return Ok(());
    }
    println!(
        "{:20}  {:>8}  {:>8}  last prompt",
        "project", "idle d", "advice"
    );
    for i in insights {
        let preview = i.last_prompt_preview.as_deref().unwrap_or("(활동 없음)");
        let idle_label = if i.idle_days < 0 {
            "".to_string()
        } else {
            format!("{}d", i.idle_days)
        };
        println!(
            "{:20}  {:>8}  {:>8}  {}",
            i.project, idle_label, i.pending_advice, preview
        );
    }
    Ok(())
}

fn cmd_voice_status() -> Result<()> {
    let cfg = load_config()?;
    let conn = db::open(&paths::brain_db()?)?;
    let last = voice::last_greeting_time(&conn, &cfg.user.id)?;
    let already = voice::already_greeted_today(&conn, &cfg.user.id)?;
    println!(
        "TTS:                  {}",
        if cfg.tts.enabled { "ON" } else { "OFF" }
    );
    println!("daily_greeting:       {}", cfg.tts.daily_greeting);
    println!("auto_speak_advice:    {}", cfg.tts.auto_speak_advice);
    println!(
        "quiet_hours:          {}",
        cfg.tts.quiet_hours.as_deref().unwrap_or("(없음)")
    );
    println!(
        "in_quiet_hours_now:   {}",
        voice::in_quiet_hours(cfg.tts.quiet_hours.as_deref())
    );
    println!(
        "last_greeting:        {}",
        last.as_deref().unwrap_or("(없음)")
    );
    println!("greeted_today:        {}", already);
    Ok(())
}

// ── Admin 명령 ───────────────────────────────────────

fn cmd_admin_normalize_events(apply: bool) -> Result<()> {
    use rusqlite::params;
    let cfg = load_config()?;
    let conn = db::open(&paths::brain_db()?)?;

    // canonical name 들 (projects 테이블).
    let mut stmt = conn.prepare("SELECT name FROM projects WHERE user_id = ?1")?;
    let canonicals: Vec<String> = stmt
        .query_map(params![&cfg.user.id], |r| r.get(0))?
        .filter_map(|r| r.ok())
        .collect();

    if canonicals.is_empty() {
        println!("(projects 테이블 비어있음 — 정규화 불가)");
        return Ok(());
    }

    let mut total_affected = 0i64;
    let mut summary: Vec<(String, String, i64)> = Vec::new();

    for canonical in &canonicals {
        // 같은 LOWER 매칭이지만 정확히는 다른 project 값 찾기.
        let mut stmt = conn.prepare(
            r#"SELECT DISTINCT project FROM events
               WHERE user_id = ?1
                 AND LOWER(project) = LOWER(?2)
                 AND project != ?2"#,
        )?;
        let variants: Vec<String> = stmt
            .query_map(params![&cfg.user.id, canonical], |r| r.get(0))?
            .filter_map(|r| r.ok())
            .collect();

        for v in variants {
            let mut count_stmt =
                conn.prepare("SELECT COUNT(*) FROM events WHERE user_id = ?1 AND project = ?2")?;
            let n: i64 = count_stmt
                .query_row(params![&cfg.user.id, &v], |r| r.get(0))
                .unwrap_or(0);
            if n == 0 {
                continue;
            }
            summary.push((v.clone(), canonical.clone(), n));
            total_affected += n;
            if apply {
                // updated_at 도 bump — 그래야 다음 sync 가 cloud 의 row 도 갱신
                // (last-writer-wins 비교 통과).
                let now = chrono::Utc::now().to_rfc3339();
                conn.execute(
                    r#"UPDATE events
                       SET project = ?1, updated_at = ?2, synced_at = NULL
                       WHERE user_id = ?3 AND project = ?4"#,
                    params![canonical, now, &cfg.user.id, &v],
                )?;
            }
        }
    }

    if summary.is_empty() {
        println!("(정규화 대상 없음 — 모든 events 가 canonical 사용 중)");
        return Ok(());
    }

    println!("─ 정규화 대상 ─────────────────────────");
    for (from, to, n) in &summary {
        println!("  {:20} → {:20}  ({}건)", from, to, n);
    }
    println!();
    if apply {
        println!(
            "✓ 적용 완료. 총 {}건 갱신, sync 다음 cycle 에 push.",
            total_affected
        );
    } else {
        println!(
            "(dry-run — 총 {}건 영향. 실제 적용은 --apply)",
            total_affected
        );
    }
    Ok(())
}

// ── Onboard 명령 ───────────────────────────────────────

fn cmd_onboard() -> Result<()> {
    use std::io::{self, Write};

    let cfg = config::Config::load(&paths::config_file()?).map_err(|_| {
        anyhow::anyhow!("config 없음 — 먼저 `asurada init` 으로 user.id + database.url 설정 필요")
    })?;
    let conn = db::open(&paths::brain_db()?)?;

    let existing = db::intent::list_all(&conn, &cfg.user.id)?;
    if !existing.is_empty() {
        println!("이미 intent 가 있습니다. onboard 는 빈 상태에서만 권장됩니다.");
        println!("기존 intent: {}", existing.len());
        print!("그래도 진행할까요? [y/N]: ");
        io::stdout().flush().ok();
        let mut line = String::new();
        io::stdin().read_line(&mut line).ok();
        if !line.trim().eq_ignore_ascii_case("y") {
            println!("취소.");
            return Ok(());
        }
    }

    println!();
    println!("═════════════════════════════════════════════════════");
    println!(" Asurada 와 함께 시작 — 5문항");
    println!("═════════════════════════════════════════════════════");
    println!();
    println!("이 답변들은 초기 intent 로 저장됩니다.");
    println!("나중에 `asurada intent add/archive` 로 추가/변경 가능.");
    println!();

    let mut created: Vec<(String, String)> = Vec::new();

    // Q1 — 응답 언어
    println!("[1/5] 응답 언어 (Asurada/Claude 가 사용자에게 답할 때 기본 언어)");
    println!("    1) 한국어  2) English  3) 둘 다 (혼용)");
    let lang = prompt_choice("> ", &["1", "2", "3"], "1")?;
    let lang_text = match lang.as_str() {
        "1" => "응답은 한국어로 작성하라. 코드 식별자/명령어는 원형 유지.",
        "2" => "Reply in English by default. Keep code identifiers in their original form.",
        _ => "응답 언어는 사용자가 마지막으로 사용한 언어를 따른다. 일관성 우선.",
    };
    add_intent(
        &conn,
        &cfg.user.id,
        db::intent::Strength::Preference,
        lang_text,
        None,
    )?;
    created.push(("preference".into(), lang_text.into()));

    // Q2 — 강한 코드 작성 선호 (free-form)
    println!();
    println!("[2/5] 코드 작성 시 *강한* 선호 (한 줄, 비워두면 skip)");
    println!("    예: \"새 기능 추가 시 테스트도 같이\", \"커밋 메시지는 conventional\"");
    let pref = prompt_line("> ")?;
    if !pref.is_empty() {
        add_intent(
            &conn,
            &cfg.user.id,
            db::intent::Strength::Preference,
            &pref,
            None,
        )?;
        created.push(("preference".into(), pref));
    }

    // Q3 — destructive git 보호 (principle)
    println!();
    println!("[3/5] destructive git 작업 (push --force, reset --hard) 전 자동 확인?");
    println!("    Y) 예 (Asurada 가 hook 으로 차단/확인)");
    println!("    n) 아니오");
    let git_protect = prompt_choice("> ", &["y", "Y", "n", "N", ""], "y")?;
    if !git_protect.eq_ignore_ascii_case("n") {
        for (label, contains) in &[
            ("git push --force", "git push --force"),
            ("git reset --hard", "git reset --hard"),
        ] {
            let mut metadata = serde_json::Map::new();
            let mut trigger = serde_json::Map::new();
            trigger.insert("tool".into(), serde_json::Value::String("Bash".into()));
            trigger.insert(
                "contains".into(),
                serde_json::Value::String((*contains).into()),
            );
            metadata.insert("trigger".into(), serde_json::Value::Object(trigger));
            metadata.insert("decision".into(), serde_json::Value::String("ask".into()));

            let text = format!("{} 전 사용자 확인 필수", label);
            db::intent::insert(
                &conn,
                db::intent::IntentInput {
                    user_id: cfg.user.id.clone(),
                    project: None,
                    strength: db::intent::Strength::Principle,
                    intent_text: text.clone(),
                    source: db::intent::Source::User,
                    source_signal_ids: vec![],
                    metadata: serde_json::Value::Object(metadata),
                },
            )?;
            created.push(("principle".into(), text));
        }
    }

    // Q4 — 상시 알아둘 맥락 (free-form)
    println!();
    println!("[4/5] 상시 기억해야 할 맥락 (한 줄, 비워두면 skip)");
    println!("    예: \"주력 스택은 Rust + React\", \"팀 합의: PR 라벨 필수\"");
    let ctx = prompt_line("> ")?;
    if !ctx.is_empty() {
        add_intent(
            &conn,
            &cfg.user.id,
            db::intent::Strength::Context,
            &ctx,
            None,
        )?;
        created.push(("context".into(), ctx));
    }

    // Q5 — 협업 모드
    println!();
    println!("[5/5] AI 와의 협업 모드");
    println!("    1) 함께 결정 — 큰 결정은 물어보고 진행");
    println!("    2) 자율 진행 — 작은 결정은 알아서, 큰 것만 보고");
    println!("    3) 일일이 확인 — 모든 단계 사용자 승인");
    let mode = prompt_choice("> ", &["1", "2", "3"], "1")?;
    let mode_text = match mode.as_str() {
        "1" => "AI 는 큰 결정 (아키텍처/배포/destructive 작업) 전 사용자에게 묻고, 작은 실행은 보고만 한다.",
        "2" => "AI 는 결정 권한을 갖되, 사용자 명시 의도와 어긋나면 즉시 중단해 묻는다. 보고는 결과 위주로 간결.",
        _ => "AI 는 모든 단계 (도구 호출/파일 변경/커밋) 전 사용자 승인을 받는다. 자율 실행 금지.",
    };
    add_intent(
        &conn,
        &cfg.user.id,
        db::intent::Strength::Preference,
        mode_text,
        None,
    )?;
    created.push(("preference".into(), mode_text.into()));

    println!();
    println!("─────────────────────────────────────────────");
    println!(" ✓ 저장됨");
    println!("─────────────────────────────────────────────");
    println!();
    for (kind, text) in &created {
        let trimmed: String = text.chars().take(70).collect();
        let suffix = if text.chars().count() > 70 { "" } else { "" };
        println!("  [{}] {}{}", kind, trimmed, suffix);
    }
    println!();
    println!("다음 단계:");
    println!("  asurada intent compile    Claude Code 에 적용");
    println!("  asurada hook install      사용자 프롬프트 관찰 시작");
    println!("  asurada serve             패턴 자동 생성을 위한 데몬 가동");
    Ok(())
}

fn add_intent(
    conn: &rusqlite::Connection,
    user_id: &str,
    strength: db::intent::Strength,
    text: &str,
    project: Option<String>,
) -> Result<()> {
    db::intent::insert(
        conn,
        db::intent::IntentInput {
            user_id: user_id.into(),
            project,
            strength,
            intent_text: text.into(),
            source: db::intent::Source::User,
            source_signal_ids: vec![],
            metadata: serde_json::json!({}),
        },
    )?;
    Ok(())
}

fn prompt_line(prompt: &str) -> Result<String> {
    use std::io::{self, Write};
    print!("{}", prompt);
    io::stdout().flush().ok();
    let mut line = String::new();
    io::stdin().read_line(&mut line)?;
    Ok(line.trim().to_string())
}

fn prompt_choice(prompt: &str, allowed: &[&str], default: &str) -> Result<String> {
    use std::io::{self, Write};
    print!("{}", prompt);
    io::stdout().flush().ok();
    let mut line = String::new();
    io::stdin().read_line(&mut line)?;
    let trimmed = line.trim();
    if trimmed.is_empty() {
        return Ok(default.into());
    }
    if allowed.iter().any(|a| a == &trimmed) {
        return Ok(trimmed.to_string());
    }
    // 잘못된 입력은 default 로.
    Ok(default.into())
}

/// env 우선, 없으면 stdin prompt.
fn prompt_or_env(prompt: &str, env_var: &str) -> Result<String> {
    if let Ok(v) = std::env::var(env_var) {
        if !v.is_empty() {
            return Ok(v);
        }
    }
    use std::io::{self, Write};
    print!("{}", prompt);
    io::stdout().flush().ok();
    let mut line = String::new();
    io::stdin().read_line(&mut line)?;
    Ok(line.trim().to_string())
}

async fn cmd_serve(
    port: u16,
    auto_pattern_interval: u64,
    auto_evolution_threshold: usize,
    auto_redo_threshold: usize,
) -> Result<()> {
    use std::sync::{Arc, Mutex};
    use std::time::Duration;

    let cfg = config::Config::load(&paths::config_file()?)?;
    let brain_path = paths::brain_db()?;
    let conn = db::open(&brain_path)?;
    let brain = Arc::new(Mutex::new(conn));

    // 백그라운드 sync 루프 — config 가 이미 user.id + db.url 강제하므로 항상 시작.
    let creds = credentials::Credentials {
        database_url: cfg.database.url.clone(),
        user_id: cfg.user.id.clone(),
    };
    match sync::Sync::connect(brain.clone(), &creds).await {
        Ok(s) => {
            tokio::spawn(s.run_loop(Duration::from_secs(30)));
        }
        Err(e) => {
            tracing::warn!("[sync] connect failed: {}", e);
        }
    }

    // 음성 큐 — TTS on 일 때만 spawn. None 이면 voice task 들이 no-op.
    let voice_queue = voice::VoiceQueue::spawn(&cfg);
    if voice_queue.is_some() {
        tracing::info!("[voice] queue active");
    }

    // 일일 인사 — 60s 짧은 간격 + Mac sleep/wake 즉시 감지 (wall-clock gap > 5분).
    // wake 직후 sleep 중이던 cycle 이 깨어나면, 다음 sleep 을 건너뛰고 바로 인사 검사.
    // 조용 시간대(21:00-09:00) 안에서는 mark 안 하고 대기.
    if let Some(vq) = voice_queue.clone() {
        if cfg.tts.daily_greeting {
            let brain_for_voice = brain.clone();
            let user_id = cfg.user.id.clone();
            let quiet_hours = cfg.tts.quiet_hours.clone();
            tokio::spawn(async move {
                tokio::time::sleep(Duration::from_secs(5)).await;
                let normal_interval = Duration::from_secs(60); // 1min — 일반 polling
                let immediate_after_wake = Duration::from_secs(2); // wake 후 빠른 후속
                let mut last_wall = chrono::Local::now();
                let mut just_woke = false;
                loop {
                    let now = chrono::Local::now();
                    let gap = now.signed_duration_since(last_wall);
                    let woke_now = gap.num_minutes() >= 5;
                    if woke_now {
                        tracing::info!(
                            "[voice] wall-clock jump {}분 — Mac wake 감지, 즉시 인사 검사",
                            gap.num_minutes()
                        );
                        just_woke = true;
                    }
                    last_wall = now;

                    let brain = brain_for_voice.clone();
                    let uid = user_id.clone();
                    let q = vq.clone();
                    let qh = quiet_hours.clone();
                    let _ = tokio::task::spawn_blocking(move || {
                        let conn = brain.lock().expect("brain mutex poisoned");
                        if let Err(e) = voice::try_daily_greeting(&conn, &uid, &q, qh.as_deref()) {
                            tracing::warn!("[voice] greeting failed: {}", e);
                        }
                    })
                    .await;
                    // wake 직후엔 한 번 즉시 후속 (조용 시간대에서 mark 못 한 직전 cycle 보완 등),
                    // 평상시는 1분 polling.
                    let next = if just_woke {
                        just_woke = false;
                        immediate_after_wake
                    } else {
                        normal_interval
                    };
                    tokio::time::sleep(next).await;
                }
            });
        }
    }

    // 새 advice 자동 발화 — 30초 간격으로 큐 점검.
    if let Some(vq) = voice_queue.clone() {
        if cfg.tts.auto_speak_advice {
            let brain_for_voice = brain.clone();
            let user_id = cfg.user.id.clone();
            tokio::spawn(async move {
                tokio::time::sleep(Duration::from_secs(10)).await;
                let interval = Duration::from_secs(30);
                loop {
                    let brain = brain_for_voice.clone();
                    let uid = user_id.clone();
                    let q = vq.clone();
                    let _ = tokio::task::spawn_blocking(move || {
                        let conn = brain.lock().expect("brain mutex poisoned");
                        if let Err(e) = voice::try_speak_new_advice(&conn, &uid, &q, 5) {
                            tracing::warn!("[voice] advice speak failed: {}", e);
                        }
                    })
                    .await;
                    tokio::time::sleep(interval).await;
                }
            });
        }
    }

    // 백그라운드 자동 reflect — 24시간마다 daily, 7일마다 weekly 통합 회고.
    {
        let brain_for_reflect = brain.clone();
        let user_id = cfg.user.id.clone();
        tokio::spawn(async move {
            tokio::time::sleep(Duration::from_secs(120)).await; // 부팅 후 2분
            let interval = Duration::from_secs(60 * 60); // 1시간마다 점검
            loop {
                let (do_daily, do_weekly) = {
                    let conn = brain_for_reflect.lock().expect("brain mutex poisoned");
                    (
                        synthesis::should_reflect_daily(&conn, &user_id).unwrap_or(false),
                        synthesis::should_reflect_weekly(&conn, &user_id).unwrap_or(false),
                    )
                };
                if do_daily {
                    let r =
                        synthesis::reflect_recent(brain_for_reflect.clone(), user_id.clone(), 1)
                            .await;
                    match r {
                        Ok(Some(m)) => {
                            tracing::info!("[reflect daily] memory {}", &m.id[..8.min(m.id.len())])
                        }
                        Ok(None) => tracing::debug!("[reflect daily] no activity"),
                        Err(e) => tracing::warn!("[reflect daily] failed: {}", e),
                    }
                }
                if do_weekly {
                    let r =
                        synthesis::reflect_recent(brain_for_reflect.clone(), user_id.clone(), 7)
                            .await;
                    match r {
                        Ok(Some(m)) => {
                            tracing::info!("[reflect weekly] memory {}", &m.id[..8.min(m.id.len())])
                        }
                        Ok(None) => tracing::debug!("[reflect weekly] no activity"),
                        Err(e) => tracing::warn!("[reflect weekly] failed: {}", e),
                    }
                }
                tokio::time::sleep(interval).await;
            }
        });
        tracing::info!("[reflect auto] enabled (daily 24h / weekly 7d)");
    }

    // 백그라운드 자동 brief — 12시간마다 활동 있는 프로젝트 회고 생성.
    // raw 이벤트가 *해석된 메모리* 로 승격되는 layer (사고의 연료 누적).
    {
        let brain_for_brief = brain.clone();
        let user_id_for_brief = cfg.user.id.clone();
        tokio::spawn(async move {
            // 첫 실행 — 부팅 후 60초 대기 (다른 init 안정화).
            tokio::time::sleep(Duration::from_secs(60)).await;
            let interval = Duration::from_secs(12 * 60 * 60); // 12h
            loop {
                let projects: Vec<String> = {
                    let conn = brain_for_brief.lock().expect("brain mutex poisoned");
                    db::project::list(&conn, &user_id_for_brief)
                        .unwrap_or_default()
                        .into_iter()
                        .filter(|p| {
                            synthesis::should_brief(&conn, &user_id_for_brief, &p.name)
                                .unwrap_or(false)
                        })
                        .map(|p| p.name)
                        .collect()
                };

                for project in projects {
                    let brain = brain_for_brief.clone();
                    let uid = user_id_for_brief.clone();
                    let proj = project.clone();
                    let result = synthesis::brief_project(brain, uid, proj, 1).await;
                    match result {
                        Ok(Some(m)) => tracing::info!(
                            "[brief auto] {} → memory {}",
                            project,
                            &m.id[..8.min(m.id.len())]
                        ),
                        Ok(None) => tracing::debug!("[brief auto] {} no activity", project),
                        Err(e) => tracing::warn!("[brief auto] {} failed: {}", project, e),
                    }
                }

                tokio::time::sleep(interval).await;
            }
        });
        tracing::info!("[brief auto] enabled (interval=12h)");
    }

    // 백그라운드 자동 패턴/진화 스캔 — Asurada 의 자율 인지 부분.
    if auto_pattern_interval > 0 {
        let brain_for_pattern = brain.clone();
        let user_id = cfg.user.id.clone();
        tokio::spawn(async move {
            let interval = Duration::from_secs(auto_pattern_interval);
            // 첫 실행 전에 한 차례 대기 — 데몬 부팅 직후 폭주 방지.
            tokio::time::sleep(interval).await;
            loop {
                let brain = brain_for_pattern.clone();
                let uid = user_id.clone();
                let result =
                    tokio::task::spawn_blocking(move || -> anyhow::Result<(usize, usize)> {
                        let conn = brain.lock().expect("brain mutex poisoned");

                        // redo cluster → advice 제안
                        let clusters =
                            detect::scan_redo_clusters(&conn, &uid, None, 30, auto_redo_threshold)?;
                        let added_redo = detect::propose_from_clusters(&conn, &uid, &clusters)?;

                        // pattern 진화 후보 → advice 제안
                        let candidates = detect::scan_pattern_evolution_candidates(
                            &conn,
                            &uid,
                            auto_evolution_threshold,
                            30,
                        )?;
                        let mut added_evol = 0usize;
                        for c in &candidates {
                            if detect::already_proposed_evolution(&conn, &uid, &c.pattern_id)? {
                                continue;
                            }
                            detect::propose_pattern_evolution(&conn, &uid, c)?;
                            added_evol += 1;
                        }
                        Ok((added_redo, added_evol))
                    })
                    .await;
                match result {
                    Ok(Ok((r, e))) if r > 0 || e > 0 => {
                        tracing::info!("[pattern auto] redo+={} evolution+={}", r, e);
                    }
                    Ok(Ok(_)) => {
                        tracing::debug!("[pattern auto] no new proposals");
                    }
                    Ok(Err(e)) => {
                        tracing::warn!("[pattern auto] scan failed: {}", e);
                    }
                    Err(e) => {
                        tracing::warn!("[pattern auto] task panicked: {}", e);
                    }
                }
                tokio::time::sleep(interval).await;
            }
        });
        tracing::info!(
            "[pattern auto] enabled (interval={}s, redo>={}, evolution>={})",
            auto_pattern_interval,
            auto_redo_threshold,
            auto_evolution_threshold
        );
    }

    let state = api::AppState { conn: brain };
    let app = api::router(state);

    let addr = format!("127.0.0.1:{}", port);
    tracing::info!("listening on http://{} (user.id={})", addr, cfg.user.id);
    let listener = tokio::net::TcpListener::bind(&addr).await?;
    axum::serve(listener, app).await?;
    Ok(())
}

fn cmd_path() -> Result<()> {
    println!("config_dir: {}", paths::config_dir()?.display());
    println!("brain_db:   {}", paths::brain_db()?.display());
    Ok(())
}