marver 0.0.25

A TUI workspace for AI agent sessions: tmux orchestration, git worktree management, and repo control in one place.
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
//! SQLite-backed store. Owned by the daemon; the TUI opens the same file.
//!
//! WAL mode, `busy_timeout` for contention. Every write takes the time as an
//! argument. [`Store::transition`] enforces the lifecycle in
//! [`crate::domain::TaskState`], so nothing else has to.

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use chrono::{DateTime, Utc};
use rusqlite::{Connection, OptionalExtension, Row, params};
use serde_json::Value;

use crate::domain::{
    BlockedKind, Event, Repo, Task, TaskRepo, TaskState, TaskUsage, Todo, TodoScope,
};

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error(transparent)]
    Sqlite(#[from] rusqlite::Error),
    #[error(transparent)]
    Json(#[from] serde_json::Error),
    #[error("io error at {path}: {source}")]
    Io {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },
    #[error("task {0} not found")]
    TaskNotFound(i64),
    #[error("repo {0} not found")]
    RepoNotFound(i64),
    #[error("task {task_id} does not target repo {repo_id}")]
    RepoNotSelected { task_id: i64, repo_id: i64 },
    #[error("illegal transition: {from} -> {to}")]
    IllegalTransition { from: TaskState, to: TaskState },
    #[error("transition to blocked requires a BlockedKind")]
    MissingBlockedKind,
    #[error("transition to failed requires a reason")]
    MissingFailureReason,
    #[error("transition detail does not match a move to {0}")]
    MismatchedDetail(TaskState),
    #[error("a {0} task is still going, so it cannot be archived")]
    NotArchivable(TaskState),
    #[error("unreadable {field} in database: {value:?}")]
    Corrupt { field: &'static str, value: String },
    #[error("migration left {0} row(s) referencing something that is gone; rolled back")]
    MigrationBrokeReferences(i64),
    #[error("todo {0} not found")]
    TodoNotFound(i64),
    #[error("a todo cannot be empty")]
    EmptyTodo,
}

pub type Result<T> = std::result::Result<T, Error>;

/// Why a task is blocked, supplied when transitioning into
/// [`TaskState::Blocked`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BlockedInfo {
    pub kind: BlockedKind,
    pub reason: Option<String>,
}

impl BlockedInfo {
    pub fn new(kind: BlockedKind) -> Self {
        Self { kind, reason: None }
    }

    pub fn with_reason(kind: BlockedKind, reason: impl Into<String>) -> Self {
        Self {
            kind,
            reason: Some(reason.into()),
        }
    }
}

/// Extra information a state change carries.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum Transition {
    /// Carries nothing. Correct for every state but `blocked` and `failed`.
    #[default]
    Plain,
    Blocked(BlockedInfo),
    Failed(String),
}

impl Transition {
    /// The state this detail is valid for, if it is only valid for one.
    fn required_state(&self) -> Option<TaskState> {
        match self {
            Self::Plain => None,
            Self::Blocked(_) => Some(TaskState::Blocked),
            Self::Failed(_) => Some(TaskState::Failed),
        }
    }

    fn blocked(&self) -> Option<&BlockedInfo> {
        match self {
            Self::Blocked(info) => Some(info),
            _ => None,
        }
    }

    fn failure(&self) -> Option<&str> {
        match self {
            Self::Failed(reason) => Some(reason),
            _ => None,
        }
    }
}

/// Applied in order; index + 1 becomes `PRAGMA user_version`.
const MIGRATIONS: &[&str] = &[
    include_str!("store/0001_initial.sql"),
    include_str!("store/0002_paused_and_todos.sql"),
    include_str!("store/0003_usage.sql"),
    include_str!("store/0004_archive.sql"),
];

pub struct Store {
    conn: Connection,
}

impl Store {
    /// Open (creating if absent) the database at `path`, applying migrations.
    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref();
        if let Some(parent) = path.parent()
            && !parent.as_os_str().is_empty()
        {
            std::fs::create_dir_all(parent).map_err(|source| Error::Io {
                path: parent.to_path_buf(),
                source,
            })?;
        }
        Self::from_connection(Connection::open(path)?)
    }

    /// An ephemeral database. Tests only.
    pub fn open_in_memory() -> Result<Self> {
        Self::from_connection(Connection::open_in_memory()?)
    }

    fn from_connection(mut conn: Connection) -> Result<Self> {
        // WAL lets readers proceed during writes; it is a no-op in memory.
        conn.pragma_update(None, "journal_mode", "WAL")?;
        conn.pragma_update(None, "foreign_keys", "ON")?;
        conn.pragma_update(None, "busy_timeout", 5_000)?;
        migrate(&mut conn)?;
        Ok(Self { conn })
    }

    /// Current schema version. Equal to `MIGRATIONS.len()` after a successful
    /// open.
    pub fn schema_version(&self) -> Result<i64> {
        Ok(self
            .conn
            .query_row("PRAGMA user_version", [], |row| row.get(0))?)
    }

    // ---- repos ---------------------------------------------------------

    /// Record a repo found by a scan. Idempotent on `path`: an existing row
    /// has its `last_seen_at` and `name` refreshed and keeps its `ignored`
    /// flag.
    pub fn upsert_repo(&self, path: &Path, name: &str, now: DateTime<Utc>) -> Result<Repo> {
        let path_str = path_to_string(path);
        self.conn.execute(
            "INSERT INTO repos (path, name, ignored, discovered_at, last_seen_at)
             VALUES (?1, ?2, 0, ?3, ?3)
             ON CONFLICT(path) DO UPDATE SET name = ?2, last_seen_at = ?3",
            params![path_str, name, now.timestamp()],
        )?;
        self.repo_by_path(path)
    }

    pub fn repo_by_path(&self, path: &Path) -> Result<Repo> {
        self.conn
            .query_row(
                "SELECT id, path, name, ignored, discovered_at, last_seen_at
                 FROM repos WHERE path = ?1",
                params![path_to_string(path)],
                row_to_repo,
            )
            .optional()?
            .ok_or_else(|| Error::Corrupt {
                field: "repos.path",
                value: path_to_string(path),
            })
    }

    pub fn get_repo(&self, id: i64) -> Result<Repo> {
        self.conn
            .query_row(
                "SELECT id, path, name, ignored, discovered_at, last_seen_at
                 FROM repos WHERE id = ?1",
                params![id],
                row_to_repo,
            )
            .optional()?
            .ok_or(Error::RepoNotFound(id))
    }

    pub fn list_repos(&self, include_ignored: bool) -> Result<Vec<Repo>> {
        let mut stmt = self.conn.prepare(
            "SELECT id, path, name, ignored, discovered_at, last_seen_at
             FROM repos
             WHERE ?1 OR ignored = 0
             ORDER BY name, path",
        )?;
        let rows = stmt.query_map(params![include_ignored], row_to_repo)?;
        rows.collect::<rusqlite::Result<Vec<_>>>()
            .map_err(Into::into)
    }

    /// Repos not touched by a scan at or after `cutoff`.
    pub fn list_repos_last_seen_before(&self, cutoff: DateTime<Utc>) -> Result<Vec<Repo>> {
        let mut stmt = self.conn.prepare(
            "SELECT id, path, name, ignored, discovered_at, last_seen_at
             FROM repos WHERE last_seen_at < ?1 ORDER BY path",
        )?;
        let rows = stmt.query_map(params![cutoff.timestamp()], row_to_repo)?;
        rows.collect::<rusqlite::Result<Vec<_>>>()
            .map_err(Into::into)
    }

    pub fn set_repo_ignored(&self, id: i64, ignored: bool) -> Result<()> {
        let changed = self.conn.execute(
            "UPDATE repos SET ignored = ?2 WHERE id = ?1",
            params![id, ignored],
        )?;
        if changed == 0 {
            return Err(Error::RepoNotFound(id));
        }
        Ok(())
    }

    // ---- tasks ---------------------------------------------------------

    /// Create a task in [`TaskState::Queued`] and log its creation.
    pub fn create_task(
        &mut self,
        title: &str,
        prompt: &str,
        workspace_root: &Path,
        repo_ids: &[i64],
        now: DateTime<Utc>,
    ) -> Result<Task> {
        let tx = self.conn.transaction()?;
        tx.execute(
            "INSERT INTO tasks (title, prompt, state, workspace_dir, created_at, updated_at)
             VALUES (?1, ?2, ?3, '', ?4, ?4)",
            params![title, prompt, TaskState::Queued.as_str(), now.timestamp(),],
        )?;
        let id = tx.last_insert_rowid();
        tx.execute(
            "UPDATE tasks SET workspace_dir = ?2 WHERE id = ?1",
            params![id, path_to_string(&workspace_root.join(id.to_string()))],
        )?;
        for repo_id in repo_ids {
            tx.execute(
                "INSERT INTO task_repos (task_id, repo_id) VALUES (?1, ?2)",
                params![id, repo_id],
            )?;
        }
        insert_event(
            &tx,
            Some(id),
            "task.created",
            &serde_json::json!({ "title": title }),
            now,
        )?;
        tx.commit()?;
        self.get_task(id)
    }

    pub fn get_task(&self, id: i64) -> Result<Task> {
        self.conn
            .query_row(TASK_SELECT, params![id], row_to_task)
            .optional()?
            .transpose()?
            .ok_or(Error::TaskNotFound(id))
    }

    pub fn list_tasks(&self) -> Result<Vec<Task>> {
        let mut stmt = self.conn.prepare(concat!(
            "SELECT ",
            task_columns!(),
            " FROM tasks ORDER BY id"
        ))?;
        let rows = stmt.query_map([], row_to_task)?;
        collect_tasks(rows)
    }

    pub fn list_tasks_in_state(&self, state: TaskState) -> Result<Vec<Task>> {
        let mut stmt = self.conn.prepare(concat!(
            "SELECT ",
            task_columns!(),
            " FROM tasks WHERE state = ?1 ORDER BY id"
        ))?;
        let rows = stmt.query_map(params![state.as_str()], row_to_task)?;
        collect_tasks(rows)
    }

    pub fn set_session_name(&self, id: i64, session_name: &str, now: DateTime<Utc>) -> Result<()> {
        let changed = self.conn.execute(
            "UPDATE tasks SET session_name = ?2, updated_at = ?3 WHERE id = ?1",
            params![id, session_name, now.timestamp()],
        )?;
        if changed == 0 {
            return Err(Error::TaskNotFound(id));
        }
        Ok(())
    }

    /// Forget a task's tmux session, once there is no longer one to point at.
    pub fn clear_session_name(&self, id: i64, now: DateTime<Utc>) -> Result<()> {
        let changed = self.conn.execute(
            "UPDATE tasks SET session_name = NULL, updated_at = ?2 WHERE id = ?1",
            params![id, now.timestamp()],
        )?;
        if changed == 0 {
            return Err(Error::TaskNotFound(id));
        }
        Ok(())
    }

    /// Put a finished task out of the way, or bring it back.
    pub fn set_task_archived(&self, id: i64, archived: bool, now: DateTime<Utc>) -> Result<Task> {
        let task = self.get_task(id)?;
        if archived && !task.state.is_terminal() {
            return Err(Error::NotArchivable(task.state));
        }
        if archived == task.is_archived() {
            return Ok(task);
        }
        let at = archived.then(|| now.timestamp());
        self.conn.execute(
            "UPDATE tasks SET archived_at = ?2, updated_at = ?3 WHERE id = ?1",
            params![id, at, now.timestamp()],
        )?;
        self.get_task(id)
    }

    /// Move a task to `next`, rejecting anything the lifecycle disallows.
    pub fn transition(
        &mut self,
        id: i64,
        next: TaskState,
        detail: Transition,
        now: DateTime<Utc>,
    ) -> Result<Task> {
        self.move_task(id, None, next, detail, now)
    }

    /// Move a task to `next`, but only if it is still in `expected`.
    pub fn transition_from(
        &mut self,
        id: i64,
        expected: TaskState,
        next: TaskState,
        detail: Transition,
        now: DateTime<Utc>,
    ) -> Result<Task> {
        self.move_task(id, Some(expected), next, detail, now)
    }

    fn move_task(
        &mut self,
        id: i64,
        expected: Option<TaskState>,
        next: TaskState,
        detail: Transition,
        now: DateTime<Utc>,
    ) -> Result<Task> {
        let current = self.get_task(id)?;
        if let Some(expected) = expected
            && current.state != expected
        {
            return Err(Error::IllegalTransition {
                from: current.state,
                to: next,
            });
        }
        if !current.state.can_transition_to(next) {
            return Err(Error::IllegalTransition {
                from: current.state,
                to: next,
            });
        }
        match detail.required_state() {
            Some(required) if required != next => return Err(Error::MismatchedDetail(next)),
            None if next == TaskState::Blocked => return Err(Error::MissingBlockedKind),
            None if next == TaskState::Failed => return Err(Error::MissingFailureReason),
            _ => {}
        }

        let tx = self.conn.transaction()?;
        // Compare-and-swap on the state we checked.
        let changed = tx.execute(
            "UPDATE tasks
             SET state = ?2, blocked_kind = ?3, blocked_reason = ?4,
                 failure_reason = ?5, updated_at = ?6
             WHERE id = ?1 AND state = ?7",
            params![
                id,
                next.as_str(),
                detail.blocked().map(|b| b.kind.as_str()),
                detail.blocked().and_then(|b| b.reason.as_deref()),
                detail.failure(),
                now.timestamp(),
                current.state.as_str(),
            ],
        )?;
        if changed == 0 {
            // Lost the race.
            drop(tx);
            let actual = self.get_task(id)?.state;
            return Err(Error::IllegalTransition {
                from: actual,
                to: next,
            });
        }
        insert_event(
            &tx,
            Some(id),
            "task.transition",
            &serde_json::json!({
                "from": current.state,
                "to": next,
                "blocked_kind": detail.blocked().map(|b| b.kind),
                "blocked_reason": detail.blocked().and_then(|b| b.reason.clone()),
                "failure_reason": detail.failure(),
            }),
            now,
        )?;
        tx.commit()?;
        self.get_task(id)
    }

    // ---- worktrees -----------------------------------------------------

    /// Add a repo to a task's selection after creation.
    pub fn select_repo(&self, task_id: i64, repo_id: i64) -> Result<()> {
        self.conn.execute(
            "INSERT INTO task_repos (task_id, repo_id) VALUES (?1, ?2)",
            params![task_id, repo_id],
        )?;
        Ok(())
    }

    /// Record the worktree provisioned for a (task, repo) pairing.
    pub fn record_worktree(
        &self,
        task_id: i64,
        repo_id: i64,
        worktree_path: &Path,
        branch: &str,
        base_ref: &str,
    ) -> Result<TaskRepo> {
        let changed = self.conn.execute(
            "UPDATE task_repos
             SET worktree_path = ?3, branch = ?4, base_ref = ?5
             WHERE task_id = ?1 AND repo_id = ?2",
            params![
                task_id,
                repo_id,
                path_to_string(worktree_path),
                branch,
                base_ref
            ],
        )?;
        if changed == 0 {
            return Err(Error::RepoNotSelected { task_id, repo_id });
        }
        Ok(TaskRepo {
            task_id,
            repo_id,
            worktree_path: Some(worktree_path.to_path_buf()),
            branch: Some(branch.to_string()),
            base_ref: Some(base_ref.to_string()),
        })
    }

    /// Clear the worktree details for a task, leaving the selection intact.
    pub fn clear_worktrees(&self, task_id: i64) -> Result<()> {
        self.conn.execute(
            "UPDATE task_repos
             SET worktree_path = NULL, branch = NULL, base_ref = NULL
             WHERE task_id = ?1",
            params![task_id],
        )?;
        Ok(())
    }

    /// Repo names for every task, keyed by task id.
    pub fn repo_names_by_task(&self) -> Result<HashMap<i64, Vec<String>>> {
        let mut statement = self.conn.prepare(
            "SELECT task_repos.task_id, repos.name
             FROM task_repos
             JOIN repos ON repos.id = task_repos.repo_id
             ORDER BY task_repos.task_id, task_repos.repo_id",
        )?;
        let rows = statement.query_map([], |row| {
            Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?))
        })?;

        let mut names: HashMap<i64, Vec<String>> = HashMap::new();
        for row in rows {
            let (task_id, name) = row?;
            names.entry(task_id).or_default().push(name);
        }
        Ok(names)
    }

    pub fn list_task_repos(&self, task_id: i64) -> Result<Vec<TaskRepo>> {
        let mut stmt = self.conn.prepare(
            "SELECT task_id, repo_id, worktree_path, branch, base_ref
             FROM task_repos WHERE task_id = ?1 ORDER BY repo_id",
        )?;
        let rows = stmt.query_map(params![task_id], |row| {
            Ok(TaskRepo {
                task_id: row.get(0)?,
                repo_id: row.get(1)?,
                worktree_path: row.get::<_, Option<String>>(2)?.map(PathBuf::from),
                branch: row.get(3)?,
                base_ref: row.get(4)?,
            })
        })?;
        rows.collect::<rusqlite::Result<Vec<_>>>()
            .map_err(Into::into)
    }

    // ---- usage ---------------------------------------------------------

    /// Record what a task's agent has spent, if nobody else has since the read.
    ///
    /// Output tokens accumulate, so this is a compare-and-swap on
    /// [`crate::usage::Usage::from`]: the daemon absorbs on every hook and the
    /// task screen refreshes on a timer, and without the condition both add the
    /// same turn. Returns whether the write landed.
    pub fn record_usage(&self, id: i64, usage: &crate::usage::Usage) -> Result<bool> {
        let changed = self.conn.execute(
            "UPDATE tasks
             SET model = coalesce(?2, model),
                 context_tokens = coalesce(?3, context_tokens),
                 output_tokens = coalesce(output_tokens, 0) + ?4,
                 transcript_offset = ?5
             WHERE id = ?1 AND transcript_offset = ?6",
            params![
                id,
                usage.model.as_deref(),
                usage.context_tokens.map(|n| n as i64),
                usage.output_tokens as i64,
                usage.offset as i64,
                usage.from as i64,
            ],
        )?;
        if changed == 0 {
            // Errors if the task is gone; otherwise the other reader won and
            // what this one read is already recorded.
            self.get_task(id)?;
            return Ok(false);
        }
        Ok(true)
    }

    /// Remember where a task's transcript is, so its usage can be refreshed
    /// without waiting for another hook.
    ///
    /// A different path rewinds the offset: what was remembered is about
    /// another file, and seeking a new transcript to an old file's offset skips
    /// however much of it happens to fit.
    pub fn set_transcript_path(&self, id: i64, path: &Path) -> Result<()> {
        self.conn.execute(
            "UPDATE tasks
             SET transcript_offset = CASE
                     WHEN transcript_path IS ?2 THEN transcript_offset ELSE 0
                 END,
                 transcript_path = ?2
             WHERE id = ?1",
            params![id, path_to_string(path)],
        )?;
        Ok(())
    }

    // ---- todos ---------------------------------------------------------

    /// Add a todo to `scope`.
    pub fn add_todo(&self, scope: TodoScope, text: &str, now: DateTime<Utc>) -> Result<Todo> {
        let text = text.trim();
        if text.is_empty() {
            return Err(Error::EmptyTodo);
        }
        self.conn.execute(
            "INSERT INTO todos (task_id, text, done, created_at) VALUES (?1, ?2, 0, ?3)",
            params![scope.task_id(), text, now.timestamp()],
        )?;
        self.get_todo(self.conn.last_insert_rowid())
    }

    pub fn get_todo(&self, id: i64) -> Result<Todo> {
        self.conn
            .query_row(
                "SELECT id, task_id, text, done, created_at FROM todos WHERE id = ?1",
                params![id],
                row_to_todo,
            )
            .optional()?
            .ok_or(Error::TodoNotFound(id))
    }

    /// Every todo in `scope`, oldest first.
    pub fn list_todos(&self, scope: TodoScope) -> Result<Vec<Todo>> {
        let mut stmt = self.conn.prepare(
            "SELECT id, task_id, text, done, created_at
             FROM todos WHERE task_id IS ?1 ORDER BY id",
        )?;
        let rows = stmt.query_map(params![scope.task_id()], row_to_todo)?;
        rows.collect::<rusqlite::Result<Vec<_>>>()
            .map_err(Into::into)
    }

    /// How many todos are outstanding in `scope`. For badges and counts.
    pub fn open_todo_count(&self, scope: TodoScope) -> Result<usize> {
        let count: i64 = self.conn.query_row(
            "SELECT count(*) FROM todos WHERE task_id IS ?1 AND done = 0",
            params![scope.task_id()],
            |row| row.get(0),
        )?;
        Ok(count as usize)
    }

    /// Outstanding todo counts for every task that has one, by task id.
    pub fn open_todo_counts(&self) -> Result<HashMap<i64, usize>> {
        let mut stmt = self.conn.prepare(
            "SELECT task_id, count(*) FROM todos
             WHERE task_id IS NOT NULL AND done = 0 GROUP BY task_id",
        )?;
        let rows = stmt.query_map([], |row| {
            Ok((row.get::<_, i64>(0)?, row.get::<_, i64>(1)? as usize))
        })?;
        rows.collect::<rusqlite::Result<HashMap<_, _>>>()
            .map_err(Into::into)
    }

    pub fn set_todo_done(&self, id: i64, done: bool) -> Result<Todo> {
        let changed = self.conn.execute(
            "UPDATE todos SET done = ?2 WHERE id = ?1",
            params![id, done as i64],
        )?;
        if changed == 0 {
            return Err(Error::TodoNotFound(id));
        }
        self.get_todo(id)
    }

    pub fn delete_todo(&self, id: i64) -> Result<()> {
        let changed = self
            .conn
            .execute("DELETE FROM todos WHERE id = ?1", params![id])?;
        if changed == 0 {
            return Err(Error::TodoNotFound(id));
        }
        Ok(())
    }

    // ---- events --------------------------------------------------------

    pub fn append_event(
        &self,
        task_id: Option<i64>,
        kind: &str,
        payload: &Value,
        now: DateTime<Utc>,
    ) -> Result<i64> {
        insert_event(&self.conn, task_id, kind, payload, now)
    }

    pub fn list_events(&self, task_id: i64) -> Result<Vec<Event>> {
        let mut stmt = self.conn.prepare(
            "SELECT id, task_id, kind, payload, created_at
             FROM events WHERE task_id = ?1 ORDER BY id",
        )?;
        let rows = stmt.query_map(params![task_id], row_to_event)?;
        let mut out = Vec::new();
        for row in rows {
            let (id, task_id, kind, payload, created_at) = row?;
            out.push(Event {
                id,
                task_id,
                kind,
                payload: serde_json::from_str(&payload)?,
                created_at: timestamp(created_at)?,
            });
        }
        Ok(out)
    }
}

/// The column list every task query selects, in the order [`row_to_task`]
/// reads. A macro rather than a const so callers can `concat!` it into a
/// literal.
macro_rules! task_columns {
    () => {
        "id, title, prompt, state, blocked_kind, blocked_reason, failure_reason,
         workspace_dir, session_name, created_at, updated_at,
         model, context_tokens, output_tokens, transcript_offset, transcript_path,
         archived_at"
    };
}
use task_columns;

const TASK_SELECT: &str = concat!("SELECT ", task_columns!(), " FROM tasks WHERE id = ?1");

fn migrate(conn: &mut Connection) -> Result<()> {
    let version: i64 = conn.query_row("PRAGMA user_version", [], |row| row.get(0))?;
    if version as usize >= MIGRATIONS.len() {
        return Ok(());
    }
    // Foreign keys off for the duration, and only for it.
    conn.pragma_update(None, "foreign_keys", "OFF")?;
    let outcome = apply(conn, version as usize);
    // Restored whatever happened, including on the error path: the connection
    // outlives this function and the rest of the process expects enforcement.
    conn.pragma_update(None, "foreign_keys", "ON")?;
    outcome
}

/// Run the outstanding migrations in one transaction.
fn apply(conn: &mut Connection, from: usize) -> Result<()> {
    let tx = conn.transaction()?;
    for (index, migration) in MIGRATIONS.iter().enumerate().skip(from) {
        tx.execute_batch(migration)?;
        // user_version takes no bind parameters.
        tx.execute_batch(&format!("PRAGMA user_version = {}", index + 1))?;
    }
    // Enforcement was off while a table was rebuilt, so nothing was watching
    // the references.
    let violations: i64 =
        tx.query_row("SELECT count(*) FROM pragma_foreign_key_check", [], |row| {
            row.get(0)
        })?;
    if violations > 0 {
        return Err(Error::MigrationBrokeReferences(violations));
    }
    tx.commit()?;
    Ok(())
}

fn insert_event(
    conn: &Connection,
    task_id: Option<i64>,
    kind: &str,
    payload: &Value,
    now: DateTime<Utc>,
) -> Result<i64> {
    conn.execute(
        "INSERT INTO events (task_id, kind, payload, created_at) VALUES (?1, ?2, ?3, ?4)",
        params![
            task_id,
            kind,
            serde_json::to_string(payload)?,
            now.timestamp()
        ],
    )?;
    Ok(conn.last_insert_rowid())
}

fn path_to_string(path: &Path) -> String {
    path.to_string_lossy().into_owned()
}

fn timestamp(secs: i64) -> Result<DateTime<Utc>> {
    DateTime::from_timestamp(secs, 0).ok_or(Error::Corrupt {
        field: "timestamp",
        value: secs.to_string(),
    })
}

fn row_to_repo(row: &Row<'_>) -> rusqlite::Result<Repo> {
    Ok(Repo {
        id: row.get(0)?,
        path: PathBuf::from(row.get::<_, String>(1)?),
        name: row.get(2)?,
        ignored: row.get(3)?,
        // Timestamps written by this module are always in range.
        discovered_at: DateTime::from_timestamp(row.get(4)?, 0).unwrap_or_default(),
        last_seen_at: DateTime::from_timestamp(row.get(5)?, 0).unwrap_or_default(),
    })
}

fn row_to_todo(row: &Row<'_>) -> rusqlite::Result<Todo> {
    Ok(Todo {
        id: row.get(0)?,
        task_id: row.get(1)?,
        text: row.get(2)?,
        done: row.get(3)?,
        created_at: DateTime::from_timestamp(row.get(4)?, 0).unwrap_or_default(),
    })
}

/// Yields a nested `Result` so a malformed enum surfaces as [`Error::Corrupt`]
/// rather than a sqlite error.
#[allow(clippy::type_complexity)]
fn row_to_task(row: &Row<'_>) -> rusqlite::Result<Result<Task>> {
    let state_raw: String = row.get(3)?;
    let blocked_raw: Option<String> = row.get(4)?;
    let created: i64 = row.get(9)?;
    let updated: i64 = row.get(10)?;

    let Some(state) = TaskState::parse(&state_raw) else {
        return Ok(Err(Error::Corrupt {
            field: "tasks.state",
            value: state_raw,
        }));
    };
    let blocked_kind = match blocked_raw {
        None => None,
        Some(raw) => match BlockedKind::parse(&raw) {
            Some(kind) => Some(kind),
            None => {
                return Ok(Err(Error::Corrupt {
                    field: "tasks.blocked_kind",
                    value: raw,
                }));
            }
        },
    };

    Ok(Ok(Task {
        id: row.get(0)?,
        title: row.get(1)?,
        prompt: row.get(2)?,
        state,
        blocked_kind,
        blocked_reason: row.get(5)?,
        failure_reason: row.get(6)?,
        workspace_dir: PathBuf::from(row.get::<_, String>(7)?),
        session_name: row.get(8)?,
        created_at: match timestamp(created) {
            Ok(ts) => ts,
            Err(err) => return Ok(Err(err)),
        },
        updated_at: match timestamp(updated) {
            Ok(ts) => ts,
            Err(err) => return Ok(Err(err)),
        },
        usage: TaskUsage {
            model: row.get(11)?,
            // Read as i64 and widened: SQLite has no unsigned type, and a
            // negative here would mean a corrupt row rather than a real count.
            context_tokens: row.get::<_, Option<i64>>(12)?.map(|n| n.max(0) as u64),
            output_tokens: row.get::<_, Option<i64>>(13)?.map(|n| n.max(0) as u64),
            transcript_offset: row.get::<_, i64>(14)?.max(0) as u64,
            transcript_path: row.get::<_, Option<String>>(15)?.map(PathBuf::from),
        },
        archived_at: match row.get::<_, Option<i64>>(16)? {
            None => None,
            Some(secs) => match timestamp(secs) {
                Ok(ts) => Some(ts),
                Err(err) => return Ok(Err(err)),
            },
        },
    }))
}

#[allow(clippy::type_complexity)]
fn row_to_event(row: &Row<'_>) -> rusqlite::Result<(i64, Option<i64>, String, String, i64)> {
    Ok((
        row.get(0)?,
        row.get(1)?,
        row.get(2)?,
        row.get(3)?,
        row.get(4)?,
    ))
}

fn collect_tasks<I>(rows: I) -> Result<Vec<Task>>
where
    I: Iterator<Item = rusqlite::Result<Result<Task>>>,
{
    let mut out = Vec::new();
    for row in rows {
        out.push(row??);
    }
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn at(secs: i64) -> DateTime<Utc> {
        DateTime::from_timestamp(secs, 0).expect("valid timestamp")
    }

    fn store() -> Store {
        Store::open_in_memory().expect("in-memory store")
    }

    fn task(store: &mut Store) -> Task {
        store
            .create_task(
                "fix auth",
                "fix the auth flow",
                Path::new("/tmp/tasks"),
                &[],
                at(0),
            )
            .expect("create task")
    }

    #[test]
    fn migrations_apply_and_are_idempotent() {
        let store = store();
        assert_eq!(store.schema_version().unwrap(), MIGRATIONS.len() as i64);
        // Re-running against the same connection must not fail or
        // double-apply.
        let mut conn = store.conn;
        migrate(&mut conn).expect("second migrate");
        let version: i64 = conn
            .query_row("PRAGMA user_version", [], |r| r.get(0))
            .unwrap();
        assert_eq!(version, MIGRATIONS.len() as i64);
    }

    #[test]
    fn workspace_dir_is_derived_from_the_id() {
        let mut store = store();
        let first = task(&mut store);
        let second = task(&mut store);
        assert_eq!(
            first.workspace_dir,
            Path::new("/tmp/tasks").join(first.id.to_string()),
            "the path must match the id it was assigned"
        );
        assert_ne!(first.workspace_dir, second.workspace_dir);
    }

    #[test]
    fn new_task_starts_queued_and_logs_creation() {
        let mut store = store();
        let task = task(&mut store);
        assert_eq!(task.state, TaskState::Queued);
        assert_eq!(task.blocked_kind, None);
        assert_eq!(task.session_name, None);

        let events = store.list_events(task.id).unwrap();
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].kind, "task.created");
    }

    #[test]
    fn happy_path_walks_to_committed() {
        let mut store = store();
        let task = task(&mut store);

        let task = store
            .transition(task.id, TaskState::Running, Transition::Plain, at(1))
            .unwrap();
        assert_eq!(task.state, TaskState::Running);

        let task = store
            .transition(task.id, TaskState::AwaitingReview, Transition::Plain, at(2))
            .unwrap();
        assert_eq!(task.state, TaskState::AwaitingReview);

        let task = store
            .transition(task.id, TaskState::Committed, Transition::Plain, at(3))
            .unwrap();
        assert_eq!(task.state, TaskState::Committed);
        assert_eq!(task.updated_at, at(3));
    }

    #[test]
    fn illegal_transitions_are_rejected() {
        let mut store = store();
        let task = task(&mut store);
        let err = store
            .transition(task.id, TaskState::Committed, Transition::Plain, at(1))
            .unwrap_err();
        assert!(matches!(
            err,
            Error::IllegalTransition {
                from: TaskState::Queued,
                to: TaskState::Committed
            }
        ));
        // The rejected move left nothing behind.
        assert_eq!(store.get_task(task.id).unwrap().state, TaskState::Queued);
        assert_eq!(store.list_events(task.id).unwrap().len(), 1);
    }

    #[test]
    fn blocking_requires_and_clears_its_reason() {
        let mut store = store();
        let task = task(&mut store);
        store
            .transition(task.id, TaskState::Running, Transition::Plain, at(1))
            .unwrap();

        assert!(matches!(
            store
                .transition(task.id, TaskState::Blocked, Transition::Plain, at(2))
                .unwrap_err(),
            Error::MissingBlockedKind
        ));

        let blocked = store
            .transition(
                task.id,
                TaskState::Blocked,
                Transition::Blocked(BlockedInfo::with_reason(
                    BlockedKind::PermissionPrompt,
                    "edit src/main.rs",
                )),
                at(3),
            )
            .unwrap();
        assert_eq!(blocked.blocked_kind, Some(BlockedKind::PermissionPrompt));
        assert_eq!(blocked.blocked_reason.as_deref(), Some("edit src/main.rs"));

        let resumed = store
            .transition(task.id, TaskState::Running, Transition::Plain, at(4))
            .unwrap();
        assert_eq!(resumed.state, TaskState::Running);
        assert_eq!(resumed.blocked_kind, None, "reason must be cleared");
        assert_eq!(resumed.blocked_reason, None);
    }

    #[test]
    fn blocked_details_rejected_for_other_states() {
        let mut store = store();
        let task = task(&mut store);
        let err = store
            .transition(
                task.id,
                TaskState::Running,
                Transition::Blocked(BlockedInfo::new(BlockedKind::Question)),
                at(1),
            )
            .unwrap_err();
        assert!(matches!(err, Error::MismatchedDetail(TaskState::Running)));
    }

    #[test]
    fn failing_requires_and_records_a_reason() {
        let mut store = store();
        let task = task(&mut store);
        store
            .transition(task.id, TaskState::Running, Transition::Plain, at(1))
            .unwrap();

        assert!(matches!(
            store
                .transition(task.id, TaskState::Failed, Transition::Plain, at(2))
                .unwrap_err(),
            Error::MissingFailureReason
        ));

        let failed = store
            .transition(
                task.id,
                TaskState::Failed,
                Transition::Failed("tmux session died".into()),
                at(3),
            )
            .unwrap();
        assert_eq!(failed.state, TaskState::Failed);
        assert_eq!(failed.failure_reason.as_deref(), Some("tmux session died"));
    }

    #[test]
    fn a_failed_task_cannot_be_resumed() {
        let mut store = store();
        let task = task(&mut store);
        store
            .transition(
                task.id,
                TaskState::Failed,
                Transition::Failed("worktree setup failed".into()),
                at(1),
            )
            .unwrap();
        assert!(matches!(
            store
                .transition(task.id, TaskState::Running, Transition::Plain, at(2))
                .unwrap_err(),
            Error::IllegalTransition {
                from: TaskState::Failed,
                to: TaskState::Running
            }
        ));
    }

    #[test]
    fn blocking_details_are_cleared_by_failing() {
        let mut store = store();
        let task = task(&mut store);
        store
            .transition(task.id, TaskState::Running, Transition::Plain, at(1))
            .unwrap();
        store
            .transition(
                task.id,
                TaskState::Blocked,
                Transition::Blocked(BlockedInfo::new(BlockedKind::Question)),
                at(2),
            )
            .unwrap();
        let failed = store
            .transition(
                task.id,
                TaskState::Failed,
                Transition::Failed("agent exited".into()),
                at(3),
            )
            .unwrap();
        assert_eq!(
            failed.blocked_kind, None,
            "stale blocking detail left behind"
        );
        assert_eq!(failed.blocked_reason, None);
        assert_eq!(failed.failure_reason.as_deref(), Some("agent exited"));
    }

    #[test]
    fn cancelling_works_from_every_unfinished_state() {
        for state in [
            TaskState::Queued,
            TaskState::Running,
            TaskState::Blocked,
            TaskState::AwaitingReview,
        ] {
            let mut store = store();
            let task = task(&mut store);

            // Walk to the state under test.
            match state {
                TaskState::Queued => {}
                TaskState::Running => {
                    store
                        .transition(task.id, TaskState::Running, Transition::Plain, at(1))
                        .unwrap();
                }
                TaskState::Blocked => {
                    store
                        .transition(task.id, TaskState::Running, Transition::Plain, at(1))
                        .unwrap();
                    store
                        .transition(
                            task.id,
                            TaskState::Blocked,
                            Transition::Blocked(BlockedInfo::new(BlockedKind::Silence)),
                            at(2),
                        )
                        .unwrap();
                }
                TaskState::AwaitingReview => {
                    store
                        .transition(task.id, TaskState::Running, Transition::Plain, at(1))
                        .unwrap();
                    store
                        .transition(task.id, TaskState::AwaitingReview, Transition::Plain, at(2))
                        .unwrap();
                }
                other => unreachable!("{other} is not under test"),
            }

            let cancelled = store
                .transition(task.id, TaskState::Cancelled, Transition::Plain, at(9))
                .unwrap();
            assert_eq!(cancelled.state, TaskState::Cancelled, "from {state}");
            assert_eq!(cancelled.blocked_kind, None, "from {state}");
        }
    }

    #[test]
    fn a_reviewed_task_cannot_fail() {
        let mut store = store();
        let task = task(&mut store);
        store
            .transition(task.id, TaskState::Running, Transition::Plain, at(1))
            .unwrap();
        store
            .transition(task.id, TaskState::AwaitingReview, Transition::Plain, at(2))
            .unwrap();
        assert!(matches!(
            store
                .transition(
                    task.id,
                    TaskState::Failed,
                    Transition::Failed("nope".into()),
                    at(3)
                )
                .unwrap_err(),
            Error::IllegalTransition {
                from: TaskState::AwaitingReview,
                to: TaskState::Failed
            }
        ));
    }

    #[test]
    fn rejection_returns_to_running() {
        let mut store = store();
        let task = task(&mut store);
        store
            .transition(task.id, TaskState::Running, Transition::Plain, at(1))
            .unwrap();
        store
            .transition(task.id, TaskState::AwaitingReview, Transition::Plain, at(2))
            .unwrap();
        let resumed = store
            .transition(task.id, TaskState::Running, Transition::Plain, at(3))
            .unwrap();
        assert_eq!(resumed.state, TaskState::Running);
    }

    #[test]
    fn every_transition_is_logged() {
        let mut store = store();
        let task = task(&mut store);
        store
            .transition(task.id, TaskState::Running, Transition::Plain, at(1))
            .unwrap();
        store
            .transition(task.id, TaskState::AwaitingReview, Transition::Plain, at(2))
            .unwrap();

        let events = store.list_events(task.id).unwrap();
        let kinds: Vec<_> = events.iter().map(|e| e.kind.as_str()).collect();
        assert_eq!(
            kinds,
            ["task.created", "task.transition", "task.transition"]
        );
        assert_eq!(events[2].payload["from"], "running");
        assert_eq!(events[2].payload["to"], "awaiting-review");
    }

    #[test]
    fn a_task_cannot_leave_one_state_twice_under_contention() {
        // The daemon and the TUI are two processes on one file, so the read in
        // `transition` and its write are separated by a window another writer
        // can land in.
        const TASKS: usize = 200;
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("marver.db");

        let mut store = Store::open(&path).unwrap();
        let mut ids = Vec::new();
        for _ in 0..TASKS {
            let t = task(&mut store);
            store
                .transition(t.id, TaskState::Running, Transition::Plain, at(1))
                .unwrap();
            store
                .transition(t.id, TaskState::AwaitingReview, Transition::Plain, at(2))
                .unwrap();
            ids.push(t.id);
        }
        drop(store);

        // Two writers racing to move every task out of awaiting-review.
        let racers: Vec<_> = [TaskState::Committed, TaskState::Cancelled]
            .into_iter()
            .map(|next| {
                let path = path.clone();
                let ids = ids.clone();
                std::thread::spawn(move || {
                    let mut store = Store::open(&path).unwrap();
                    for id in ids {
                        let _ = store.transition(id, next, Transition::Plain, at(3));
                    }
                })
            })
            .collect();
        for racer in racers {
            racer.join().unwrap();
        }

        let store = Store::open(&path).unwrap();
        for id in ids {
            let exits = store
                .list_events(id)
                .unwrap()
                .iter()
                .filter(|e| e.kind == "task.transition" && e.payload["from"] == "awaiting-review")
                .count();
            assert_eq!(exits, 1, "task {id} left awaiting-review {exits} times");
        }
    }

    #[test]
    fn missing_task_is_reported() {
        let store = store();
        assert!(matches!(store.get_task(404), Err(Error::TaskNotFound(404))));
    }

    #[test]
    fn repo_upsert_is_idempotent_and_preserves_ignored() {
        let store = store();
        let path = Path::new("/Users/kit/workspace/marver");
        let first = store.upsert_repo(path, "marver", at(10)).unwrap();
        store.set_repo_ignored(first.id, true).unwrap();

        let second = store.upsert_repo(path, "marver", at(20)).unwrap();
        assert_eq!(second.id, first.id, "no duplicate row");
        assert_eq!(second.discovered_at, at(10), "discovery time is kept");
        assert_eq!(second.last_seen_at, at(20), "last seen is refreshed");
        assert!(second.ignored, "ignore flag survives a rescan");

        assert_eq!(store.list_repos(false).unwrap().len(), 0);
        assert_eq!(store.list_repos(true).unwrap().len(), 1);
    }

    #[test]
    fn tasks_can_span_several_repos() {
        let mut store = store();
        let a = store
            .upsert_repo(Path::new("/w/api"), "api", at(0))
            .unwrap();
        let b = store
            .upsert_repo(Path::new("/w/web"), "web", at(0))
            .unwrap();
        let task = store
            .create_task("t", "p", Path::new("/tmp/tasks"), &[a.id, b.id], at(0))
            .unwrap();

        store
            .record_worktree(task.id, a.id, Path::new("/t/1/api"), "task/1", "main")
            .unwrap();
        store
            .record_worktree(task.id, b.id, Path::new("/t/1/web"), "task/1", "develop")
            .unwrap();

        let worktrees = store.list_task_repos(task.id).unwrap();
        assert_eq!(worktrees.len(), 2);
        assert_eq!(worktrees[0].base_ref.as_deref(), Some("main"));
        assert_eq!(worktrees[1].base_ref.as_deref(), Some("develop"));
    }

    #[test]
    fn repos_are_selected_at_creation_before_any_worktree_exists() {
        let mut store = store();
        let repo = store
            .upsert_repo(Path::new("/w/api"), "api", at(0))
            .unwrap();
        let task = store
            .create_task("t", "p", Path::new("/tmp/tasks"), &[repo.id], at(0))
            .unwrap();

        let links = store.list_task_repos(task.id).unwrap();
        assert_eq!(links.len(), 1, "the selection is recorded immediately");
        assert!(
            !links[0].is_provisioned(),
            "a queued task owns no worktree yet"
        );
    }

    #[test]
    fn a_worktree_cannot_be_recorded_for_an_unselected_repo() {
        let mut store = store();
        let repo = store
            .upsert_repo(Path::new("/w/api"), "api", at(0))
            .unwrap();
        let task = task(&mut store);
        assert!(
            matches!(
                store.record_worktree(task.id, repo.id, Path::new("/t/x"), "b", "main"),
                Err(Error::RepoNotSelected { .. })
            ),
            "a worktree for an untargeted repo would be orphaned at teardown"
        );
    }

    #[test]
    fn clearing_worktrees_keeps_the_selection() {
        let mut store = store();
        let repo = store
            .upsert_repo(Path::new("/w/api"), "api", at(0))
            .unwrap();
        let task = store
            .create_task("t", "p", Path::new("/tmp/tasks"), &[repo.id], at(0))
            .unwrap();
        store
            .record_worktree(task.id, repo.id, Path::new("/t/1/api"), "b", "main")
            .unwrap();

        store.clear_worktrees(task.id).unwrap();
        let links = store.list_task_repos(task.id).unwrap();
        assert_eq!(links.len(), 1, "the task still targets the repo");
        assert!(!links[0].is_provisioned());
    }

    #[test]
    fn a_repo_joins_a_task_only_once() {
        let mut store = store();
        let repo = store
            .upsert_repo(Path::new("/w/api"), "api", at(0))
            .unwrap();
        let task = store
            .create_task("t", "p", Path::new("/tmp/tasks"), &[repo.id], at(0))
            .unwrap();
        assert!(store.select_repo(task.id, repo.id).is_err());
    }

    #[test]
    fn worktrees_require_a_real_task() {
        let store = store();
        let repo = store
            .upsert_repo(Path::new("/w/api"), "api", at(0))
            .unwrap();
        assert!(
            store.select_repo(999, repo.id).is_err(),
            "foreign keys must be enforced"
        );
    }

    #[test]
    fn listing_by_state_partitions_tasks() {
        let mut store = store();
        let a = task(&mut store);
        let b = task(&mut store);
        store
            .transition(a.id, TaskState::Running, Transition::Plain, at(1))
            .unwrap();

        let queued = store.list_tasks_in_state(TaskState::Queued).unwrap();
        let running = store.list_tasks_in_state(TaskState::Running).unwrap();
        assert_eq!(queued.iter().map(|t| t.id).collect::<Vec<_>>(), [b.id]);
        assert_eq!(running.iter().map(|t| t.id).collect::<Vec<_>>(), [a.id]);
        assert_eq!(store.list_tasks().unwrap().len(), 2);
    }

    #[test]
    fn session_name_is_recorded() {
        let mut store = store();
        let task = task(&mut store);
        store.set_session_name(task.id, "marver-1", at(5)).unwrap();
        let task = store.get_task(task.id).unwrap();
        assert_eq!(task.session_name.as_deref(), Some("marver-1"));
        assert_eq!(task.updated_at, at(5));
    }

    #[test]
    fn database_rejects_an_unknown_state() {
        let store = store();
        let err = store.conn.execute(
            "INSERT INTO tasks (title, prompt, state, workspace_dir, created_at, updated_at)
             VALUES ('x', 'x', 'nonsense', '/tmp', 0, 0)",
            [],
        );
        assert!(err.is_err(), "CHECK constraint should reject the state");
    }

    #[test]
    fn database_rejects_a_reason_without_being_blocked() {
        let store = store();
        let err = store.conn.execute(
            "INSERT INTO tasks (title, prompt, state, blocked_kind, workspace_dir, created_at, updated_at)
             VALUES ('x', 'x', 'running', 'question', '/tmp', 0, 0)",
            [],
        );
        assert!(
            err.is_err(),
            "a blocked_kind outside the blocked state is incoherent"
        );
    }
}

#[cfg(test)]
mod migration_tests {
    use super::*;
    use tempfile::TempDir;

    /// A database at schema version 1, with a row in every table that
    /// references `tasks`.
    fn version_one_database(path: &Path) {
        let conn = Connection::open(path).expect("open");
        conn.execute_batch(MIGRATIONS[0]).expect("initial schema");
        conn.execute_batch("PRAGMA user_version = 1")
            .expect("stamp");
        conn.execute_batch(
            "INSERT INTO repos (path, name, ignored, discovered_at, last_seen_at)
                 VALUES ('/r/api', 'api', 0, 0, 0);
             INSERT INTO tasks (title, prompt, state, workspace_dir, created_at, updated_at)
                 VALUES ('old task', 'do it', 'running', '/w/1', 0, 0);
             INSERT INTO task_repos (task_id, repo_id, worktree_path, branch, base_ref)
                 VALUES (1, 1, '/w/1/api', 'marver/1-old', 'main');
             INSERT INTO events (task_id, kind, payload, created_at)
                 VALUES (1, 'task.transition', '{}', 0);",
        )
        .expect("seed");
    }

    #[test]
    fn migrating_to_the_paused_schema_keeps_every_row() {
        // The tasks table is rebuilt to widen a CHECK constraint, which means
        // dropping it while task_repos and events still reference it.
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("v1.db");
        version_one_database(&path);

        let store = Store::open(&path).expect("migrate");

        assert_eq!(store.schema_version().unwrap(), MIGRATIONS.len() as i64);
        assert_eq!(store.get_task(1).unwrap().title, "old task");
        assert_eq!(
            store.list_task_repos(1).unwrap().len(),
            1,
            "the cascade would have taken the worktree record"
        );
        assert_eq!(
            store.list_events(1).unwrap().len(),
            1,
            "and the task's whole history with it"
        );
    }

    #[test]
    fn the_rebuilt_tasks_table_keeps_the_constraints_it_had() {
        // A rebuild is a retyping, and a retyping can quietly drop a CHECK.
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("v1.db");
        version_one_database(&path);
        let store = Store::open(&path).expect("migrate");

        assert!(
            store
                .conn
                .execute_batch(
                    "INSERT INTO tasks (title, prompt, state, workspace_dir, created_at, updated_at)
                     VALUES ('bad', 'x', 'nonsense', '/w/2', 0, 0)",
                )
                .is_err(),
            "the state list must still be closed"
        );
        assert!(
            store
                .conn
                .execute_batch(
                    "INSERT INTO tasks (title, prompt, state, failure_reason, workspace_dir,
                                        created_at, updated_at)
                     VALUES ('bad', 'x', 'running', 'why', '/w/2', 0, 0)",
                )
                .is_err(),
            "a failure reason still belongs only to a failed task"
        );
    }

    #[test]
    fn foreign_keys_are_enforced_again_after_migrating() {
        // They are turned off around the rebuild.
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("v1.db");
        version_one_database(&path);
        let store = Store::open(&path).expect("migrate");

        let enforced: i64 = store
            .conn
            .query_row("PRAGMA foreign_keys", [], |row| row.get(0))
            .unwrap();
        assert_eq!(enforced, 1);
        assert!(
            store
                .conn
                .execute_batch(
                    "INSERT INTO todos (task_id, text, done, created_at)
                     VALUES (9999, 'orphan', 0, 0)",
                )
                .is_err(),
            "a todo pointing at no task must be refused"
        );
    }

    #[test]
    fn the_usage_columns_arrive_empty_on_a_task_that_predates_them() {
        // Added by ALTER TABLE rather than a rebuild, so the existing rows
        // keep everything they had and gain nothing but nulls -- and a null
        // must read as "not known", never as zero tokens spent.
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("v1.db");
        version_one_database(&path);

        let store = Store::open(&path).expect("migrate");

        let task = store.get_task(1).unwrap();
        assert_eq!(task.title, "old task", "the row survived both migrations");
        assert!(!task.usage.is_known());
        assert_eq!(task.usage.output_tokens, None);
        assert_eq!(task.usage.transcript_offset, 0, "read it from the start");
    }

    #[test]
    fn a_fresh_database_arrives_at_the_same_place_as_a_migrated_one() {
        let dir = TempDir::new().unwrap();
        let migrated = dir.path().join("v1.db");
        version_one_database(&migrated);
        let migrated = Store::open(&migrated).expect("migrate");
        let fresh = Store::open(dir.path().join("new.db")).expect("create");

        assert_eq!(
            migrated.schema_version().unwrap(),
            fresh.schema_version().unwrap()
        );
        for store in [&migrated, &fresh] {
            let mut names: Vec<String> = store
                .conn
                .prepare("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name")
                .unwrap()
                .query_map([], |row| row.get(0))
                .unwrap()
                .collect::<rusqlite::Result<_>>()
                .unwrap();
            names.retain(|name: &String| !name.starts_with("sqlite_"));
            assert_eq!(names, ["events", "repos", "task_repos", "tasks", "todos"]);
        }
    }
}

#[cfg(test)]
mod todo_tests {
    use super::*;

    fn at(secs: i64) -> DateTime<Utc> {
        DateTime::from_timestamp(secs, 0).expect("valid timestamp")
    }

    fn store_with_task() -> (Store, i64) {
        let mut store = Store::open_in_memory().unwrap();
        let id = store
            .create_task("a task", "do it", Path::new("/tmp/tasks"), &[], at(0))
            .unwrap()
            .id;
        (store, id)
    }

    #[test]
    fn the_two_scopes_do_not_see_each_other() {
        // The whole design rests on this: `↵` sends a task todo to an agent
        // and turns a global one into a task, so a list that mixed them would
        // offer the wrong verb for half its rows.
        let (store, task_id) = store_with_task();
        store
            .add_todo(TodoScope::Global, "upgrade ratatui", at(1))
            .unwrap();
        store
            .add_todo(TodoScope::Task(task_id), "also handle nulls", at(2))
            .unwrap();

        let global = store.list_todos(TodoScope::Global).unwrap();
        let task = store.list_todos(TodoScope::Task(task_id)).unwrap();

        assert_eq!(global.len(), 1);
        assert_eq!(global[0].text, "upgrade ratatui");
        assert!(global[0].is_global());
        assert_eq!(task.len(), 1);
        assert_eq!(task[0].text, "also handle nulls");
        assert_eq!(task[0].task_id, Some(task_id));
    }

    #[test]
    fn an_empty_todo_is_refused() {
        let (store, _) = store_with_task();
        assert!(matches!(
            store.add_todo(TodoScope::Global, "   ", at(1)),
            Err(Error::EmptyTodo)
        ));
    }

    #[test]
    fn text_is_trimmed_on_the_way_in() {
        let (store, _) = store_with_task();
        let todo = store
            .add_todo(TodoScope::Global, "  spaced  ", at(1))
            .unwrap();
        assert_eq!(todo.text, "spaced");
    }

    #[test]
    fn done_todos_stay_in_the_list() {
        // Ticking one off must not look like deleting it; `space` and `x` are
        // different keys and mean different things.
        let (store, _) = store_with_task();
        let todo = store.add_todo(TodoScope::Global, "note", at(1)).unwrap();

        let done = store.set_todo_done(todo.id, true).unwrap();

        assert!(done.done);
        assert_eq!(store.list_todos(TodoScope::Global).unwrap().len(), 1);
        assert_eq!(store.open_todo_count(TodoScope::Global).unwrap(), 0);
    }

    #[test]
    fn counts_are_per_task_and_skip_the_finished_ones() {
        let (mut store, first) = store_with_task();
        let second = store
            .create_task("another", "do it", Path::new("/tmp/tasks"), &[], at(0))
            .unwrap()
            .id;
        store
            .add_todo(TodoScope::Task(first), "one", at(1))
            .unwrap();
        let done = store
            .add_todo(TodoScope::Task(first), "two", at(2))
            .unwrap();
        store
            .add_todo(TodoScope::Task(second), "three", at(3))
            .unwrap();
        store
            .add_todo(TodoScope::Global, "not a task's", at(4))
            .unwrap();
        store.set_todo_done(done.id, true).unwrap();

        let counts = store.open_todo_counts().unwrap();

        assert_eq!(counts.get(&first), Some(&1));
        assert_eq!(counts.get(&second), Some(&1));
        assert_eq!(counts.len(), 2, "the global todo belongs to no task");
    }

    #[test]
    fn a_todo_goes_when_its_task_does() {
        let (store, task_id) = store_with_task();
        store
            .add_todo(TodoScope::Task(task_id), "note", at(1))
            .unwrap();

        store
            .conn
            .execute("DELETE FROM tasks WHERE id = ?1", params![task_id])
            .unwrap();

        assert!(
            store
                .list_todos(TodoScope::Task(task_id))
                .unwrap()
                .is_empty()
        );
    }

    #[test]
    fn deleting_something_that_is_not_there_says_so() {
        let (store, _) = store_with_task();
        assert!(matches!(
            store.delete_todo(404),
            Err(Error::TodoNotFound(404))
        ));
    }
}

#[cfg(test)]
mod usage_tests {
    use super::*;
    use crate::usage::Usage;

    fn at(secs: i64) -> DateTime<Utc> {
        DateTime::from_timestamp(secs, 0).expect("valid timestamp")
    }

    fn store_with_task() -> (Store, i64) {
        let mut store = Store::open_in_memory().unwrap();
        let id = store
            .create_task("a task", "do it", Path::new("/tmp/tasks"), &[], at(0))
            .unwrap()
            .id;
        (store, id)
    }

    #[test]
    fn a_new_task_knows_nothing_about_what_it_has_spent() {
        let (store, id) = store_with_task();
        let usage = store.get_task(id).unwrap().usage;

        assert!(!usage.is_known());
        assert_eq!(usage.transcript_offset, 0);
        assert_eq!(usage.output_tokens, None, "unknown is not zero");
    }

    #[test]
    fn context_replaces_and_output_accumulates() {
        // The two numbers mean different things: context is how full the
        // window was on the last turn, output is a total across every turn.
        let (store, id) = store_with_task();

        store
            .record_usage(
                id,
                &Usage {
                    model: Some("claude-opus-5".into()),
                    context_tokens: Some(1_000),
                    output_tokens: 200,
                    offset: 512,
                    from: 0,
                },
            )
            .unwrap();
        store
            .record_usage(
                id,
                &Usage {
                    model: Some("claude-opus-5".into()),
                    context_tokens: Some(4_000),
                    output_tokens: 50,
                    offset: 900,
                    from: 512,
                },
            )
            .unwrap();

        let usage = store.get_task(id).unwrap().usage;
        assert_eq!(usage.context_tokens, Some(4_000), "the latest level");
        assert_eq!(usage.output_tokens, Some(250), "the running total");
        assert_eq!(usage.transcript_offset, 900);
    }

    #[test]
    fn a_read_that_found_nothing_advances_the_offset_and_keeps_the_rest() {
        // Walking over user turns is progress, but it is not a reason to
        // forget which model the agent is on.
        let (store, id) = store_with_task();
        store
            .record_usage(
                id,
                &Usage {
                    model: Some("claude-opus-5".into()),
                    context_tokens: Some(1_000),
                    output_tokens: 200,
                    offset: 512,
                    from: 0,
                },
            )
            .unwrap();

        store
            .record_usage(
                id,
                &Usage {
                    offset: 800,
                    from: 512,
                    ..Usage::default()
                },
            )
            .unwrap();

        let usage = store.get_task(id).unwrap().usage;
        assert_eq!(usage.model.as_deref(), Some("claude-opus-5"));
        assert_eq!(usage.context_tokens, Some(1_000));
        assert_eq!(usage.output_tokens, Some(200));
        assert_eq!(usage.transcript_offset, 800);
    }

    #[test]
    fn the_transcript_path_is_remembered() {
        let (store, id) = store_with_task();
        store
            .set_transcript_path(id, Path::new("/t/session.jsonl"))
            .unwrap();

        assert_eq!(
            store.get_task(id).unwrap().usage.transcript_path,
            Some(PathBuf::from("/t/session.jsonl"))
        );
    }

    #[test]
    fn two_readers_of_the_same_turn_count_it_once() {
        // The daemon absorbs on every hook and the task screen refreshes on a
        // timer. Both read the offset, both parse the same bytes, and output
        // tokens accumulate — so the second write has to be refused.
        let (store, id) = store_with_task();
        let seen_by_both = Usage {
            model: Some("claude-opus-5".into()),
            context_tokens: Some(1_000),
            output_tokens: 200,
            offset: 500,
            from: 0,
        };

        assert!(store.record_usage(id, &seen_by_both).unwrap());
        assert!(
            !store.record_usage(id, &seen_by_both).unwrap(),
            "the second reader read stale state and must be told so"
        );

        assert_eq!(store.get_task(id).unwrap().usage.output_tokens, Some(200));
    }

    #[test]
    fn a_different_transcript_is_read_from_its_own_beginning() {
        // A new session writes a new file. Seeking it to the old file's offset
        // would skip however much of the new one happens to fit.
        let (store, id) = store_with_task();
        store
            .set_transcript_path(id, Path::new("/t/one.jsonl"))
            .unwrap();
        store
            .record_usage(
                id,
                &Usage {
                    output_tokens: 200,
                    offset: 4_096,
                    from: 0,
                    ..Usage::default()
                },
            )
            .unwrap();

        store
            .set_transcript_path(id, Path::new("/t/two.jsonl"))
            .unwrap();

        let usage = store.get_task(id).unwrap().usage;
        assert_eq!(usage.transcript_offset, 0, "rewound for the new file");
        assert_eq!(
            usage.output_tokens,
            Some(200),
            "but what the agent already spent is still spent"
        );
    }

    #[test]
    fn setting_the_same_transcript_path_again_does_not_rewind() {
        // Every hook carrying the same path must not re-read the file from the
        // start and count all of it again.
        let (store, id) = store_with_task();
        store
            .set_transcript_path(id, Path::new("/t/one.jsonl"))
            .unwrap();
        store
            .record_usage(
                id,
                &Usage {
                    offset: 4_096,
                    from: 0,
                    ..Usage::default()
                },
            )
            .unwrap();

        store
            .set_transcript_path(id, Path::new("/t/one.jsonl"))
            .unwrap();

        assert_eq!(store.get_task(id).unwrap().usage.transcript_offset, 4_096);
    }

    #[test]
    fn recording_against_a_task_that_is_gone_says_so() {
        let (store, _) = store_with_task();
        assert!(matches!(
            store.record_usage(404, &Usage::default()),
            Err(Error::TaskNotFound(404))
        ));
    }
}