aidaemon-work 0.27.3

Goals, mandates, tasks and work coordination with a SQLite store; internal to aidaemon, no stability promise
Documentation
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
//! The goals, mandates, tasks, work and notification tables.
//!
//! The statements run in the order they always have. A database gives no way
//! to tell which of them it has seen, so they stay idempotent and keep
//! running on every start. Called in two steps because the host's own tables
//! sit between them. `goals.source_episode_id` refers to long-term memory's
//! `episodes` table, so a host without that memory creates a table of that
//! name first; `aidaemon_events::schema::migrate_events` runs first as well.

use chrono::{Datelike, TimeZone, Timelike};
use sqlx::Row;
use sqlx::SqlitePool;

/// The version record that says `_goals_legacy_deprecated` has been imported.
pub const LEGACY_GOALS_IMPORTED_VERSION: i64 = 2;

pub async fn table_exists_in_pool(pool: &SqlitePool, name: &str) -> anyhow::Result<bool> {
    Ok(sqlx::query_scalar::<_, i64>(
        "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?",
    )
    .bind(name)
    .fetch_optional(pool)
    .await?
    .is_some())
}

/// The version record that says the one-time backfills below have run with
/// this release's code: mandate session links, task dependency rows and the
/// legacy goal runs. Recorded by the host after the steps ran; before it they
/// run on every start, as they always did.
pub const WORK_BACKFILLS_DONE_VERSION: i64 = 3;

async fn state_version_recorded(pool: &SqlitePool, version: i64) -> anyhow::Result<bool> {
    if !table_exists_in_pool(pool, "state_schema_versions").await? {
        return Ok(false);
    }
    Ok(
        sqlx::query_scalar::<_, i64>("SELECT 1 FROM state_schema_versions WHERE version = ?")
            .bind(version)
            .fetch_optional(pool)
            .await?
            .is_some(),
    )
}

async fn legacy_goals_already_imported(pool: &SqlitePool) -> anyhow::Result<bool> {
    state_version_recorded(pool, LEGACY_GOALS_IMPORTED_VERSION).await
}

async fn work_backfills_done(pool: &SqlitePool) -> anyhow::Result<bool> {
    state_version_recorded(pool, WORK_BACKFILLS_DONE_VERSION).await
}

/// The goal, mandate, task and notification tables, up to the host's own.
pub async fn migrate_work_tables(
    pool: &SqlitePool,
    is_one_shot_schedule: fn(&str) -> bool,
) -> anyhow::Result<()> {
    // --- Goals/Tasks/Schedules (cleanup/unification) ---
    //
    // Historical schemas:
    // - `goals` (INTEGER PRIMARY KEY): personal memory goals (legacy)
    // - `scheduled_tasks`: legacy scheduler rows
    // - prior orchestration schema: `goals_v3`, `tasks_v3`, `task_activity_v3`
    //
    // Target schema:
    // - `goals` (TEXT PRIMARY KEY) with `domain` gating ("orchestration" vs "personal")
    // - `tasks`, `task_activity`
    // - `goal_schedules` (multiple schedules per goal with per-schedule state)
    //
    // Safety goals:
    // - Transactional table renames (all succeed or none)
    // - Legacy tables preserved as *_deprecated for recovery (not dropped)
    // - Idempotent (safe to run multiple times)

    let has_goals_v3 = sqlx::query_scalar::<_, i64>(
        "SELECT 1 FROM sqlite_master WHERE type='table' AND name='goals_v3' LIMIT 1",
    )
    .fetch_optional(pool)
    .await?
    .is_some();
    let has_tasks_v3 = sqlx::query_scalar::<_, i64>(
        "SELECT 1 FROM sqlite_master WHERE type='table' AND name='tasks_v3' LIMIT 1",
    )
    .fetch_optional(pool)
    .await?
    .is_some();
    let has_task_activity_v3 = sqlx::query_scalar::<_, i64>(
        "SELECT 1 FROM sqlite_master WHERE type='table' AND name='task_activity_v3' LIMIT 1",
    )
    .fetch_optional(pool)
    .await?
    .is_some();
    let has_scheduled_tasks = sqlx::query_scalar::<_, i64>(
        "SELECT 1 FROM sqlite_master WHERE type='table' AND name='scheduled_tasks' LIMIT 1",
    )
    .fetch_optional(pool)
    .await?
    .is_some();

    let has_goals = sqlx::query_scalar::<_, i64>(
        "SELECT 1 FROM sqlite_master WHERE type='table' AND name='goals' LIMIT 1",
    )
    .fetch_optional(pool)
    .await?
    .is_some();

    let (goals_has_goal_type, goals_has_legacy_int_id) = if has_goals {
        let cols = sqlx::query("PRAGMA table_info(goals)")
            .fetch_all(pool)
            .await?;
        let mut has_goal_type = false;
        let mut has_legacy_int_id = false;
        for name in cols
            .iter()
            .filter_map(|r| r.try_get::<String, _>("name").ok())
        {
            if name == "goal_type" {
                has_goal_type = true;
            } else if name == "legacy_int_id" {
                has_legacy_int_id = true;
            }
        }
        (has_goal_type, has_legacy_int_id)
    } else {
        (false, false)
    };
    let has_legacy_goals = has_goals && !goals_has_goal_type;

    let has_legacy_goals_deprecated = sqlx::query_scalar::<_, i64>(
        "SELECT 1 FROM sqlite_master WHERE type='table' AND name='_goals_legacy_deprecated' LIMIT 1",
    )
    .fetch_optional(pool)
    .await?
    .is_some();

    // Keep the deprecated table for recovery, but only re-run heavy goal schema
    // unification when it still contains rows that are not represented in unified goals.
    let legacy_goals_deprecated_needs_migration = if has_legacy_goals_deprecated {
        if !has_goals || !goals_has_goal_type || !goals_has_legacy_int_id {
            true
        } else if legacy_goals_already_imported(pool).await? {
            // Retention may have removed imported goals since. They stay gone.
            false
        } else {
            sqlx::query_scalar::<_, i64>(
                "SELECT 1
                 FROM _goals_legacy_deprecated lg
                 WHERE NOT EXISTS (
                     SELECT 1
                     FROM goals g
                     WHERE g.domain = 'personal'
                       AND g.legacy_int_id = lg.id
                 )
                 LIMIT 1",
            )
            .fetch_optional(pool)
            .await?
            .is_some()
        }
    } else {
        false
    };

    let should_unify_goal_schema = has_goals_v3
        || has_tasks_v3
        || has_task_activity_v3
        || has_scheduled_tasks
        || has_legacy_goals
        || legacy_goals_deprecated_needs_migration;

    if should_unify_goal_schema {
        tracing::info!(
            "Migrating database: unifying goals/tasks schema (legacy + prior schema -> clean names)"
        );

        // Best-effort datetime parser for legacy rows.
        fn parse_legacy_datetime_to_local(raw: &str) -> Option<chrono::DateTime<chrono::Local>> {
            chrono::DateTime::parse_from_rfc3339(raw)
                .ok()
                .map(|dt| dt.with_timezone(&chrono::Local))
                .or_else(|| {
                    chrono::NaiveDateTime::parse_from_str(raw, "%Y-%m-%d %H:%M:%S")
                        .ok()
                        .and_then(|naive| match chrono::Local.from_local_datetime(&naive) {
                            chrono::LocalResult::Single(dt) => Some(dt),
                            chrono::LocalResult::Ambiguous(early, _) => Some(early),
                            chrono::LocalResult::None => None,
                        })
                })
        }

        let mut tx = pool.begin_with("BEGIN IMMEDIATE").await?;

        // Helper: column existence check (works even if the table doesn't exist).
        async fn column_exists(
            tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
            table: &str,
            column: &str,
        ) -> anyhow::Result<bool> {
            let rows = sqlx::query(sqlx::AssertSqlSafe(format!("PRAGMA table_info({})", table)))
                .fetch_all(&mut **tx)
                .await?;
            Ok(rows
                .iter()
                .filter_map(|r| r.try_get::<String, _>("name").ok())
                .any(|n| n == column))
        }

        async fn table_exists(
            tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
            name: &str,
        ) -> anyhow::Result<bool> {
            Ok(sqlx::query_scalar::<_, i64>(
                "SELECT 1 FROM sqlite_master WHERE type='table' AND name=? LIMIT 1",
            )
            .bind(name)
            .fetch_optional(&mut **tx)
            .await?
            .is_some())
        }

        // 1) If a legacy `goals` table exists (INTEGER PK), rename it out of the way.
        // Drop the legacy index first to avoid name collisions when we create new indexes.
        let goals_is_legacy = table_exists(&mut tx, "goals").await?
            && !column_exists(&mut tx, "goals", "goal_type").await?;
        if goals_is_legacy && !table_exists(&mut tx, "_goals_legacy_deprecated").await? {
            let _ = sqlx::query("DROP INDEX IF EXISTS idx_goals_status")
                .execute(&mut *tx)
                .await;
            sqlx::query("ALTER TABLE goals RENAME TO _goals_legacy_deprecated")
                .execute(&mut *tx)
                .await?;
        }

        // 2) Rename prior orchestration tables to clean names.
        if table_exists(&mut tx, "goals_v3").await? && !table_exists(&mut tx, "goals").await? {
            sqlx::query("ALTER TABLE goals_v3 RENAME TO goals")
                .execute(&mut *tx)
                .await?;
        }
        if table_exists(&mut tx, "tasks_v3").await? && !table_exists(&mut tx, "tasks").await? {
            sqlx::query("ALTER TABLE tasks_v3 RENAME TO tasks")
                .execute(&mut *tx)
                .await?;
        }
        if table_exists(&mut tx, "task_activity_v3").await?
            && !table_exists(&mut tx, "task_activity").await?
        {
            sqlx::query("ALTER TABLE task_activity_v3 RENAME TO task_activity")
                .execute(&mut *tx)
                .await?;
        }

        // 3) Drop old index names (SQLite keeps index names on table rename).
        let _ = sqlx::query("DROP INDEX IF EXISTS idx_goals_v3_status")
            .execute(&mut *tx)
            .await;
        let _ = sqlx::query("DROP INDEX IF EXISTS idx_goals_v3_session")
            .execute(&mut *tx)
            .await;
        let _ = sqlx::query("DROP INDEX IF EXISTS idx_tasks_v3_goal")
            .execute(&mut *tx)
            .await;
        let _ = sqlx::query("DROP INDEX IF EXISTS idx_tasks_v3_status")
            .execute(&mut *tx)
            .await;
        let _ = sqlx::query("DROP INDEX IF EXISTS idx_task_activity_v3_task")
            .execute(&mut *tx)
            .await;
        let _ = sqlx::query("DROP INDEX IF EXISTS idx_task_activity_v3_created_at")
            .execute(&mut *tx)
            .await;

        // 4) Create clean tables if missing (fresh installs or legacy DBs).
        sqlx::query(
            "CREATE TABLE IF NOT EXISTS goals (
                id TEXT PRIMARY KEY,
                description TEXT NOT NULL,
                domain TEXT NOT NULL DEFAULT 'orchestration',
                goal_type TEXT NOT NULL DEFAULT 'finite',
                status TEXT NOT NULL DEFAULT 'active',
                priority TEXT NOT NULL DEFAULT 'medium',
                conditions TEXT,
                context TEXT,
                resources TEXT,
                budget_per_check INTEGER,
                budget_daily INTEGER,
                tokens_used_today INTEGER NOT NULL DEFAULT 0,
                tokens_used_day TEXT NOT NULL DEFAULT '1970-01-01',
                last_useful_action TEXT,
                created_at TEXT NOT NULL DEFAULT (datetime('now')),
                updated_at TEXT NOT NULL DEFAULT (datetime('now')),
                completed_at TEXT,
                parent_goal_id TEXT,
                session_id TEXT NOT NULL,
                notified_at TEXT,
                notification_attempts INTEGER NOT NULL DEFAULT 0,
                dispatch_failures INTEGER NOT NULL DEFAULT 0,
                progress_notes TEXT,
                source_episode_id INTEGER REFERENCES episodes(id),
                legacy_int_id INTEGER
            )",
        )
        .execute(&mut *tx)
        .await?;

        sqlx::query(
            "CREATE TABLE IF NOT EXISTS tasks (
                id TEXT PRIMARY KEY,
                goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
                description TEXT NOT NULL,
                status TEXT NOT NULL DEFAULT 'pending',
                priority TEXT NOT NULL DEFAULT 'medium',
                task_order INTEGER NOT NULL DEFAULT 0,
                parallel_group TEXT,
                depends_on TEXT,
                agent_id TEXT,
                context TEXT,
                result TEXT,
                error TEXT,
                blocker TEXT,
                idempotent INTEGER NOT NULL DEFAULT 0,
                retry_count INTEGER NOT NULL DEFAULT 0,
                max_retries INTEGER NOT NULL DEFAULT 3,
                created_at TEXT NOT NULL DEFAULT (datetime('now')),
                started_at TEXT,
                completed_at TEXT
            )",
        )
        .execute(&mut *tx)
        .await?;

        sqlx::query(
            "CREATE TABLE IF NOT EXISTS task_activity (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
                activity_type TEXT NOT NULL,
                tool_name TEXT,
                tool_args TEXT,
                result TEXT,
                success INTEGER,
                tokens_used INTEGER,
                created_at TEXT NOT NULL DEFAULT (datetime('now'))
            )",
        )
        .execute(&mut *tx)
        .await?;

        sqlx::query(
            "CREATE TABLE IF NOT EXISTS goal_schedules (
                id TEXT PRIMARY KEY,
                goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
                cron_expr TEXT NOT NULL,
                tz TEXT NOT NULL DEFAULT 'local',
                original_schedule TEXT,
                fire_policy TEXT NOT NULL DEFAULT 'coalesce',
                is_one_shot INTEGER NOT NULL DEFAULT 0,
                is_paused INTEGER NOT NULL DEFAULT 0,
                last_run_at TEXT,
                next_run_at TEXT NOT NULL,
                created_at TEXT NOT NULL DEFAULT (datetime('now')),
                updated_at TEXT NOT NULL DEFAULT (datetime('now'))
            )",
        )
        .execute(&mut *tx)
        .await?;

        // 5) Ensure new columns exist on renamed goals table.
        aidaemon_tools::sqlite_schema::add_column_if_missing_on(
            &mut tx,
            "ALTER TABLE goals ADD COLUMN domain TEXT NOT NULL DEFAULT 'orchestration'",
        )
        .await?;
        aidaemon_tools::sqlite_schema::add_column_if_missing_on(
            &mut tx,
            "ALTER TABLE goals ADD COLUMN tokens_used_day TEXT NOT NULL DEFAULT '1970-01-01'",
        )
        .await?;
        aidaemon_tools::sqlite_schema::add_column_if_missing_on(
            &mut tx,
            "ALTER TABLE goals ADD COLUMN notification_attempts INTEGER NOT NULL DEFAULT 0",
        )
        .await?;
        aidaemon_tools::sqlite_schema::add_column_if_missing_on(
            &mut tx,
            "ALTER TABLE goals ADD COLUMN dispatch_failures INTEGER NOT NULL DEFAULT 0",
        )
        .await?;
        aidaemon_tools::sqlite_schema::add_column_if_missing_on(
            &mut tx,
            "ALTER TABLE goals ADD COLUMN progress_notes TEXT",
        )
        .await?;
        aidaemon_tools::sqlite_schema::add_column_if_missing_on(
            &mut tx,
            "ALTER TABLE goals ADD COLUMN source_episode_id INTEGER",
        )
        .await?;
        aidaemon_tools::sqlite_schema::add_column_if_missing_on(
            &mut tx,
            "ALTER TABLE goals ADD COLUMN legacy_int_id INTEGER",
        )
        .await?;

        // 6) Create clean indexes (drop potential collisions first).
        let _ = sqlx::query("DROP INDEX IF EXISTS idx_goals_status")
            .execute(&mut *tx)
            .await;
        let _ = sqlx::query("DROP INDEX IF EXISTS idx_goals_session")
            .execute(&mut *tx)
            .await;

        sqlx::query("CREATE INDEX IF NOT EXISTS idx_goals_status ON goals(status)")
            .execute(&mut *tx)
            .await?;
        sqlx::query("CREATE INDEX IF NOT EXISTS idx_goals_session ON goals(session_id)")
            .execute(&mut *tx)
            .await?;
        sqlx::query("CREATE INDEX IF NOT EXISTS idx_goals_domain_status ON goals(domain, status)")
            .execute(&mut *tx)
            .await?;
        sqlx::query("CREATE INDEX IF NOT EXISTS idx_tasks_goal ON tasks(goal_id)")
            .execute(&mut *tx)
            .await?;
        sqlx::query("CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks(status)")
            .execute(&mut *tx)
            .await?;
        sqlx::query("CREATE INDEX IF NOT EXISTS idx_task_activity_task ON task_activity(task_id)")
            .execute(&mut *tx)
            .await?;
        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_task_activity_created_at ON task_activity(created_at)",
        )
        .execute(&mut *tx)
        .await?;
        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_goal_schedules_goal ON goal_schedules(goal_id)",
        )
        .execute(&mut *tx)
        .await?;
        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_goal_schedules_next_run
             ON goal_schedules(next_run_at) WHERE is_paused = 0",
        )
        .execute(&mut *tx)
        .await?;

        // 7) Migrate legacy personal goals into unified `goals` (domain='personal').
        if table_exists(&mut tx, "_goals_legacy_deprecated").await? {
            sqlx::query(
                "INSERT OR IGNORE INTO goals (
                    id, description, domain, goal_type, status, priority,
                    conditions, context, resources,
                    budget_per_check, budget_daily,
                    tokens_used_today, tokens_used_day,
                    last_useful_action,
                    created_at, updated_at, completed_at,
                    parent_goal_id, session_id, notified_at,
                    notification_attempts, dispatch_failures,
                    progress_notes, source_episode_id, legacy_int_id
                )
                SELECT
                    'personal-legacy-' || id,
                    description,
                    'personal',
                    'finite',
                    COALESCE(status, 'active'),
                    COALESCE(priority, 'medium'),
                    NULL, NULL, NULL,
                    NULL, NULL,
                    0,
                    '1970-01-01',
                    NULL,
                    created_at,
                    updated_at,
                    completed_at,
                    NULL,
                    '_global',
                    NULL,
                    0,
                    0,
                    progress_notes,
                    source_episode_id,
                    id
                FROM _goals_legacy_deprecated",
            )
            .execute(&mut *tx)
            .await?;
        }

        // 8) Migrate schedules stored as `goals.schedule` into `goal_schedules`.
        if column_exists(&mut tx, "goals", "schedule").await? {
            let rows = sqlx::query(
                "SELECT id, goal_type, status, schedule, created_at, last_useful_action
                 FROM goals
                 WHERE schedule IS NOT NULL AND TRIM(schedule) != ''",
            )
            .fetch_all(&mut *tx)
            .await?;

            for r in &rows {
                let goal_id: String = r.get("id");
                let goal_type: String = r.get("goal_type");
                let status: String = r.get("status");
                let cron_expr: Option<String> = r.get("schedule");
                let created_at: String = r.get("created_at");
                let last_useful_action: Option<String> = r.get("last_useful_action");

                let Some(cron_expr) = cron_expr
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty())
                else {
                    continue;
                };

                // Deterministic schedule ID keeps migration idempotent.
                let schedule_id = format!("sched-migrated-{}", goal_id);

                let cron: croner::Cron = match cron_expr.parse() {
                    Ok(c) => c,
                    Err(_) => continue,
                };

                // Anchor next-run computation to last_useful_action or created_at,
                // matching prior behavior (so one-shots overdue on restart fire ASAP).
                let anchor_local = last_useful_action
                    .as_deref()
                    .and_then(parse_legacy_datetime_to_local)
                    .or_else(|| parse_legacy_datetime_to_local(&created_at))
                    .unwrap_or_else(chrono::Local::now);

                let next_local = match cron.find_next_occurrence(&anchor_local, false) {
                    Ok(dt) => dt,
                    Err(_) => continue,
                };

                let is_one_shot = goal_type == "finite" && is_one_shot_schedule(&cron_expr);
                let fire_policy = "coalesce";
                let tz = "local";
                let now = chrono::Utc::now().to_rfc3339();
                let next_run_at = next_local.with_timezone(&chrono::Utc).to_rfc3339();

                let schedule_paused = status == "paused";

                let _ = sqlx::query(
                    "INSERT OR IGNORE INTO goal_schedules
                        (id, goal_id, cron_expr, tz, original_schedule, fire_policy, is_one_shot, is_paused, last_run_at, next_run_at, created_at, updated_at)
                     VALUES (?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?)",
                )
                .bind(&schedule_id)
                .bind(&goal_id)
                .bind(&cron_expr)
                .bind(tz)
                .bind(fire_policy)
                .bind(if is_one_shot { 1 } else { 0 })
                .bind(if schedule_paused { 1 } else { 0 })
                .bind(&last_useful_action)
                .bind(&next_run_at)
                .bind(&now)
                .bind(&now)
                .execute(&mut *tx)
                .await;
            }
        }

        // 9) Migrate legacy scheduled_tasks rows into goals + goal_schedules, then drop the table.
        if table_exists(&mut tx, "scheduled_tasks").await? {
            let rows = sqlx::query(
                "SELECT id, name, cron_expr, original_schedule, prompt, source, is_oneshot, is_paused,
                        last_run_at, next_run_at
                 FROM scheduled_tasks
                 ORDER BY created_at ASC",
            )
            .fetch_all(&mut *tx)
            .await?;

            let now_rfc3339 = chrono::Utc::now().to_rfc3339();
            let now_local = chrono::Local::now();

            for r in &rows {
                let legacy_id: String = r.get("id");
                let legacy_name: String = r.get("name");
                let legacy_cron: String = r.get("cron_expr");
                let legacy_original_schedule: String = r.get("original_schedule");
                let legacy_prompt: String = r.get("prompt");
                let legacy_source: String = r.get("source");
                let legacy_is_oneshot: bool = r.get::<i64, _>("is_oneshot") != 0;
                let legacy_is_paused: bool = r.get::<i64, _>("is_paused") != 0;
                let legacy_last_run: Option<String> = r.get("last_run_at");
                let legacy_next_run: String = r.get("next_run_at");

                let migrated_goal_id = format!("legacy-sched-{}", legacy_id);
                let description = if !legacy_prompt.trim().is_empty() {
                    legacy_prompt.trim().to_string()
                } else {
                    legacy_name.clone()
                };

                // If this goal already exists (e.g., migrated earlier by runtime code), skip creating it.
                let goal_exists =
                    sqlx::query_scalar::<_, i64>("SELECT 1 FROM goals WHERE id = ? LIMIT 1")
                        .bind(&migrated_goal_id)
                        .fetch_optional(&mut *tx)
                        .await?
                        .is_some();

                if !goal_exists {
                    let (goal_type, priority, budget_per_check, budget_daily) = if legacy_is_oneshot
                    {
                        ("finite", "medium", Some(100_000i64), Some(500_000i64))
                    } else {
                        ("continuous", "low", Some(100_000i64), Some(500_000i64))
                    };

                    let status = if legacy_is_paused { "paused" } else { "active" };

                    let ctx = serde_json::json!({
                        "migrated_from": "scheduled_tasks",
                        "legacy_task_id": legacy_id,
                        "legacy_name": legacy_name,
                        "legacy_source": legacy_source,
                        "legacy_original_schedule": legacy_original_schedule,
                        "legacy_next_run_at": legacy_next_run,
                    })
                    .to_string();

                    let _ = sqlx::query(
                        "INSERT OR IGNORE INTO goals
                            (id, description, domain, goal_type, status, priority, conditions, context, resources,
                             budget_per_check, budget_daily, tokens_used_today, tokens_used_day, last_useful_action,
                             created_at, updated_at, completed_at, parent_goal_id, session_id, notified_at,
                             notification_attempts, dispatch_failures, progress_notes, source_episode_id, legacy_int_id)
                         VALUES (?, ?, 'orchestration', ?, ?, ?, NULL, ?, NULL, ?, ?, 0, ?, ?, ?, ?, NULL, NULL, 'system', NULL, 0, 0, NULL, NULL, NULL)",
                    )
                    .bind(&migrated_goal_id)
                    .bind(&description)
                    .bind(goal_type)
                    .bind(status)
                    .bind(priority)
                    .bind(&ctx)
                    .bind(budget_per_check)
                    .bind(budget_daily)
                    .bind(chrono::Utc::now().date_naive().to_string())
                    .bind(legacy_last_run.as_deref().unwrap_or(""))
                    .bind(&now_rfc3339)
                    .bind(&now_rfc3339)
                    .execute(&mut *tx)
                    .await;
                }

                // Schedule: preserve legacy next_run_at when possible.
                let cron_expr = if legacy_is_oneshot {
                    let target_local = parse_legacy_datetime_to_local(&legacy_next_run)
                        .unwrap_or_else(|| now_local + chrono::Duration::minutes(1));
                    let effective_target = if target_local <= now_local {
                        now_local + chrono::Duration::minutes(1)
                    } else {
                        target_local
                    };
                    format!(
                        "{} {} {} {} *",
                        effective_target.minute(),
                        effective_target.hour(),
                        effective_target.day(),
                        effective_target.month()
                    )
                } else {
                    legacy_cron.clone()
                };

                let next_run_at = parse_legacy_datetime_to_local(&legacy_next_run)
                    .map(|dt| dt.with_timezone(&chrono::Utc).to_rfc3339())
                    .unwrap_or_else(|| chrono::Utc::now().to_rfc3339());

                let schedule_id = format!("sched-legacy-{}", legacy_id);
                let _ = sqlx::query(
                    "INSERT OR IGNORE INTO goal_schedules
                        (id, goal_id, cron_expr, tz, original_schedule, fire_policy, is_one_shot, is_paused, last_run_at, next_run_at, created_at, updated_at)
                     VALUES (?, ?, ?, 'local', ?, 'coalesce', ?, ?, ?, ?, ?, ?)",
                )
                .bind(&schedule_id)
                .bind(&migrated_goal_id)
                .bind(&cron_expr)
                .bind(&legacy_original_schedule)
                .bind(if legacy_is_oneshot { 1 } else { 0 })
                .bind(if legacy_is_paused { 1 } else { 0 })
                .bind(&legacy_last_run)
                .bind(&next_run_at)
                .bind(&now_rfc3339)
                .bind(&now_rfc3339)
                .execute(&mut *tx)
                .await;
            }

            let _ = sqlx::query("DROP TABLE IF EXISTS scheduled_tasks")
                .execute(&mut *tx)
                .await;
        }

        tx.commit().await?;
    }

    // Ensure clean schema exists for fresh installs or already-migrated DBs.
    sqlx::query(
        "CREATE TABLE IF NOT EXISTS goals (
            id TEXT PRIMARY KEY,
            description TEXT NOT NULL,
            domain TEXT NOT NULL DEFAULT 'orchestration',
            goal_type TEXT NOT NULL DEFAULT 'finite',
            status TEXT NOT NULL DEFAULT 'active',
            priority TEXT NOT NULL DEFAULT 'medium',
            conditions TEXT,
            context TEXT,
            resources TEXT,
            budget_per_check INTEGER,
            budget_daily INTEGER,
            tokens_used_today INTEGER NOT NULL DEFAULT 0,
            tokens_used_day TEXT NOT NULL DEFAULT '1970-01-01',
            last_useful_action TEXT,
            created_at TEXT NOT NULL DEFAULT (datetime('now')),
            updated_at TEXT NOT NULL DEFAULT (datetime('now')),
            completed_at TEXT,
            parent_goal_id TEXT,
            session_id TEXT NOT NULL,
            notified_at TEXT,
            notification_attempts INTEGER NOT NULL DEFAULT 0,
            dispatch_failures INTEGER NOT NULL DEFAULT 0,
            progress_notes TEXT,
            source_episode_id INTEGER REFERENCES episodes(id),
            legacy_int_id INTEGER
        )",
    )
    .execute(pool)
    .await?;

    sqlx::query(
        "CREATE TABLE IF NOT EXISTS tasks (
            id TEXT PRIMARY KEY,
            goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
            description TEXT NOT NULL,
            status TEXT NOT NULL DEFAULT 'pending',
            priority TEXT NOT NULL DEFAULT 'medium',
            task_order INTEGER NOT NULL DEFAULT 0,
            parallel_group TEXT,
            depends_on TEXT,
            agent_id TEXT,
            context TEXT,
            result TEXT,
            error TEXT,
            blocker TEXT,
            idempotent INTEGER NOT NULL DEFAULT 0,
            retry_count INTEGER NOT NULL DEFAULT 0,
            max_retries INTEGER NOT NULL DEFAULT 3,
            created_at TEXT NOT NULL DEFAULT (datetime('now')),
            started_at TEXT,
            completed_at TEXT
        )",
    )
    .execute(pool)
    .await?;

    sqlx::query(
        "CREATE TABLE IF NOT EXISTS task_activity (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
            activity_type TEXT NOT NULL,
            tool_name TEXT,
            tool_args TEXT,
            result TEXT,
            success INTEGER,
            tokens_used INTEGER,
            created_at TEXT NOT NULL DEFAULT (datetime('now'))
        )",
    )
    .execute(pool)
    .await?;

    sqlx::query(
        "CREATE TABLE IF NOT EXISTS goal_schedules (
            id TEXT PRIMARY KEY,
            goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
            cron_expr TEXT NOT NULL,
            tz TEXT NOT NULL DEFAULT 'local',
            original_schedule TEXT,
            fire_policy TEXT NOT NULL DEFAULT 'coalesce',
            is_one_shot INTEGER NOT NULL DEFAULT 0,
            is_paused INTEGER NOT NULL DEFAULT 0,
            last_run_at TEXT,
            next_run_at TEXT NOT NULL,
            created_at TEXT NOT NULL DEFAULT (datetime('now')),
            updated_at TEXT NOT NULL DEFAULT (datetime('now'))
        )",
    )
    .execute(pool)
    .await?;

    sqlx::query(
        "CREATE TABLE IF NOT EXISTS scheduled_run_state (
            goal_id TEXT PRIMARY KEY REFERENCES goals(id) ON DELETE CASCADE,
            root_task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
            effective_budget_per_check INTEGER NOT NULL,
            tokens_used INTEGER NOT NULL DEFAULT 0,
            budget_extensions_count INTEGER NOT NULL DEFAULT 0,
            health_json TEXT NOT NULL DEFAULT '{}',
            created_at TEXT NOT NULL DEFAULT (datetime('now')),
            updated_at TEXT NOT NULL DEFAULT (datetime('now'))
        )",
    )
    .execute(pool)
    .await?;

    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE scheduled_run_state ADD COLUMN health_json TEXT NOT NULL DEFAULT '{}'",
    )
    .await?;
    sqlx::query(
        "CREATE TABLE IF NOT EXISTS scheduled_recovery_state (
            goal_id TEXT PRIMARY KEY REFERENCES goals(id) ON DELETE CASCADE,
            consecutive_failures INTEGER NOT NULL DEFAULT 0,
            failure_budget INTEGER NOT NULL DEFAULT 3 CHECK (failure_budget BETWEEN 1 AND 10),
            disposition TEXT NOT NULL DEFAULT 'healthy'
                CHECK (disposition IN ('healthy', 'recovering', 'escalated')),
            latest_failure_kind TEXT,
            last_failed_run_id TEXT REFERENCES goal_runs(id) ON DELETE SET NULL,
            last_recovery_run_id TEXT REFERENCES goal_runs(id) ON DELETE SET NULL,
            updated_at TEXT NOT NULL
        )",
    )
    .execute(pool)
    .await?;
    // Additive columns for automatic post-escalation recovery attempts.
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE scheduled_recovery_state
            ADD COLUMN recovery_attempts INTEGER NOT NULL DEFAULT 0",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE scheduled_recovery_state ADD COLUMN last_recovery_attempt_at TEXT",
    )
    .await?;
    sqlx::query(
        "CREATE TABLE IF NOT EXISTS goal_run_recovery_links (
            failed_run_id TEXT NOT NULL REFERENCES goal_runs(id) ON DELETE CASCADE,
            recovery_run_id TEXT NOT NULL REFERENCES goal_runs(id) ON DELETE CASCADE,
            outcome_status TEXT NOT NULL
                CHECK (outcome_status IN ('recovering', 'verified', 'failed')),
            proof_receipt_ids_json TEXT NOT NULL DEFAULT '[]',
            created_at TEXT NOT NULL,
            updated_at TEXT NOT NULL,
            PRIMARY KEY (failed_run_id, recovery_run_id)
        )",
    )
    .execute(pool)
    .await?;
    sqlx::query(
        "CREATE TABLE IF NOT EXISTS scheduled_recovery_paused_schedules (
            schedule_id TEXT PRIMARY KEY REFERENCES goal_schedules(id) ON DELETE CASCADE,
            goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
            paused_at TEXT NOT NULL
        )",
    )
    .execute(pool)
    .await?;

    // Columns on goals added via ALTER for older migrated databases.
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE goals ADD COLUMN domain TEXT NOT NULL DEFAULT 'orchestration'",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE goals ADD COLUMN tokens_used_day TEXT NOT NULL DEFAULT '1970-01-01'",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE goals ADD COLUMN notification_attempts INTEGER NOT NULL DEFAULT 0",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE goals ADD COLUMN dispatch_failures INTEGER NOT NULL DEFAULT 0",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE goals ADD COLUMN progress_notes TEXT",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE goals ADD COLUMN source_episode_id INTEGER",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE goals ADD COLUMN legacy_int_id INTEGER",
    )
    .await?;

    // Durable collaborative-work model. The default project keeps existing
    // installations behaviorally unchanged while making project scope explicit.
    sqlx::query(
        "CREATE TABLE IF NOT EXISTS work_projects (
            id TEXT PRIMARY KEY,
            name TEXT NOT NULL COLLATE NOCASE UNIQUE,
            description TEXT,
            created_at TEXT NOT NULL DEFAULT (datetime('now')),
            updated_at TEXT NOT NULL DEFAULT (datetime('now'))
        )",
    )
    .execute(pool)
    .await?;
    // A project's folder (any folder: a repository, a site, designs);
    // conversations in the project work there.
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE work_projects ADD COLUMN path TEXT",
    )
    .await?;
    sqlx::query(
        "INSERT OR IGNORE INTO work_projects (id, name, description)
         VALUES ('default', 'Default', 'Default Aidaemon work project')",
    )
    .execute(pool)
    .await?;

    sqlx::query(
        "CREATE TABLE IF NOT EXISTS session_work_projects (
            session_id TEXT PRIMARY KEY,
            project_id TEXT NOT NULL REFERENCES work_projects(id) ON DELETE CASCADE,
            updated_at TEXT NOT NULL DEFAULT (datetime('now'))
        )",
    )
    .execute(pool)
    .await?;
    // The project a chat bot's direct-message chats go to (`channel`: the
    // bot's session channel, `telegram:coding_bot`).
    sqlx::query(
        "CREATE TABLE IF NOT EXISTS channel_work_projects (
            channel TEXT PRIMARY KEY,
            project_id TEXT NOT NULL REFERENCES work_projects(id) ON DELETE CASCADE,
            updated_at TEXT NOT NULL DEFAULT (datetime('now'))
        )",
    )
    .execute(pool)
    .await?;

    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE goals ADD COLUMN project_id TEXT NOT NULL DEFAULT 'default'",
    )
    .await?;
    sqlx::query(
        "UPDATE goals SET project_id = 'default' WHERE project_id IS NULL OR project_id = ''",
    )
    .execute(pool)
    .await?;

    sqlx::query(
        "CREATE TABLE IF NOT EXISTS goal_runs (
            id TEXT PRIMARY KEY,
            project_id TEXT NOT NULL REFERENCES work_projects(id) ON DELETE CASCADE,
            goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
            trigger_type TEXT NOT NULL,
            schedule_id TEXT REFERENCES goal_schedules(id) ON DELETE SET NULL,
            root_task_id TEXT,
            status TEXT NOT NULL DEFAULT 'running',
            outcome_summary TEXT,
            started_at TEXT NOT NULL DEFAULT (datetime('now')),
            completed_at TEXT,
            created_at TEXT NOT NULL DEFAULT (datetime('now')),
            updated_at TEXT NOT NULL DEFAULT (datetime('now'))
        )",
    )
    .execute(pool)
    .await?;

    // Owner-authorized autonomy. A mandate is intentionally separate from a
    // personal goal (desire) and from an intention (one agent commitment).
    // Every decision cycle is bound to exactly one durable goal run.
    sqlx::query(
        "CREATE TABLE IF NOT EXISTS mandates (
            id TEXT PRIMARY KEY,
            goal_id TEXT NOT NULL UNIQUE REFERENCES goals(id) ON DELETE CASCADE,
            source_goal_id TEXT REFERENCES goals(id) ON DELETE SET NULL,
            name TEXT,
            objective TEXT NOT NULL,
            status TEXT NOT NULL DEFAULT 'active'
                CHECK (status IN ('active', 'paused', 'awaiting_input', 'completed', 'cancelled')),
            autonomy_mode TEXT NOT NULL DEFAULT 'bounded'
                CHECK (autonomy_mode IN ('bounded', 'autopilot')),
            authority_json TEXT NOT NULL,
            strategy_json TEXT,
            objective_control_json TEXT,
            suspension_json TEXT,
            constraints_json TEXT NOT NULL DEFAULT '[]',
            success_criteria_json TEXT NOT NULL DEFAULT '[]',
            stop_conditions_json TEXT NOT NULL DEFAULT '[]',
            min_review_secs INTEGER NOT NULL CHECK (min_review_secs > 0),
            max_review_secs INTEGER NOT NULL CHECK (max_review_secs >= min_review_secs),
            default_review_secs INTEGER NOT NULL
                CHECK (default_review_secs BETWEEN min_review_secs AND max_review_secs),
            review_effort TEXT NOT NULL DEFAULT 'balanced'
                CHECK (review_effort IN ('efficient', 'balanced', 'thorough', 'legacy_custom')),
            next_review_at TEXT NOT NULL,
            review_lease_token TEXT,
            review_lease_expires_at TEXT,
            expires_at TEXT,
            confirmed_at TEXT,
            version INTEGER NOT NULL DEFAULT 1 CHECK (version > 0),
            owner_principal_id TEXT NOT NULL,
            created_by_session TEXT NOT NULL,
            created_at TEXT NOT NULL DEFAULT (datetime('now')),
            updated_at TEXT NOT NULL DEFAULT (datetime('now'))
        )",
    )
    .execute(pool)
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE mandates ADD COLUMN owner_principal_id TEXT",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE mandates ADD COLUMN objective_control_json TEXT",
    )
    .await?;
    // The owner-given name (nullable: mandates created before it have none).
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE mandates ADD COLUMN name TEXT",
    )
    .await?;
    sqlx::query(
        "UPDATE mandates SET owner_principal_id = 'principal:' || id
         WHERE owner_principal_id IS NULL OR trim(owner_principal_id) = ''",
    )
    .execute(pool)
    .await?;
    sqlx::query(
        "CREATE TABLE IF NOT EXISTS mandate_principal_sessions (
            principal_id TEXT NOT NULL,
            session_id TEXT NOT NULL,
            linked_at TEXT NOT NULL,
            linked_by_session TEXT NOT NULL,
            PRIMARY KEY (principal_id, session_id)
        )",
    )
    .execute(pool)
    .await?;
    // Links for mandates made before links existed, once
    // ([`WORK_BACKFILLS_DONE_VERSION`]): a link taken back must stay gone.
    if !work_backfills_done(pool).await? {
        sqlx::query(
            "INSERT OR IGNORE INTO mandate_principal_sessions
                (principal_id, session_id, linked_at, linked_by_session)
             SELECT owner_principal_id, created_by_session, created_at, created_by_session
             FROM mandates",
        )
        .execute(pool)
        .await?;
        // Older mandates were assigned one random principal per mandate. Migrate
        // only channel identities whose platform semantics prove they are the
        // same private owner across bot routes; never infer group or arbitrary
        // session-name equivalence.
        let mandate_owner_rows = sqlx::query("SELECT id, created_by_session FROM mandates")
            .fetch_all(pool)
            .await?;
        for row in mandate_owner_rows {
            let mandate_id: String = row.get("id");
            let created_by_session: String = row.get("created_by_session");
            let Some(principal_id) =
                aidaemon_events::session::stable_private_owner_principal_id(&created_by_session)
            else {
                continue;
            };
            sqlx::query("UPDATE mandates SET owner_principal_id = ? WHERE id = ?")
                .bind(&principal_id)
                .bind(&mandate_id)
                .execute(pool)
                .await?;
            sqlx::query(
                "INSERT OR IGNORE INTO mandate_principal_sessions
                    (principal_id, session_id, linked_at, linked_by_session)
                 VALUES (?, ?, datetime('now'), ?)",
            )
            .bind(&principal_id)
            .bind(&created_by_session)
            .bind(&created_by_session)
            .execute(pool)
            .await?;
        }
    }
    sqlx::query(
        "CREATE INDEX IF NOT EXISTS idx_mandate_principal_sessions_session
         ON mandate_principal_sessions(session_id, principal_id)",
    )
    .execute(pool)
    .await?;
    sqlx::query(
        "CREATE TABLE IF NOT EXISTS mandate_objective_measurements (
            id TEXT PRIMARY KEY,
            mandate_id TEXT NOT NULL REFERENCES mandates(id) ON DELETE CASCADE,
            mandate_version INTEGER NOT NULL CHECK (mandate_version > 0),
            goal_run_id TEXT NOT NULL REFERENCES goal_runs(id) ON DELETE CASCADE,
            value_micros INTEGER NOT NULL,
            confidence_bps INTEGER NOT NULL CHECK (confidence_bps BETWEEN 0 AND 10000),
            evidence_receipt_ids_json TEXT NOT NULL,
            attributed_intention_ids_json TEXT NOT NULL DEFAULT '[]',
            observed_at TEXT NOT NULL,
            created_at TEXT NOT NULL,
            UNIQUE (mandate_id, goal_run_id, observed_at)
        )",
    )
    .execute(pool)
    .await?;
    sqlx::query(
        "CREATE INDEX IF NOT EXISTS idx_mandate_measurements_recent
         ON mandate_objective_measurements(mandate_id, observed_at DESC)",
    )
    .execute(pool)
    .await?;
    sqlx::query(
        "CREATE TABLE IF NOT EXISTS mandate_ownership_transfers (
            id TEXT PRIMARY KEY,
            mandate_id TEXT NOT NULL REFERENCES mandates(id) ON DELETE CASCADE,
            principal_id TEXT NOT NULL,
            from_session_id TEXT NOT NULL,
            to_session_id TEXT NOT NULL,
            from_version INTEGER NOT NULL,
            to_version INTEGER NOT NULL,
            transferred_at TEXT NOT NULL
        )",
    )
    .execute(pool)
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE mandates ADD COLUMN autonomy_mode TEXT NOT NULL DEFAULT 'bounded'
         CHECK (autonomy_mode IN ('bounded', 'autopilot'))",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE mandates ADD COLUMN review_effort TEXT NOT NULL DEFAULT 'balanced'
         CHECK (review_effort IN ('efficient', 'balanced', 'thorough', 'legacy_custom'))",
    )
    .await?;

    // One immutable aggregate budget per autonomous decision cycle. The
    // short-lived call lease serializes lead/executor model calls so they
    // cannot each observe the same remaining balance and overspend in
    // parallel. Usage survives daemon restarts and is never auto-extended.
    sqlx::query(
        "CREATE TABLE IF NOT EXISTS mandate_run_token_budgets (
            goal_run_id TEXT PRIMARY KEY REFERENCES goal_runs(id) ON DELETE CASCADE,
            budget_per_cycle INTEGER NOT NULL CHECK (budget_per_cycle > 0),
            tokens_used INTEGER NOT NULL DEFAULT 0 CHECK (tokens_used >= 0),
            call_lease_token TEXT,
            call_lease_expires_at TEXT,
            call_dispatched INTEGER NOT NULL DEFAULT 0 CHECK (call_dispatched IN (0, 1)),
            call_tokens_used_before INTEGER,
            created_at TEXT NOT NULL DEFAULT (datetime('now')),
            updated_at TEXT NOT NULL DEFAULT (datetime('now')),
            CHECK (
                (call_lease_token IS NULL AND call_lease_expires_at IS NULL
                    AND call_dispatched = 0 AND call_tokens_used_before IS NULL)
                OR (call_lease_token IS NOT NULL AND call_lease_expires_at IS NOT NULL
                    AND ((call_dispatched = 0 AND call_tokens_used_before IS NULL)
                         OR (call_dispatched = 1 AND call_tokens_used_before IS NOT NULL)))
            )
        )",
    )
    .execute(pool)
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE mandate_run_token_budgets
         ADD COLUMN call_dispatched INTEGER NOT NULL DEFAULT 0 CHECK (call_dispatched IN (0, 1))",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE mandate_run_token_budgets ADD COLUMN call_tokens_used_before INTEGER",
    )
    .await?;

    sqlx::query(
        "CREATE TABLE IF NOT EXISTS mandate_decision_cycles (
            id TEXT PRIMARY KEY,
            mandate_id TEXT NOT NULL REFERENCES mandates(id) ON DELETE CASCADE,
            goal_run_id TEXT NOT NULL UNIQUE REFERENCES goal_runs(id) ON DELETE CASCADE,
            mandate_version INTEGER NOT NULL,
            outcome TEXT NOT NULL CHECK (outcome IN ('act', 'wait', 'ask', 'stop')),
            origin TEXT NOT NULL DEFAULT 'deliberator'
                CHECK (origin IN ('deliberator', 'runtime_fallback')),
            activity_level TEXT NOT NULL DEFAULT 'quiet'
                CHECK (activity_level IN ('quiet', 'active', 'urgent')),
            rationale TEXT NOT NULL,
            belief_snapshot TEXT,
            evidence_receipt_ids_json TEXT NOT NULL DEFAULT '[]'
                CHECK (json_valid(evidence_receipt_ids_json)),
            question TEXT,
            termination_kind TEXT
                CHECK (termination_kind IS NULL OR termination_kind IN (
                    'success_criteria_satisfied', 'stop_condition_met', 'safety_termination'
                )),
            termination_match TEXT,
            reconsider_at TEXT,
            action_attempts INTEGER NOT NULL DEFAULT 0 CHECK (action_attempts >= 0),
            created_at TEXT NOT NULL DEFAULT (datetime('now')),
            updated_at TEXT NOT NULL DEFAULT (datetime('now'))
        )",
    )
    .execute(pool)
    .await?;

    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE mandate_decision_cycles ADD COLUMN owner_alert TEXT",
    )
    .await?;

    // Pre-release development databases may already contain the first mandate
    // draft. Keep startup migration idempotent while backfilling the durable
    // wake/lease and policy-version columns added before the first release.
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE mandates ADD COLUMN next_review_at TEXT",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE mandates ADD COLUMN review_lease_token TEXT",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE mandates ADD COLUMN review_lease_expires_at TEXT",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE mandates ADD COLUMN confirmed_at TEXT",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE mandates ADD COLUMN strategy_json TEXT",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE mandates ADD COLUMN suspension_json TEXT",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE mandate_decision_cycles
         ADD COLUMN evidence_receipt_ids_json TEXT NOT NULL DEFAULT '[]'",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE mandate_decision_cycles
         ADD COLUMN activity_level TEXT NOT NULL DEFAULT 'quiet'
         CHECK (activity_level IN ('quiet', 'active', 'urgent'))",
    )
    .await?;
    // Who wrote a decision was once read from its rationale text; existing
    // runtime-written rows are recognised by the two texts the runtime used.
    let origin_added = aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE mandate_decision_cycles
         ADD COLUMN origin TEXT NOT NULL DEFAULT 'deliberator'
         CHECK (origin IN ('deliberator', 'runtime_fallback'))",
    )
    .await?;
    if origin_added {
        sqlx::query(
            "UPDATE mandate_decision_cycles SET origin = 'runtime_fallback'
             WHERE rationale IN (?, ?)",
        )
        .bind(crate::mandates::SAFE_FALLBACK_WAIT_RATIONALE)
        .bind(
            "This review reached its internal runaway-protection ceiling before another model \
             turn could be admitted. No new action was authorized; the controller will retry \
             automatically at the earliest bounded review time.",
        )
        .execute(pool)
        .await?;
    }
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE mandate_decision_cycles ADD COLUMN termination_kind TEXT",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE mandate_decision_cycles ADD COLUMN termination_match TEXT",
    )
    .await?;
    sqlx::query(
        "UPDATE mandates
         SET next_review_at = COALESCE(next_review_at, updated_at, created_at, datetime('now'))",
    )
    .execute(pool)
    .await?;
    // Backfill only states that could have been reached after confirmation in
    // the pre-release schema. A paused mandate whose controller is still
    // pending confirmation deliberately remains unconfirmed, as do cancelled
    // records where provenance can no longer be inferred safely.
    sqlx::query(
        "UPDATE mandates
         SET confirmed_at = COALESCE(confirmed_at, created_at, updated_at, datetime('now'))
         WHERE confirmed_at IS NULL
           AND (
               status IN ('active', 'awaiting_input', 'completed')
               OR (
                   status = 'paused'
                   AND EXISTS (
                       SELECT 1 FROM goals g
                       WHERE g.id = mandates.goal_id AND g.status = 'paused'
                   )
               )
           )",
    )
    .execute(pool)
    .await?;
    sqlx::query(
        "UPDATE mandates
         SET suspension_json = json_object(
             'kind', CASE WHEN status = 'paused' THEN 'owner_paused' ELSE 'review_failed' END,
             'reason_code', 'legacy_state_backfill',
             'created_at', COALESCE(updated_at, created_at, datetime('now'))
         )
         WHERE suspension_json IS NULL
           AND confirmed_at IS NOT NULL
           AND status IN ('paused', 'awaiting_input')",
    )
    .execute(pool)
    .await?;
    let added_mandate_version = aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE mandate_decision_cycles
         ADD COLUMN mandate_version INTEGER NOT NULL DEFAULT 1",
    )
    .await?;
    if added_mandate_version {
        sqlx::query(
            "UPDATE mandate_decision_cycles
             SET mandate_version = COALESCE(
                 (SELECT m.version FROM mandates m
                  WHERE m.id = mandate_decision_cycles.mandate_id),
                 mandate_version
             )",
        )
        .execute(pool)
        .await?;
    }

    sqlx::query(
        "CREATE TABLE IF NOT EXISTS intentions (
            id TEXT PRIMARY KEY,
            mandate_id TEXT NOT NULL REFERENCES mandates(id) ON DELETE CASCADE,
            decision_cycle_id TEXT NOT NULL UNIQUE REFERENCES mandate_decision_cycles(id) ON DELETE CASCADE,
            goal_run_id TEXT NOT NULL REFERENCES goal_runs(id) ON DELETE CASCADE,
            description TEXT NOT NULL,
            rationale TEXT NOT NULL,
            value_criterion TEXT,
            expected_benefit TEXT,
            risk TEXT,
            invalidation_criteria TEXT,
            format_key TEXT,
            status TEXT NOT NULL DEFAULT 'committed',
            created_at TEXT NOT NULL DEFAULT (datetime('now')),
            updated_at TEXT NOT NULL DEFAULT (datetime('now')),
            completed_at TEXT
        )",
    )
    .execute(pool)
    .await?;
    // Existing installations may have the pre-value-contract intentions
    // table. Historical rows remain nullable and readable; every new
    // value-contract ACT is validated before insertion.
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE intentions ADD COLUMN value_criterion TEXT",
    )
    .await?;
    // The canonical format an ACT declared (`[a-z0-9_-]{1,64}`), so outcomes
    // can be grouped by format. Older rows stay NULL ("untagged").
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE intentions ADD COLUMN format_key TEXT",
    )
    .await?;

    sqlx::query(
        "CREATE TABLE IF NOT EXISTS mandate_learning_notes (
            id TEXT PRIMARY KEY,
            mandate_id TEXT NOT NULL REFERENCES mandates(id) ON DELETE CASCADE,
            mandate_version INTEGER NOT NULL CHECK (mandate_version > 0),
            learned_in_decision_cycle_id TEXT NOT NULL
                REFERENCES mandate_decision_cycles(id) ON DELETE CASCADE,
            summary TEXT NOT NULL,
            evidence_receipt_ids_json TEXT NOT NULL CHECK (json_valid(evidence_receipt_ids_json)),
            created_at TEXT NOT NULL,
            UNIQUE(mandate_id, learned_in_decision_cycle_id, summary)
        )",
    )
    .execute(pool)
    .await?;
    sqlx::query(
        "CREATE INDEX IF NOT EXISTS idx_mandate_learning_notes_recent
         ON mandate_learning_notes(mandate_id, created_at DESC)",
    )
    .execute(pool)
    .await?;

    // Append-only adaptive operating-strategy revisions. They are deliberately
    // separate from the owner-confirmed mandate policy and therefore cannot
    // grant authority. The latest revision for one key is its current node.
    sqlx::query(
        "CREATE TABLE IF NOT EXISTS mandate_strategy_revisions (
            id TEXT PRIMARY KEY,
            mandate_id TEXT NOT NULL REFERENCES mandates(id) ON DELETE CASCADE,
            mandate_version INTEGER NOT NULL CHECK (mandate_version > 0),
            decision_cycle_id TEXT NOT NULL
                REFERENCES mandate_decision_cycles(id) ON DELETE CASCADE,
            strategy_key TEXT NOT NULL,
            kind TEXT NOT NULL CHECK (kind IN ('reinforce', 'explore', 'avoid', 'retire')),
            guidance TEXT NOT NULL,
            confidence_bps INTEGER NOT NULL CHECK (confidence_bps BETWEEN 0 AND 10000),
            evidence_receipt_ids_json TEXT NOT NULL CHECK (json_valid(evidence_receipt_ids_json)),
            created_at TEXT NOT NULL,
            UNIQUE(decision_cycle_id, strategy_key)
        )",
    )
    .execute(pool)
    .await?;
    sqlx::query(
        "CREATE INDEX IF NOT EXISTS idx_mandate_strategy_revisions_latest
         ON mandate_strategy_revisions(mandate_id, strategy_key, created_at DESC, id DESC)",
    )
    .execute(pool)
    .await?;

    // Content-free, deduplicated wake receipts for structured external signals.
    // Raw webhook bodies never enter this table or the mandate prompt.
    sqlx::query(
        "CREATE TABLE IF NOT EXISTS mandate_wake_signals (
            mandate_id TEXT NOT NULL REFERENCES mandates(id) ON DELETE CASCADE,
            mandate_version INTEGER NOT NULL CHECK (mandate_version > 0),
            signal_digest TEXT NOT NULL,
            kind TEXT NOT NULL CHECK (kind IN (
                'mention', 'reply', 'reaction', 'metric_change',
                'delivery_failure', 'external_change'
            )),
            source TEXT NOT NULL,
            target_url TEXT NOT NULL,
            account_id TEXT,
            occurred_at TEXT NOT NULL,
            received_at TEXT NOT NULL,
            PRIMARY KEY(mandate_id, signal_digest)
        )",
    )
    .execute(pool)
    .await?;
    sqlx::query(
        "CREATE INDEX IF NOT EXISTS idx_mandate_wake_signals_recent
         ON mandate_wake_signals(mandate_id, received_at DESC)",
    )
    .execute(pool)
    .await?;

    sqlx::query(
        "CREATE TABLE IF NOT EXISTS mandate_reconciliations (
            id TEXT PRIMARY KEY,
            mandate_id TEXT NOT NULL REFERENCES mandates(id) ON DELETE CASCADE,
            suspended_version INTEGER NOT NULL CHECK (suspended_version > 0),
            suspension_kind TEXT NOT NULL,
            resolution TEXT NOT NULL CHECK (resolution IN (
                'confirmed_effect_occurred', 'confirmed_no_effect', 'abandon_attempt'
            )),
            owner_guidance TEXT NOT NULL,
            resolved_by_session TEXT NOT NULL,
            resolved_at TEXT NOT NULL
        )",
    )
    .execute(pool)
    .await?;

    // Cross-cycle mutation safety ledger. This table intentionally contains
    // only typed identifiers and compact execution facts; raw tool arguments,
    // bodies, outputs, errors, and credentials belong nowhere in this ledger.
    sqlx::query(
        "CREATE TABLE IF NOT EXISTS mandate_mutation_attempts (
            id TEXT PRIMARY KEY,
            mandate_id TEXT NOT NULL REFERENCES mandates(id) ON DELETE CASCADE,
            mandate_version INTEGER NOT NULL CHECK (mandate_version > 0),
            decision_cycle_id TEXT NOT NULL REFERENCES mandate_decision_cycles(id) ON DELETE CASCADE,
            goal_run_id TEXT NOT NULL REFERENCES goal_runs(id) ON DELETE CASCADE,
            intention_id TEXT NOT NULL REFERENCES intentions(id) ON DELETE CASCADE,
            root_task_id TEXT NOT NULL,
            root_task_attempt_id TEXT NOT NULL,
            task_id TEXT NOT NULL,
            task_attempt_id TEXT NOT NULL,
            reserved_action_attempt INTEGER NOT NULL CHECK (reserved_action_attempt > 0),
            action_digest TEXT NOT NULL UNIQUE CHECK (length(action_digest) = 64),
            tool_call_id TEXT NOT NULL UNIQUE,
            tool_name TEXT NOT NULL,
            mutation_effects_json TEXT NOT NULL CHECK (json_valid(mutation_effects_json)),
            targets_json TEXT NOT NULL CHECK (json_valid(targets_json)),
            account_identifiers_json TEXT NOT NULL CHECK (json_valid(account_identifiers_json)),
            status TEXT NOT NULL DEFAULT 'reserved'
                CHECK (status IN ('reserved', 'never_dispatched', 'succeeded', 'failed', 'ambiguous')),
            outcome_evidence TEXT
                CHECK (outcome_evidence IS NULL OR outcome_evidence IN ('tool_reported', 'structured_metadata')),
            http_status INTEGER CHECK (http_status IS NULL OR http_status BETWEEN 100 AND 599),
            exit_code INTEGER,
            external_resource_id TEXT,
            reserved_at TEXT NOT NULL,
            dispatch_claimed_at TEXT,
            completed_at TEXT,
            UNIQUE (decision_cycle_id, reserved_action_attempt)
        )",
    )
    .execute(pool)
    .await?;
    // Development and upgrade databases may already have the v1 ledger from
    // an earlier build. Duplicate-column is the expected no-op on fresh/newer
    // schemas; a successful ALTER upgrades the old table in place.
    let _added_dispatch_claim = aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE mandate_mutation_attempts
         ADD COLUMN dispatch_claimed_at TEXT",
    )
    .await?;

    // SQLite cannot widen an inline CHECK constraint in place. Rebuild the
    // pre-release ledger once so invalidated reservations that never crossed
    // the final dispatcher boundary can be closed without misclassifying them
    // as an ambiguous external effect.
    let mutation_attempts_schema = sqlx::query(
        "SELECT sql FROM sqlite_master
         WHERE type = 'table' AND name = 'mandate_mutation_attempts'",
    )
    .fetch_optional(pool)
    .await?
    .and_then(|row| row.try_get::<Option<String>, _>("sql").ok().flatten())
    .unwrap_or_default();
    if !mutation_attempts_schema.contains("never_dispatched") {
        let mut tx = pool.begin_with("BEGIN IMMEDIATE").await?;
        sqlx::query("DROP TABLE IF EXISTS mandate_mutation_attempts_v2")
            .execute(&mut *tx)
            .await?;
        sqlx::query(
            "CREATE TABLE mandate_mutation_attempts_v2 (
                id TEXT PRIMARY KEY,
                mandate_id TEXT NOT NULL REFERENCES mandates(id) ON DELETE CASCADE,
                mandate_version INTEGER NOT NULL CHECK (mandate_version > 0),
                decision_cycle_id TEXT NOT NULL REFERENCES mandate_decision_cycles(id) ON DELETE CASCADE,
                goal_run_id TEXT NOT NULL REFERENCES goal_runs(id) ON DELETE CASCADE,
                intention_id TEXT NOT NULL REFERENCES intentions(id) ON DELETE CASCADE,
                root_task_id TEXT NOT NULL,
                root_task_attempt_id TEXT NOT NULL,
                task_id TEXT NOT NULL,
                task_attempt_id TEXT NOT NULL,
                reserved_action_attempt INTEGER NOT NULL CHECK (reserved_action_attempt > 0),
                action_digest TEXT NOT NULL UNIQUE CHECK (length(action_digest) = 64),
                tool_call_id TEXT NOT NULL UNIQUE,
                tool_name TEXT NOT NULL,
                mutation_effects_json TEXT NOT NULL CHECK (json_valid(mutation_effects_json)),
                targets_json TEXT NOT NULL CHECK (json_valid(targets_json)),
                account_identifiers_json TEXT NOT NULL CHECK (json_valid(account_identifiers_json)),
                status TEXT NOT NULL DEFAULT 'reserved'
                    CHECK (status IN ('reserved', 'never_dispatched', 'succeeded', 'failed', 'ambiguous')),
                outcome_evidence TEXT
                    CHECK (outcome_evidence IS NULL OR outcome_evidence IN ('tool_reported', 'structured_metadata')),
                http_status INTEGER CHECK (http_status IS NULL OR http_status BETWEEN 100 AND 599),
                exit_code INTEGER,
                reserved_at TEXT NOT NULL,
                dispatch_claimed_at TEXT,
                completed_at TEXT,
                UNIQUE (decision_cycle_id, reserved_action_attempt)
            )",
        )
        .execute(&mut *tx)
        .await?;
        sqlx::query(
            "INSERT INTO mandate_mutation_attempts_v2
                (id, mandate_id, mandate_version, decision_cycle_id, goal_run_id,
                 intention_id, root_task_id, root_task_attempt_id, task_id,
                 task_attempt_id, reserved_action_attempt, action_digest,
                 tool_call_id, tool_name, mutation_effects_json, targets_json,
                 account_identifiers_json, status, outcome_evidence, http_status,
                 exit_code, reserved_at, dispatch_claimed_at, completed_at)
             SELECT id, mandate_id, mandate_version, decision_cycle_id, goal_run_id,
                    intention_id, root_task_id, root_task_attempt_id, task_id,
                    task_attempt_id, reserved_action_attempt, action_digest,
                    tool_call_id, tool_name, mutation_effects_json, targets_json,
                    account_identifiers_json, status, outcome_evidence, http_status,
                    exit_code, reserved_at, dispatch_claimed_at, completed_at
             FROM mandate_mutation_attempts",
        )
        .execute(&mut *tx)
        .await?;
        sqlx::query("DROP TABLE mandate_mutation_attempts")
            .execute(&mut *tx)
            .await?;
        sqlx::query("ALTER TABLE mandate_mutation_attempts_v2 RENAME TO mandate_mutation_attempts")
            .execute(&mut *tx)
            .await?;
        tx.commit().await?;
    }
    // The canonical id of the resource a strictly successful mutation
    // created, projected from its receipt by the event store. Added after
    // the rebuild above so an upgraded ledger gets it too.
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE mandate_mutation_attempts ADD COLUMN external_resource_id TEXT",
    )
    .await?;

    // Runtime-validated per-action outcomes: a later review reads a
    // published resource's public counts and records them against the
    // succeeded mutation that created it. Only ids and counts, never text.
    sqlx::query(
        "CREATE TABLE IF NOT EXISTS mandate_action_outcomes (
            id TEXT PRIMARY KEY,
            mandate_id TEXT NOT NULL REFERENCES mandates(id) ON DELETE CASCADE,
            mandate_version INTEGER NOT NULL CHECK (mandate_version > 0),
            decision_cycle_id TEXT NOT NULL REFERENCES mandate_decision_cycles(id) ON DELETE CASCADE,
            external_resource_id TEXT NOT NULL,
            format_key TEXT,
            engagements_micros INTEGER NOT NULL CHECK (engagements_micros >= 0),
            impressions INTEGER CHECK (impressions IS NULL OR impressions >= 0),
            evidence_receipt_ids_json TEXT NOT NULL CHECK (json_valid(evidence_receipt_ids_json)),
            observed_at TEXT NOT NULL,
            created_at TEXT NOT NULL,
            UNIQUE(mandate_id, external_resource_id, decision_cycle_id)
        )",
    )
    .execute(pool)
    .await?;
    sqlx::query(
        "CREATE INDEX IF NOT EXISTS idx_mandate_action_outcomes_recent
         ON mandate_action_outcomes(mandate_id, observed_at DESC)",
    )
    .execute(pool)
    .await?;

    sqlx::query(
        "CREATE INDEX IF NOT EXISTS idx_mandates_due
         ON mandates(status, next_review_at, review_lease_expires_at)",
    )
    .execute(pool)
    .await?;
    sqlx::query(
        "CREATE INDEX IF NOT EXISTS idx_mandate_cycles_mandate
         ON mandate_decision_cycles(mandate_id, created_at DESC)",
    )
    .execute(pool)
    .await?;
    sqlx::query(
        "CREATE INDEX IF NOT EXISTS idx_intentions_mandate
         ON intentions(mandate_id, created_at DESC)",
    )
    .execute(pool)
    .await?;
    sqlx::query(
        "CREATE INDEX IF NOT EXISTS idx_mandate_mutations_quota
         ON mandate_mutation_attempts(mandate_id, reserved_at)",
    )
    .execute(pool)
    .await?;
    sqlx::query(
        "CREATE INDEX IF NOT EXISTS idx_mandate_mutations_run_status
         ON mandate_mutation_attempts(goal_run_id, status)",
    )
    .execute(pool)
    .await?;

    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE tasks ADD COLUMN goal_run_id TEXT",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE tasks ADD COLUMN current_attempt_id TEXT",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE tasks ADD COLUMN worker_profile_id TEXT",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE tasks ADD COLUMN workspace_policy TEXT NOT NULL DEFAULT 'shared'",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE tasks ADD COLUMN workspace_policy_explicit INTEGER NOT NULL DEFAULT 0",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE tasks ADD COLUMN task_kind TEXT NOT NULL DEFAULT 'work'",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE tasks ADD COLUMN visibility TEXT NOT NULL DEFAULT 'internal'",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE tasks ADD COLUMN version INTEGER NOT NULL DEFAULT 0",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE tasks ADD COLUMN updated_at TEXT",
    )
    .await?;
    sqlx::query(
        "UPDATE tasks
         SET updated_at = COALESCE(updated_at, completed_at, started_at, created_at)",
    )
    .execute(pool)
    .await?;

    sqlx::query(
        "CREATE TABLE IF NOT EXISTS worker_profiles (
            id TEXT PRIMARY KEY,
            project_id TEXT REFERENCES work_projects(id) ON DELETE CASCADE,
            name TEXT NOT NULL,
            specialist TEXT NOT NULL,
            model TEXT,
            tools_json TEXT,
            max_iterations INTEGER,
            tool_budget INTEGER,
            timeout_secs INTEGER,
            max_concurrency INTEGER NOT NULL DEFAULT 1 CHECK (max_concurrency > 0),
            workspace_policy TEXT NOT NULL DEFAULT 'shared',
            memory_scope TEXT NOT NULL DEFAULT 'project',
            version INTEGER NOT NULL DEFAULT 1,
            enabled INTEGER NOT NULL DEFAULT 1,
            created_at TEXT NOT NULL DEFAULT (datetime('now')),
            updated_at TEXT NOT NULL DEFAULT (datetime('now')),
            UNIQUE(project_id, name)
        )",
    )
    .execute(pool)
    .await?;

    for (id, name, max_concurrency, workspace_policy) in [
        ("profile-task-lead", "task_lead", 2_i64, "shared"),
        ("profile-executor", "executor", 4_i64, "shared"),
        ("profile-research", "research", 4_i64, "shared"),
        (
            "profile-artifact-writer",
            "artifact_writer",
            2_i64,
            "shared",
        ),
        ("profile-code", "code", 2_i64, "shared"),
        (
            "profile-browser-verifier",
            "browser_verifier",
            2_i64,
            "shared",
        ),
        ("profile-review", "review", 2_i64, "shared"),
        ("profile-comms-draft", "comms_draft", 2_i64, "shared"),
        ("profile-generic", "generic", 2_i64, "shared"),
    ] {
        sqlx::query(
            "INSERT OR IGNORE INTO worker_profiles
                (id, project_id, name, specialist, max_concurrency, workspace_policy)
             VALUES (?, NULL, ?, ?, ?, ?)",
        )
        .bind(id)
        .bind(name)
        .bind(name)
        .bind(max_concurrency)
        .bind(workspace_policy)
        .execute(pool)
        .await?;
    }

    sqlx::query(
        "CREATE TABLE IF NOT EXISTS task_attempts (
            id TEXT PRIMARY KEY,
            task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
            goal_run_id TEXT NOT NULL REFERENCES goal_runs(id) ON DELETE CASCADE,
            worker_profile_id TEXT REFERENCES worker_profiles(id) ON DELETE SET NULL,
            worker_instance_id TEXT NOT NULL,
            lease_token TEXT NOT NULL UNIQUE,
            status TEXT NOT NULL,
            lease_expires_at TEXT NOT NULL,
            last_heartbeat_at TEXT NOT NULL,
            workspace_id TEXT,
            started_at TEXT NOT NULL,
            completed_at TEXT
        )",
    )
    .execute(pool)
    .await?;

    sqlx::query(
        "CREATE TABLE IF NOT EXISTS task_journal (
            id TEXT PRIMARY KEY,
            project_id TEXT NOT NULL REFERENCES work_projects(id) ON DELETE CASCADE,
            goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
            goal_run_id TEXT NOT NULL REFERENCES goal_runs(id) ON DELETE CASCADE,
            task_id TEXT REFERENCES tasks(id) ON DELETE CASCADE,
            attempt_id TEXT REFERENCES task_attempts(id) ON DELETE SET NULL,
            entry_type TEXT NOT NULL,
            actor_type TEXT NOT NULL,
            actor_id TEXT NOT NULL,
            source_channel TEXT,
            body TEXT NOT NULL,
            payload TEXT,
            created_at TEXT NOT NULL DEFAULT (datetime('now'))
        )",
    )
    .execute(pool)
    .await?;

    sqlx::query(
        "CREATE TABLE IF NOT EXISTS task_handoffs (
            id TEXT PRIMARY KEY,
            task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
            attempt_id TEXT NOT NULL REFERENCES task_attempts(id) ON DELETE CASCADE,
            summary TEXT NOT NULL,
            artifacts_json TEXT NOT NULL DEFAULT '[]',
            verification_json TEXT NOT NULL DEFAULT '[]',
            remaining_risk TEXT,
            next_step TEXT,
            created_at TEXT NOT NULL DEFAULT (datetime('now'))
        )",
    )
    .execute(pool)
    .await?;

    sqlx::query(
        "CREATE TABLE IF NOT EXISTS task_workspaces (
            id TEXT PRIMARY KEY,
            task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
            attempt_id TEXT NOT NULL REFERENCES task_attempts(id) ON DELETE CASCADE,
            backend_id TEXT NOT NULL,
            policy TEXT NOT NULL,
            root_path TEXT NOT NULL,
            branch_name TEXT,
            base_ref TEXT,
            head_ref TEXT,
            status TEXT NOT NULL,
            created_at TEXT NOT NULL DEFAULT (datetime('now')),
            released_at TEXT
        )",
    )
    .execute(pool)
    .await?;

    sqlx::query(
        "CREATE TABLE IF NOT EXISTS work_channel_links (
            goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
            channel_session_id TEXT NOT NULL,
            thread_ref TEXT,
            created_at TEXT NOT NULL DEFAULT (datetime('now')),
            updated_at TEXT NOT NULL DEFAULT (datetime('now')),
            PRIMARY KEY (goal_id, channel_session_id)
        )",
    )
    .execute(pool)
    .await?;

    // Episode analysis historically inserted inferred goal mentions without a
    // domain, so the orchestration default made them executable work. Reclassify
    // only rows that still have no task or schedule evidence; preserve them as
    // inert personal observations for audit and possible later confirmation.
    sqlx::query(
        "UPDATE goals
         SET domain = 'personal',
             status = CASE
                 WHEN status IN ('active', 'pending', 'pending_confirmation')
                 THEN 'observed'
                 ELSE status
             END,
             updated_at = datetime('now')
         WHERE domain = 'orchestration'
           AND source_episode_id IS NOT NULL
           AND NOT EXISTS (SELECT 1 FROM tasks t WHERE t.goal_id = goals.id)
           AND NOT EXISTS (SELECT 1 FROM goal_schedules s WHERE s.goal_id = goals.id)",
    )
    .execute(pool)
    .await?;

    sqlx::query(
        "DELETE FROM work_channel_links
         WHERE goal_id IN (
             SELECT id FROM goals
             WHERE domain = 'personal' AND source_episode_id IS NOT NULL
         )",
    )
    .execute(pool)
    .await?;

    sqlx::query(
        "UPDATE goal_runs
         SET status = 'cancelled',
             outcome_summary = COALESCE(
                 outcome_summary,
                 'Reclassified as a non-executable personal observation'
             ),
             completed_at = COALESCE(completed_at, datetime('now')),
             updated_at = datetime('now')
         WHERE status IN ('pending', 'running', 'blocked')
           AND goal_id IN (
               SELECT g.id FROM goals g
               WHERE g.domain = 'personal'
                 AND g.source_episode_id IS NOT NULL
                 AND NOT EXISTS (SELECT 1 FROM tasks t WHERE t.goal_id = g.id)
           )",
    )
    .execute(pool)
    .await?;

    // Once ([`WORK_BACKFILLS_DONE_VERSION`]): run on every start it gave each
    // goal made since a task-less "legacy" run (4,304 of 4,365 in one owner's
    // database on 2026-11-21).
    if !work_backfills_done(pool).await? {
        // Existing goal/task data gets one explicit legacy run. New scheduled
        // firings create a fresh run before any task is inserted.
        sqlx::query(
            "INSERT OR IGNORE INTO goal_runs
                (id, project_id, goal_id, trigger_type, status, outcome_summary,
                 started_at, completed_at, created_at, updated_at)
             SELECT
                'run-legacy-' || g.id,
                COALESCE(NULLIF(g.project_id, ''), 'default'),
                g.id,
                'legacy',
                CASE
                    WHEN g.status IN ('completed', 'failed', 'cancelled') THEN g.status
                    WHEN EXISTS (
                        SELECT 1 FROM tasks t
                        WHERE t.goal_id = g.id AND t.status = 'blocked'
                    ) THEN 'blocked'
                    ELSE 'running'
                END,
                NULL,
                g.created_at,
                CASE WHEN g.status IN ('completed', 'failed', 'cancelled')
                     THEN COALESCE(g.completed_at, g.updated_at) ELSE NULL END,
                g.created_at,
                g.updated_at
             FROM goals g
             WHERE g.domain = 'orchestration'",
        )
        .execute(pool)
        .await?;
    }
    sqlx::query(
        "UPDATE tasks
         SET goal_run_id = COALESCE(
             goal_run_id,
             (SELECT gr.id FROM goal_runs gr
              WHERE gr.goal_id = tasks.goal_id
              ORDER BY julianday(gr.started_at) DESC, gr.id DESC LIMIT 1)
         )
         WHERE goal_run_id IS NULL OR goal_run_id = ''",
    )
    .execute(pool)
    .await?;

    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE scheduled_run_state ADD COLUMN goal_run_id TEXT",
    )
    .await?;
    sqlx::query(
        "UPDATE scheduled_run_state
         SET goal_run_id = COALESCE(
             goal_run_id,
             (SELECT t.goal_run_id FROM tasks t
              WHERE t.id = scheduled_run_state.root_task_id)
         )",
    )
    .execute(pool)
    .await?;

    // The first run-isolation migration grouped all pre-existing recurring
    // history into one legacy run. Once no live task or scheduled-run state
    // references that run, close it so current board views do not present old
    // outcomes as an active recurring cycle. Tasks and journals remain intact.
    sqlx::query(
        "UPDATE goal_runs
         SET status = CASE
                 WHEN EXISTS (
                     SELECT 1 FROM tasks t
                     WHERE t.goal_run_id = goal_runs.id
                       AND t.status IN ('failed', 'blocked', 'interrupted')
                 ) THEN 'failed'
                 ELSE 'completed'
             END,
             outcome_summary = COALESCE(
                 outcome_summary,
                 'Archived legacy history after recurring-run isolation'
             ),
             completed_at = COALESCE(completed_at, datetime('now')),
             updated_at = datetime('now')
         WHERE trigger_type = 'legacy'
           AND status IN ('pending', 'running', 'blocked')
           AND EXISTS (
               SELECT 1 FROM goals g
               WHERE g.id = goal_runs.goal_id
                 AND g.goal_type = 'continuous'
           )
           AND NOT EXISTS (
               SELECT 1 FROM tasks t
               WHERE t.goal_run_id = goal_runs.id
                 AND t.status IN ('pending', 'claimed', 'running')
           )
           AND NOT EXISTS (
               SELECT 1 FROM scheduled_run_state s
               WHERE s.goal_run_id = goal_runs.id
           )",
    )
    .execute(pool)
    .await?;

    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE notification_queue ADD COLUMN task_id TEXT",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE notification_queue ADD COLUMN action_token TEXT",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE notification_queue ADD COLUMN untrusted INTEGER NOT NULL DEFAULT 0",
    )
    .await?;

    let _ = sqlx::query(
        "CREATE INDEX IF NOT EXISTS idx_goals_project_status
         ON goals(project_id, status)",
    )
    .execute(pool)
    .await;
    let _ = sqlx::query(
        "CREATE INDEX IF NOT EXISTS idx_goal_runs_goal_started
         ON goal_runs(goal_id, started_at DESC)",
    )
    .execute(pool)
    .await;
    let _ = sqlx::query("DROP INDEX IF EXISTS idx_goal_runs_one_open")
        .execute(pool)
        .await;
    let _ = sqlx::query(
        "CREATE INDEX IF NOT EXISTS idx_goal_runs_open
         ON goal_runs(goal_id, status)
         WHERE status IN ('pending', 'running', 'blocked')",
    )
    .execute(pool)
    .await;
    let _ = sqlx::query(
        "CREATE INDEX IF NOT EXISTS idx_tasks_goal_run_status
         ON tasks(goal_run_id, status)",
    )
    .execute(pool)
    .await;
    let _ = sqlx::query(
        "CREATE UNIQUE INDEX IF NOT EXISTS idx_task_attempts_one_active
         ON task_attempts(task_id)
         WHERE status IN ('claimed', 'running')",
    )
    .execute(pool)
    .await;
    let _ = sqlx::query(
        "CREATE INDEX IF NOT EXISTS idx_task_attempts_lease
         ON task_attempts(status, lease_expires_at)",
    )
    .execute(pool)
    .await;
    let _ = sqlx::query(
        "CREATE INDEX IF NOT EXISTS idx_task_journal_task_created
         ON task_journal(task_id, created_at)",
    )
    .execute(pool)
    .await;
    let _ = sqlx::query(
        "CREATE INDEX IF NOT EXISTS idx_task_handoffs_task_created
         ON task_handoffs(task_id, created_at)",
    )
    .execute(pool)
    .await;
    let _ = sqlx::query(
        "CREATE INDEX IF NOT EXISTS idx_task_workspaces_task
         ON task_workspaces(task_id, created_at)",
    )
    .execute(pool)
    .await;

    // Indexes (idempotent).
    let _ = sqlx::query("CREATE INDEX IF NOT EXISTS idx_goals_status ON goals(status)")
        .execute(pool)
        .await;
    let _ = sqlx::query("CREATE INDEX IF NOT EXISTS idx_goals_session ON goals(session_id)")
        .execute(pool)
        .await;
    let _ =
        sqlx::query("CREATE INDEX IF NOT EXISTS idx_goals_domain_status ON goals(domain, status)")
            .execute(pool)
            .await;
    let _ = sqlx::query("CREATE INDEX IF NOT EXISTS idx_tasks_goal ON tasks(goal_id)")
        .execute(pool)
        .await;
    let _ = sqlx::query("CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks(status)")
        .execute(pool)
        .await;
    let _ =
        sqlx::query("CREATE INDEX IF NOT EXISTS idx_task_activity_task ON task_activity(task_id)")
            .execute(pool)
            .await;
    let _ = sqlx::query(
        "CREATE INDEX IF NOT EXISTS idx_task_activity_created_at ON task_activity(created_at)",
    )
    .execute(pool)
    .await;
    // Self-correcting-resilience Component A: the inactivity watchdog does a
    // lexical MAX(created_at) per task, so all rows must share one sortable UTC
    // format. Normalize any legacy RFC3339 rows ('...T...Z') to SQLite datetime,
    // and add a composite index to serve the correlated per-task MAX.
    let _ = sqlx::query(
        "UPDATE task_activity SET created_at = datetime(created_at) WHERE created_at LIKE '%T%'",
    )
    .execute(pool)
    .await;
    let _ = sqlx::query(
        "CREATE INDEX IF NOT EXISTS idx_task_activity_task_created_at \
         ON task_activity(task_id, created_at)",
    )
    .execute(pool)
    .await;
    let _ = sqlx::query(
        "CREATE INDEX IF NOT EXISTS idx_goal_schedules_goal ON goal_schedules(goal_id)",
    )
    .execute(pool)
    .await;
    let _ = sqlx::query(
        "CREATE INDEX IF NOT EXISTS idx_goal_schedules_next_run
         ON goal_schedules(next_run_at) WHERE is_paused = 0",
    )
    .execute(pool)
    .await;
    let _ = sqlx::query(
        "CREATE INDEX IF NOT EXISTS idx_scheduled_run_state_root_task
         ON scheduled_run_state(root_task_id)",
    )
    .execute(pool)
    .await;

    // Notification queue — queued when channel unavailable, delivered on reconnect.
    // Retention: status_update expires after 24h, critical persists indefinitely.
    sqlx::query(
        "CREATE TABLE IF NOT EXISTS notification_queue (
            id TEXT PRIMARY KEY,
            goal_id TEXT NOT NULL,
            session_id TEXT NOT NULL,
            notification_type TEXT NOT NULL,
            priority TEXT NOT NULL DEFAULT 'status_update',
            message TEXT NOT NULL,
            created_at TEXT NOT NULL DEFAULT (datetime('now')),
            delivered_at TEXT,
            attempts INTEGER NOT NULL DEFAULT 0,
            expires_at TEXT
        )",
    )
    .execute(pool)
    .await?;

    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE notification_queue ADD COLUMN task_id TEXT",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE notification_queue ADD COLUMN action_token TEXT",
    )
    .await?;
    aidaemon_tools::sqlite_schema::add_column_if_missing(
        pool,
        "ALTER TABLE notification_queue ADD COLUMN untrusted INTEGER NOT NULL DEFAULT 0",
    )
    .await?;

    sqlx::query(
        "CREATE INDEX IF NOT EXISTS idx_notification_queue_pending
         ON notification_queue(delivered_at, priority, created_at)
         WHERE delivered_at IS NULL",
    )
    .execute(pool)
    .await?;

    Ok(())
}

/// Repairs and tables that have always run after the host's own.
pub async fn migrate_work_tail(pool: &SqlitePool) -> anyhow::Result<()> {
    // Normalize legacy optional task fields. Empty strings caused completed
    // tasks to be misclassified as failures by callers expecting NULL.
    sqlx::query(
        "UPDATE tasks
         SET result = NULLIF(TRIM(result), ''),
             error = NULLIF(TRIM(error), ''),
             blocker = NULLIF(TRIM(blocker), '')
         WHERE (result IS NOT NULL AND TRIM(result) = '')
            OR (error IS NOT NULL AND TRIM(error) = '')
            OR (blocker IS NOT NULL AND TRIM(blocker) = '')",
    )
    .execute(pool)
    .await?;

    // Repair the historical race where an executor durably blocked an attempt,
    // then a stale coordinator overwrote the task row as completed without an
    // unblock or a newer attempt. The latest fenced attempt is authoritative.
    sqlx::query(
        "UPDATE tasks
         SET status = 'blocked',
             blocker = COALESCE(blocker, 'Latest execution attempt is blocked.'),
             completed_at = COALESCE(
                 (SELECT a.completed_at FROM task_attempts a
                  WHERE a.task_id = tasks.id
                  ORDER BY julianday(a.started_at) DESC, a.id DESC LIMIT 1),
                 completed_at
             ),
             updated_at = datetime('now'), version = version + 1
         WHERE status = 'completed'
           AND (
               SELECT a.status FROM task_attempts a
               WHERE a.task_id = tasks.id
               ORDER BY julianday(a.started_at) DESC, a.id DESC LIMIT 1
           ) = 'blocked'",
    )
    .execute(pool)
    .await?;

    // Task-linked escalation notifications are actionable only while the task
    // remains blocked. Close obsolete critical rows so they cannot surface
    // hours later after an unblock, retry, cancellation, or completion.
    sqlx::query(
        "UPDATE notification_queue
         SET delivered_at = datetime('now')
         WHERE delivered_at IS NULL
           AND notification_type = 'escalation'
           AND task_id IS NOT NULL
           AND NOT EXISTS (
               SELECT 1 FROM tasks t
               WHERE t.id = notification_queue.task_id AND t.status = 'blocked'
           )",
    )
    .execute(pool)
    .await?;

    // Migration: scheduled continuous goals were historically created with incorrect
    // 5K/20K budgets. Bump them to the current continuous defaults (100K/500K).
    // Safe + idempotent.
    let _ = sqlx::query(
        "UPDATE goals
         SET budget_per_check = 100000,
             budget_daily = 500000
         WHERE domain = 'orchestration'
           AND goal_type = 'continuous'
           AND budget_per_check = 5000
           AND budget_daily = 20000
           AND EXISTS (SELECT 1 FROM goal_schedules s WHERE s.goal_id = goals.id)",
    )
    .execute(pool)
    .await;

    // Migration: raise previously standard scheduled continuous defaults
    // (50K/200K) to the newer defaults (100K/500K). This only touches goals
    // still at the exact historical defaults, so explicit user-set budgets are
    // preserved.
    let _ = sqlx::query(
        "UPDATE goals
         SET budget_per_check = 100000,
             budget_daily = 500000
         WHERE domain = 'orchestration'
           AND goal_type = 'continuous'
           AND budget_per_check = 50000
           AND budget_daily = 200000
           AND EXISTS (SELECT 1 FROM goal_schedules s WHERE s.goal_id = goals.id)",
    )
    .execute(pool)
    .await;

    // Cleanup: schedules attached to terminal goals are dead rows. They can exist
    // after migrations from legacy schemas or older bulk-cancel implementations.
    // Safe + idempotent.
    let _ = sqlx::query(
        "DELETE FROM goal_schedules
         WHERE goal_id IN (
            SELECT id FROM goals WHERE status IN ('cancelled', 'completed')
         )",
    )
    .execute(pool)
    .await;

    let _ = sqlx::query(
        "DELETE FROM scheduled_run_state
         WHERE goal_id IN (
            SELECT id FROM goals WHERE status IN ('cancelled', 'completed', 'failed')
         )",
    )
    .execute(pool)
    .await;

    // Token arithmetic is an internal runaway guard for mandates. Migrate
    // historical low defaults to the automatic balanced policy and derive a
    // daily envelope that can fund every cadence slot. This only raises
    // capacity; explicit efficient/thorough choices are persisted separately.
    let _ = sqlx::query(
        "UPDATE goals
         SET budget_per_check = MAX(COALESCE(budget_per_check, 0), 250000),
             budget_daily = MAX(
                 COALESCE(budget_daily, 0),
                 2000000,
                 ((86400 + m.default_review_secs - 1) / m.default_review_secs)
                    * MAX(COALESCE(budget_per_check, 0), 250000)
             )
         FROM mandates AS m
         WHERE m.goal_id = goals.id
           AND m.review_effort = 'balanced'
           AND (
               COALESCE(goals.budget_per_check, 0) < 250000
               OR COALESCE(goals.budget_daily, 0) < MAX(
                   2000000,
                   ((86400 + m.default_review_secs - 1) / m.default_review_secs)
                       * MAX(COALESCE(goals.budget_per_check, 0), 250000)
               )
           )
           AND goals.status IN ('active', 'pending', 'pending_confirmation')",
    )
    .execute(pool)
    .await;

    // Bound only obviously runaway historical values. Managed thorough mode
    // legitimately exceeds the old two-million-token ceiling at fast cadences.
    let _ = sqlx::query(
        "UPDATE goals
         SET budget_daily = 50000000
         WHERE budget_daily > 50000000
           AND status IN ('active', 'pending', 'pending_confirmation')",
    )
    .execute(pool)
    .await;

    // Background sub-agents still running. In-memory work does not survive a
    // restart; this is how the owner hears that it was lost.
    sqlx::query(
        "CREATE TABLE IF NOT EXISTS background_spawns (
            id TEXT PRIMARY KEY,
            session_id TEXT NOT NULL,
            mission TEXT NOT NULL,
            started_at TEXT NOT NULL
        )",
    )
    .execute(pool)
    .await?;

    // Normalize task dependency edges. `tasks.depends_on` remains as a JSON
    // compatibility projection, while schedulers and claims use this table as
    // their authoritative graph. The join skips invalid legacy references so
    // migration cannot manufacture an edge to a nonexistent task.
    sqlx::query(
        "CREATE TABLE IF NOT EXISTS task_dependencies (
            task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
            depends_on_task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
            created_at TEXT NOT NULL DEFAULT (datetime('now')),
            PRIMARY KEY(task_id, depends_on_task_id),
            CHECK(task_id <> depends_on_task_id)
        )",
    )
    .execute(pool)
    .await?;
    sqlx::query(
        "CREATE INDEX IF NOT EXISTS idx_task_dependencies_prerequisite
         ON task_dependencies(depends_on_task_id, task_id)",
    )
    .execute(pool)
    .await?;
    // The table from the tasks' own lists, once ([`WORK_BACKFILLS_DONE_VERSION`]):
    // every task write keeps it (`replace_task_dependencies`).
    if !work_backfills_done(pool).await? {
        sqlx::query(
            "INSERT OR IGNORE INTO task_dependencies(task_id, depends_on_task_id)
             SELECT t.id, CAST(dep.value AS TEXT)
             FROM tasks t
             JOIN json_each(
                CASE
                    WHEN json_valid(COALESCE(t.depends_on, '[]'))
                     AND json_type(COALESCE(t.depends_on, '[]')) = 'array'
                    THEN COALESCE(t.depends_on, '[]')
                    ELSE '[]'
                END
             ) dep
             JOIN tasks prerequisite ON prerequisite.id = CAST(dep.value AS TEXT)
             WHERE CAST(dep.value AS TEXT) <> t.id",
        )
        .execute(pool)
        .await?;
    }
    sqlx::query(
        "CREATE TRIGGER IF NOT EXISTS trg_task_dependencies_no_cycle
         BEFORE INSERT ON task_dependencies
         WHEN EXISTS (
            WITH RECURSIVE prerequisites(id) AS (
                SELECT NEW.depends_on_task_id
                UNION
                SELECT edge.depends_on_task_id
                FROM task_dependencies edge
                JOIN prerequisites prior ON edge.task_id = prior.id
            )
            SELECT 1 FROM prerequisites WHERE id = NEW.task_id
         )
         BEGIN
            SELECT RAISE(ABORT, 'task dependency cycle');
         END",
    )
    .execute(pool)
    .await?;

    Ok(())
}