sloop-daemon 0.4.0

Agentic coding scheduler — a daemon that runs background coding agents autonomously in isolated git worktrees
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
use std::collections::BTreeMap;
use std::fmt;
use std::fs;
use std::fs::OpenOptions;
use std::io::{self, Write};
use std::path::{Component, Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};

use async_trait::async_trait;
use rusqlite::{Transaction, TransactionBehavior};
use serde_json::{Value, json};

use crate::config::{AgentConfig, expand_agent_cmd};
use crate::db::StoreError;
use crate::domain::ticket::TicketState;
use crate::domain::trigger::TriggerKind;
use crate::domain::work::{ExecutionHints, SourceVersion, TicketRef, WorkTicket, WorkTicketState};
use crate::flow::Flow;
use crate::frontmatter::{self, FrontmatterError};
use crate::ids::{IdError, next_id};
use crate::protocol::{PostArgs, PostTrigger};
use crate::work_state::local::{self, LocalSqlite, LocalTicketWrite};
use crate::work_state::trigger::{self, Duplicates, EnqueueRequest};
use crate::work_state::{SourceError, WorkStateAuthor};

#[derive(Clone, Copy)]
struct TriggerRequest {
    kind: TriggerKind,
    eligible_at_ms: Option<i64>,
}

static POST_TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);

struct StagedWrite {
    path: PathBuf,
    target: PathBuf,
    persisted: bool,
}

impl StagedWrite {
    fn new(target: PathBuf, content: &str) -> io::Result<Self> {
        let parent = target.parent().unwrap_or_else(|| Path::new("."));
        let name = target
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or("ticket");
        let (path, mut file) = loop {
            let ordinal = POST_TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
            let path = parent.join(format!(
                ".{name}.sloop-post-{}-{ordinal}.tmp",
                std::process::id()
            ));
            match OpenOptions::new().write(true).create_new(true).open(&path) {
                Ok(file) => break (path, file),
                Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
                Err(error) => return Err(error),
            }
        };
        let staged = Self {
            path,
            target,
            persisted: false,
        };
        if let Ok(metadata) = fs::metadata(&staged.target) {
            fs::set_permissions(&staged.path, metadata.permissions())?;
        }
        file.write_all(content.as_bytes())?;
        file.sync_all()?;
        Ok(staged)
    }

    fn persist(mut self) -> io::Result<()> {
        fs::rename(&self.path, &self.target)?;
        self.persisted = true;
        Ok(())
    }
}

impl Drop for StagedWrite {
    fn drop(&mut self) {
        if !self.persisted {
            let _ = fs::remove_file(&self.path);
        }
    }
}

/// Local markdown authoring over SQLite.
///
/// A [`SourceVersion`] is the lowercase hexadecimal FNV-1a hash of the
/// complete markdown file content. Updates compare that version with the file
/// immediately before committing, so a concurrent edit is rejected instead
/// of silently overwritten.
struct MarkdownWorkStateAuthor<'a> {
    root: &'a Path,
    file_path: &'a str,
    worktree: &'a str,
    work_state: &'a LocalSqlite,
    original_content: &'a str,
    final_content: &'a str,
    original_version: SourceVersion,
    trigger: Option<TriggerRequest>,
    now_ms: i64,
    trigger_result: Mutex<Value>,
}

impl MarkdownWorkStateAuthor<'_> {
    fn absolute_path(&self) -> PathBuf {
        self.root.join(self.file_path)
    }

    fn ensure_source_version(&self, expected: &SourceVersion) -> Result<(), SourceError> {
        let path = self.absolute_path();
        let content = fs::read_to_string(&path).map_err(|error| SourceError::Corrupt {
            message: format!("cannot read {}: {error}", path.display()),
        })?;
        let actual = source_version(&content);
        if &actual != expected {
            return Err(SourceError::Rejected {
                message: format!(
                    "source version conflict for `{}`: expected {}, found {}",
                    self.file_path, expected.0, actual.0
                ),
            });
        }
        Ok(())
    }

    fn commit(
        &self,
        ticket: &WorkTicket,
        update: bool,
        expected: &SourceVersion,
    ) -> Result<(), SourceError> {
        let staged = (self.final_content != self.original_content)
            .then(|| StagedWrite::new(self.absolute_path(), self.final_content))
            .transpose()
            .map_err(|error| SourceError::Corrupt {
                message: format!("cannot stage {}: {error}", self.file_path),
            })?;
        self.ensure_source_version(expected)?;
        let db = self.work_state.db();
        let mut connection = db.lock();
        let transaction = connection
            .transaction_with_behavior(TransactionBehavior::Immediate)
            .map_err(StoreError::from)
            .map_err(source_store_error)?;
        let write = LocalTicketWrite {
            id: &ticket.id,
            project_id: &ticket.project_id,
            file_path: self.file_path,
            name: &ticket.name,
            blocked_by: &ticket.blocked_by,
            worktree: self.worktree,
            target: ticket.hints.target.as_deref(),
            model: ticket.hints.model.as_deref(),
            effort: ticket.hints.effort.as_deref(),
            flow: ticket.hints.flow.as_deref().unwrap_or_default(),
            state: ticket.state.to_ticket_state(),
            body: &ticket.body,
            content_hash: &ticket.version.0,
            now_ms: self.now_ms,
        };
        if update {
            local::tx::update_authored_ticket(&transaction, &write).map_err(source_store_error)?;
        } else {
            local::tx::insert_authored_ticket(&transaction, &write).map_err(source_store_error)?;
        }
        let trigger =
            queue_trigger_transaction(&transaction, &ticket.id, self.trigger, self.now_ms)
                .map_err(source_store_error)?;
        self.ensure_source_version(expected)?;
        transaction
            .commit()
            .map_err(StoreError::from)
            .map_err(source_store_error)?;
        drop(connection);

        if let Some(staged) = staged {
            staged.persist().map_err(|error| SourceError::Corrupt {
                message: format!("cannot replace {}: {error}", self.file_path),
            })?;
        }
        *self
            .trigger_result
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner()) = trigger;
        Ok(())
    }

    fn trigger_result(&self) -> Value {
        self.trigger_result
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .clone()
    }
}

#[async_trait]
impl WorkStateAuthor for MarkdownWorkStateAuthor<'_> {
    async fn post(&self, ticket: &WorkTicket) -> Result<TicketRef, SourceError> {
        self.commit(ticket, false, &self.original_version)?;
        Ok(TicketRef {
            id: ticket.id.clone(),
            source: "local".into(),
            source_ref: Some(self.file_path.into()),
        })
    }

    async fn update(
        &self,
        ticket: &TicketRef,
        content: &WorkTicket,
        expected: &SourceVersion,
    ) -> Result<SourceVersion, SourceError> {
        if ticket.id != content.id || ticket.source_ref.as_deref() != Some(self.file_path) {
            return Err(SourceError::Rejected {
                message: format!("ticket reference conflict for `{}`", content.id),
            });
        }
        self.commit(content, true, expected)?;
        Ok(content.version.clone())
    }
}

/// Registers a ticket file: validates and stamps frontmatter, indexes the
/// ticket, and for `auto` and `at` creates one queued trigger. Reposting
/// a stamped file is idempotent; reposting with a different `--at` time
/// reschedules the queued trigger. The dispatcher is the only caller and
/// computes `at_eligible_ms` from its injected clock, so plain reads before
/// writes here cannot race another writer.
///
/// A trigger is queued only when the post leaves the ticket in `ready`.
/// Reposting a settled ticket still refreshes the indexed content — editing
/// a merged ticket's file must keep working — but queues nothing.
#[allow(clippy::too_many_arguments)]
pub async fn handle(
    root: &Path,
    ticket_dir: &Path,
    work_state: &LocalSqlite,
    args: &PostArgs,
    now_ms: i64,
    at_eligible_ms: Option<i64>,
    ticket_prefix: &str,
    agent: Option<&AgentConfig>,
    flows: &BTreeMap<String, Flow>,
    default_flow: &str,
) -> Result<Value, PostError> {
    let initial_state = match args.trigger {
        PostTrigger::Hold => TicketState::Held,
        _ => TicketState::Ready,
    };
    let relative = repository_relative(root, ticket_dir, &args.file)?;
    let relative_str = relative.to_string_lossy().into_owned();
    let absolute = root.join(&relative);
    let content = fs::read_to_string(&absolute).map_err(|source| {
        if source.kind() == io::ErrorKind::NotFound {
            PostError::TicketFileNotFound(relative_str.clone())
        } else {
            PostError::Io {
                path: relative_str.clone(),
                source,
            }
        }
    })?;
    let stamped = parse_ticket_frontmatter(&content, &relative_str)?;

    let project = match (stamped.project.as_deref(), args.project.as_deref()) {
        (Some(stamped), Some(requested)) if stamped != requested => {
            return Err(PostError::ProjectConflict {
                path: relative_str,
                stamped: stamped.into(),
                requested: requested.into(),
            });
        }
        (Some(stamped), _) => stamped.to_owned(),
        (None, Some(requested)) => requested.to_owned(),
        (None, None) => "default".to_owned(),
    };
    if !work_state.project_exists(&project)? {
        return Err(PostError::UnknownProject(project));
    }

    let flow_name = match (stamped.flow.as_deref(), args.flow.as_deref()) {
        (Some(stamped), Some(requested)) if stamped != requested => {
            return Err(PostError::FlowConflict {
                path: relative_str,
                stamped: stamped.into(),
                requested: requested.into(),
            });
        }
        (Some(stamped), _) => stamped.to_owned(),
        (None, Some(requested)) => requested.to_owned(),
        (None, None) => default_flow.to_owned(),
    };
    if !flows.contains_key(&flow_name) {
        let mut known: Vec<&str> = flows.keys().map(String::as_str).collect();
        known.sort_unstable();
        return Err(PostError::UnknownFlow {
            flow: flow_name,
            known: known.into_iter().map(str::to_owned).collect(),
        });
    }

    let target = match stamped.target.as_deref() {
        Some(target) if agent.is_some_and(|agent| agent.targets.contains_key(target)) => {
            Some(target.to_owned())
        }
        Some(target) => return Err(PostError::UnknownTarget(target.to_owned())),
        None => agent.map(|agent| agent.default_target.clone()),
    };
    if let (Some(agent), Some(target)) = (agent, target.as_deref()) {
        let command = agent
            .targets
            .get(target)
            .expect("configured default target was validated");
        expand_agent_cmd(
            command,
            stamped.model.as_deref(),
            stamped.effort.as_deref(),
            "",
        )
        .map_err(|message| PostError::MissingTargetValue {
            target: target.to_owned(),
            message,
        })?;
    }

    let (ticket_id, existing) = match stamped.id.as_deref() {
        Some(id) => {
            if let Some(existing) = work_state.ticket(id)? {
                if existing.file_path.as_deref() != Some(relative_str.as_str()) {
                    return Err(PostError::TicketIdTaken {
                        id: id.to_owned(),
                        file: existing.file_path.unwrap_or_default(),
                    });
                }
                if existing.project_id != project {
                    return Err(PostError::ProjectConflict {
                        path: relative_str,
                        stamped: project,
                        requested: existing.project_id,
                    });
                }
                (id.to_owned(), Some(existing))
            } else {
                (id.to_owned(), None)
            }
        }
        None => match work_state.ticket_by_file(&relative_str)? {
            Some(existing) => {
                if existing.project_id != project {
                    return Err(PostError::ProjectConflict {
                        path: relative_str,
                        stamped: project,
                        requested: existing.project_id,
                    });
                }
                (existing.id.clone(), Some(existing))
            }
            None => (allocate_ticket_id(work_state, ticket_prefix)?, None),
        },
    };
    for blocker in &stamped.blocked_by {
        if blocker != &ticket_id && work_state.ticket(blocker)?.is_none() {
            return Err(PostError::UnknownBlockedBy {
                ticket: ticket_id.clone(),
                blocker: blocker.clone(),
            });
        }
    }
    let mut dependencies = work_state.ticket_dependencies()?;
    dependencies.insert(ticket_id.clone(), stamped.blocked_by.clone());
    if let Some(chain) = crate::domain::graph::find_cycle(&dependencies) {
        return Err(PostError::DependencyCycle(chain));
    }

    let worktree = match stamped.worktree.clone() {
        Some(worktree) => worktree,
        None => {
            let stem = Path::new(&relative_str)
                .file_stem()
                .and_then(|stem| stem.to_str());
            crate::ids::default_worktree(stem, &ticket_id).map_err(|reason| {
                PostError::InvalidWorktreeStem {
                    path: relative_str.clone(),
                    reason,
                }
            })?
        }
    };
    let final_content = frontmatter::stamp(&content, &ticket_id, &project, &worktree, &flow_name)
        .map_err(|error| PostError::InvalidTicket {
            path: relative_str.clone(),
            error,
        })?
        .unwrap_or_else(|| content.clone());
    // A repost cannot move a settled ticket: `update_authored_ticket` omits
    // `state` from its `SET`, so `merged`, `failed`, and `needs_review` all
    // survive the write. Dispatch requires `ready`, so a trigger queued
    // here could never fire; it would only sit in `queued_triggers` as
    // phantom demand and skew every gate that reads that count. `failed` is
    // included even though `sloop retry` revives it: a lingering trigger
    // would make one failed ticket spawn on `retry` while every other one
    // waits for `sloop run`.
    let terminal_state = existing
        .as_ref()
        .map(|ticket| ticket.state.clone())
        .filter(|state| matches!(state.as_str(), "merged" | "failed" | "needs_review"));
    let trigger_request = if terminal_state.is_some() {
        None
    } else {
        match &args.trigger {
            PostTrigger::Manual | PostTrigger::Hold => None,
            PostTrigger::Auto => Some(TriggerRequest {
                kind: TriggerKind::Auto,
                eligible_at_ms: None,
            }),
            PostTrigger::At { .. } => Some(TriggerRequest {
                kind: TriggerKind::At,
                eligible_at_ms: Some(
                    at_eligible_ms.expect("the dispatcher computes eligibility for at triggers"),
                ),
            }),
        }
    };
    let work_ticket = WorkTicket {
        id: ticket_id.clone(),
        project_id: project.clone(),
        name: stamped.name.clone(),
        body: frontmatter::body(&content)
            .expect("validated frontmatter has a body")
            .to_owned(),
        state: WorkTicketState::from_ticket_state(
            initial_state,
            false,
            String::new(),
            crate::domain::work::OwnerId(String::new()),
        ),
        blocked_by: stamped.blocked_by.clone(),
        attempts: existing.as_ref().map_or(0, |ticket| ticket.attempts as u32),
        hints: ExecutionHints {
            worktree: Some(worktree.clone()),
            trigger_id: None,
            target,
            model: stamped.model.clone(),
            effort: stamped.effort.clone(),
            flow: Some(flow_name.clone()),
        },
        version: source_version(&final_content),
    };
    let author = MarkdownWorkStateAuthor {
        root,
        file_path: &relative_str,
        worktree: &worktree,
        work_state,
        original_content: &content,
        final_content: &final_content,
        original_version: source_version(&content),
        trigger: trigger_request,
        now_ms,
        trigger_result: Mutex::new(Value::Null),
    };
    let ticket_ref = TicketRef {
        id: ticket_id,
        source: "local".into(),
        source_ref: Some(relative_str.clone()),
    };
    let created = existing.is_none();
    if created {
        author.post(&work_ticket).await?;
    } else {
        author
            .update(&ticket_ref, &work_ticket, &author.original_version)
            .await?;
    }
    let trigger = author.trigger_result();
    let ticket = work_state
        .ticket(&work_ticket.id)?
        .expect("registered ticket still exists");

    Ok(json!({
        "ticket": {
            "id": ticket.id,
            "project": project,
            "file": relative_str,
            "state": ticket.state,
            "name": ticket.name,
            "blocked_by": ticket.blocked_by,
            "worktree": ticket.worktree,
            "target": ticket.target,
            "model": ticket.model,
            "effort": ticket.effort,
            "flow": ticket.flow,
        },
        "created": created,
        "trigger": trigger,
        // `trigger` alone cannot tell a machine consumer why it is null:
        // `--manual` and `--hold` never asked for one, while a terminal
        // ticket asked and was refused. Only the second sets this.
        "trigger_suppressed": terminal_state.map(|state| json!({
            "reason": "terminal_ticket",
            "state": state,
        })),
    }))
}

/// Validates a ticket file, reporting *every* independent problem at once so
/// authoring a ticket does not turn into one round-trip per mistake.
///
/// The split between short-circuiting and accumulating is deliberate. A file
/// whose frontmatter cannot be read at all — no block, unterminated, YAML
/// that does not parse, a block that is not a mapping — fails fast: no field
/// can be read out of it, so every other check would either be unanswerable
/// or degenerate into "everything is missing". Once a mapping is in hand,
/// each field and the body are independent, and the caller deserves the full
/// list. Checks that need the store (unknown blockers, dependency cycles,
/// project/flow/target resolution) stay in `handle`: they are registration
/// problems rather than problems with the file, and they carry their own
/// error codes.
pub(crate) fn parse_ticket_frontmatter(
    content: &str,
    path: &str,
) -> Result<frontmatter::Frontmatter, PostError> {
    let (stamped, field_errors) =
        frontmatter::parse_collecting(content).map_err(|error| PostError::InvalidTicket {
            path: path.to_owned(),
            error,
        })?;

    // A field that failed to parse is already reported by its own problem;
    // adding "missing" on top of "wrong type" would only muddy the list.
    let name_is_reported = field_errors
        .iter()
        .any(|error| matches!(error, FrontmatterError::InvalidFieldType { key } if key == "name"));
    let blocked_by_is_reported = field_errors
        .iter()
        .any(|error| matches!(error, FrontmatterError::InvalidBlockedBy));

    let mut problems = Vec::new();
    if !name_is_reported && stamped.name.trim().is_empty() {
        problems.push(TicketProblem::MissingName);
    }
    if !blocked_by_is_reported && !stamped.has_blocked_by() {
        problems.push(TicketProblem::MissingBlockedBy);
    }
    if frontmatter::body(content)
        .expect("frontmatter was already parsed")
        .trim()
        .is_empty()
    {
        problems.push(TicketProblem::EmptyBody);
    }
    problems.extend(field_errors.into_iter().map(TicketProblem::from));

    if problems.is_empty() {
        Ok(stamped)
    } else {
        Err(PostError::InvalidTicketFields {
            path: path.to_owned(),
            problems,
        })
    }
}

/// Queues the demand a post asked for, inside the transaction that registers
/// the ticket. `Duplicates::Reuse` is what makes reposting idempotent: an
/// existing queued trigger of the same kind absorbs the request instead of
/// piling a second one behind it.
///
/// `request` is `None` for a settled ticket, which is what keeps the reuse
/// branch from re-timing a stale `--at` trigger onto one: the caller decides
/// eligibility, this function only carries it out.
fn queue_trigger_transaction(
    transaction: &Transaction<'_>,
    ticket_id: &str,
    request: Option<TriggerRequest>,
    now_ms: i64,
) -> Result<Value, StoreError> {
    let Some(request) = request else {
        return Ok(Value::Null);
    };
    let id = trigger::enqueue(
        transaction,
        &EnqueueRequest {
            kind: request.kind,
            ticket_id: Some(ticket_id),
            project_id: None,
            eligible_at_ms: request.eligible_at_ms,
            interval_ms: None,
            filters: &[],
            duplicates: Duplicates::Reuse,
        },
        now_ms,
    )?
    .id;
    let mut trigger = json!({
        "id": id,
        "kind": request.kind.as_str(),
        "state": "queued",
        "ticket": ticket_id,
    });
    if let Some(eligible_at_ms) = request.eligible_at_ms {
        trigger["eligible_at_ms"] = json!(eligible_at_ms);
    }
    Ok(trigger)
}

fn source_store_error(error: StoreError) -> SourceError {
    if error.is_disk_full() {
        SourceError::Unavailable { retry_after: None }
    } else {
        SourceError::Corrupt {
            message: error.to_string(),
        }
    }
}

fn source_version(content: &str) -> SourceVersion {
    let mut hash = 0xcbf29ce484222325_u64;
    for byte in content.as_bytes() {
        hash ^= u64::from(*byte);
        hash = hash.wrapping_mul(0x100000001b3);
    }
    SourceVersion(format!("{hash:016x}"))
}

fn allocate_ticket_id(work_state: &LocalSqlite, prefix: &str) -> Result<String, PostError> {
    let ids = work_state.ticket_ids()?;
    next_id(prefix, ids.iter().map(String::as_str)).map_err(PostError::IdAllocation)
}

/// Resolves the request path against the repository root and requires the
/// result to stay inside the committed Sloop ticket directory.
fn repository_relative(root: &Path, ticket_dir: &Path, file: &str) -> Result<PathBuf, PostError> {
    let path = Path::new(file);
    let joined = if path.is_absolute() {
        path.to_path_buf()
    } else {
        root.join(path)
    };

    let mut normalized = PathBuf::new();
    for component in joined.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                if !normalized.pop() {
                    return Err(PostError::OutsideRepository(file.to_owned()));
                }
            }
            component => normalized.push(component),
        }
    }
    // Both sides go through the same resolution: `Repository::discover` hands
    // this a canonical root, but a caller that does not must not silently get
    // a containment answer decided by symlink spelling.
    let relative = resolve_symlinks(&normalized)
        .strip_prefix(resolve_symlinks(root))
        .map(Path::to_path_buf)
        .map_err(|_| PostError::OutsideRepository(file.to_owned()))?;
    if !relative.starts_with(ticket_dir) {
        return Err(PostError::OutsideTicketDirectory {
            path: file.to_owned(),
            directory: ticket_dir.to_path_buf(),
        });
    }
    Ok(relative)
}

/// Resolves `path` through any symlinks along it, so containment is decided on
/// the same footing as the repository root, which `Repository::discover`
/// always canonicalizes. Without this, a root reached through a symlink — the
/// normal case on macOS, where `/tmp` and `/var/folders` are both links into
/// `/private` — makes every absolute path the operator types look external.
///
/// Containment is checked before the ticket file is read, so the path need not
/// exist yet. The longest existing ancestor is canonicalized and the remaining
/// components are appended unresolved, which keeps a missing file inside the
/// ticket directory reported as `not found` rather than as an escape. A path
/// with no resolvable ancestor keeps its lexical form for the same reason.
fn resolve_symlinks(path: &Path) -> PathBuf {
    let mut unresolved = Vec::new();
    let mut prefix = path;
    loop {
        if let Ok(resolved) = prefix.canonicalize() {
            return unresolved
                .iter()
                .rev()
                .fold(resolved, |base, component| base.join(component));
        }
        match (prefix.parent(), prefix.file_name()) {
            (Some(parent), Some(name)) => {
                unresolved.push(name);
                prefix = parent;
            }
            _ => return path.to_path_buf(),
        }
    }
}

/// A single problem with a ticket file, phrased without the file path so
/// several can be listed under one path heading.
#[derive(Debug)]
pub enum TicketProblem {
    Frontmatter(FrontmatterError),
    MissingName,
    MissingBlockedBy,
    InvalidBlockedBy,
    EmptyBody,
}

impl From<FrontmatterError> for TicketProblem {
    fn from(error: FrontmatterError) -> Self {
        match error {
            FrontmatterError::InvalidBlockedBy => Self::InvalidBlockedBy,
            error => Self::Frontmatter(error),
        }
    }
}

impl fmt::Display for TicketProblem {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Frontmatter(error) => error.fmt(formatter),
            Self::MissingName => {
                formatter.write_str("missing or empty `name`; add `name: Your ticket title`")
            }
            Self::MissingBlockedBy => formatter.write_str(
                "missing `blocked_by`; add `blocked_by: []` if there are no dependencies",
            ),
            Self::InvalidBlockedBy => formatter.write_str(
                "invalid `blocked_by`; use `blocked_by: []` or a YAML list of ticket IDs",
            ),
            Self::EmptyBody => {
                formatter.write_str("empty `body`; add a ticket description after the frontmatter")
            }
        }
    }
}

#[derive(Debug)]
pub enum PostError {
    TicketFileNotFound(String),
    OutsideRepository(String),
    OutsideTicketDirectory {
        path: String,
        directory: PathBuf,
    },
    InvalidTicket {
        path: String,
        error: FrontmatterError,
    },
    /// One or more independent problems with the ticket file itself,
    /// reported together. Never empty.
    InvalidTicketFields {
        path: String,
        problems: Vec<TicketProblem>,
    },
    InvalidWorktreeStem {
        path: String,
        reason: String,
    },
    UnknownBlockedBy {
        ticket: String,
        blocker: String,
    },
    DependencyCycle(Vec<String>),
    UnknownProject(String),
    UnknownTarget(String),
    MissingTargetValue {
        target: String,
        message: String,
    },
    ProjectConflict {
        path: String,
        stamped: String,
        requested: String,
    },
    FlowConflict {
        path: String,
        stamped: String,
        requested: String,
    },
    UnknownFlow {
        flow: String,
        known: Vec<String>,
    },
    TicketIdTaken {
        id: String,
        file: String,
    },
    Io {
        path: String,
        source: io::Error,
    },
    Source(SourceError),
    Store(StoreError),
    IdAllocation(IdError),
}

impl From<SourceError> for PostError {
    fn from(error: SourceError) -> Self {
        Self::Source(error)
    }
}

impl From<StoreError> for PostError {
    fn from(error: StoreError) -> Self {
        Self::Store(error)
    }
}

impl fmt::Display for PostError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::TicketFileNotFound(path) => write!(formatter, "ticket file `{path}` not found"),
            Self::OutsideRepository(path) => {
                write!(formatter, "`{path}` is outside the repository")
            }
            Self::OutsideTicketDirectory { path, directory } => write!(
                formatter,
                "`{path}` is outside the {} directory",
                directory.display()
            ),
            Self::InvalidTicket { path, error } => write!(formatter, "{path}: {error}"),
            // A lone problem keeps the original one-line `path: problem`
            // shape; only a genuine list needs the heading and bullets.
            Self::InvalidTicketFields { path, problems } => match problems.as_slice() {
                [problem] => write!(formatter, "{path}: {problem}"),
                problems => {
                    write!(formatter, "{path}:")?;
                    for problem in problems {
                        write!(formatter, "\n  - {problem}")?;
                    }
                    Ok(())
                }
            },
            Self::InvalidWorktreeStem { path, reason } => {
                write!(formatter, "{path}: {reason}")
            }
            Self::UnknownBlockedBy { ticket, blocker } => write!(
                formatter,
                "ticket `{ticket}` field `blocked_by` references unknown ticket `{blocker}`"
            ),
            Self::DependencyCycle(chain) => write!(
                formatter,
                "field `blocked_by` creates a dependency cycle: {}",
                chain.join(" -> ")
            ),
            Self::UnknownProject(project) => {
                write!(formatter, "project `{project}` is not indexed")
            }
            Self::UnknownTarget(target) => {
                write!(formatter, "agent target `{target}` is not configured")
            }
            Self::MissingTargetValue { target, message } => {
                write!(formatter, "ticket using agent target `{target}` {message}")
            }
            Self::ProjectConflict {
                path,
                stamped,
                requested,
            } => write!(
                formatter,
                "{path}: ticket belongs to project `{stamped}`, not `{requested}`"
            ),
            Self::FlowConflict {
                path,
                stamped,
                requested,
            } => write!(
                formatter,
                "{path}: ticket is bound to flow `{stamped}`, not `{requested}`"
            ),
            Self::UnknownFlow { flow, known } => write!(
                formatter,
                "flow `{flow}` is not defined; known flows: {}",
                known.join(", ")
            ),
            Self::TicketIdTaken { id, file } => write!(
                formatter,
                "ticket ID `{id}` is already registered by `{file}`"
            ),
            Self::Io { path, source } => write!(formatter, "{path}: {source}"),
            Self::Source(error) => error.fmt(formatter),
            Self::Store(error) => error.fmt(formatter),
            Self::IdAllocation(error) => error.fmt(formatter),
        }
    }
}

impl std::error::Error for PostError {}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use tempfile::tempdir;

    use super::{
        MarkdownWorkStateAuthor, PostError, handle as handle_with_directory, source_version,
    };
    use crate::config::{AgentConfig, AgentTarget};
    use crate::db::Db;
    use crate::domain::work::{ExecutionHints, TicketRef, WorkTicket, WorkTicketState};
    use crate::flow::{Actor, Builtin, Check, FailAction, Flow, Stage};
    use crate::protocol::{PostArgs, PostTrigger};
    use crate::work_state::local::LocalSqlite;
    use crate::work_state::{SourceError, WorkStateAuthor};

    fn world() -> (tempfile::TempDir, LocalSqlite) {
        let root = tempdir().unwrap();
        std::fs::create_dir_all(root.path().join(".agents/sloop/tickets")).unwrap();
        let store = LocalSqlite::from_db(Db::open(&root.path().join("sloop.db"), 1_000).unwrap());
        store
            .upsert_local_project(
                "default",
                ".agents/sloop/projects/default.md",
                "Default",
                1_000,
            )
            .unwrap();
        (root, store)
    }

    #[allow(clippy::too_many_arguments)]
    fn handle(
        root: &std::path::Path,
        store: &LocalSqlite,
        args: &PostArgs,
        now_ms: i64,
        ticket_prefix: &str,
        agent: Option<&AgentConfig>,
        flows: &BTreeMap<String, Flow>,
        default_flow: &str,
    ) -> Result<serde_json::Value, PostError> {
        tokio::runtime::Runtime::new()
            .unwrap()
            .block_on(handle_with_directory(
                root,
                std::path::Path::new(".agents/sloop/tickets"),
                store,
                args,
                now_ms,
                None,
                ticket_prefix,
                agent,
                flows,
                default_flow,
            ))
    }

    fn handle_at(
        root: &std::path::Path,
        store: &LocalSqlite,
        args: &PostArgs,
        now_ms: i64,
        at_eligible_ms: i64,
    ) -> Result<serde_json::Value, PostError> {
        tokio::runtime::Runtime::new()
            .unwrap()
            .block_on(handle_with_directory(
                root,
                std::path::Path::new(".agents/sloop/tickets"),
                store,
                args,
                now_ms,
                Some(at_eligible_ms),
                "TICK",
                None,
                &flows(),
                "default",
            ))
    }

    fn post(file: &str, trigger: PostTrigger) -> PostArgs {
        PostArgs {
            file: file.into(),
            project: None,
            flow: None,
            trigger,
        }
    }

    fn flows() -> BTreeMap<String, Flow> {
        BTreeMap::from([
            (
                "default".to_owned(),
                Flow {
                    name: "default".into(),
                    stages: vec![Stage {
                        name: "build".into(),
                        action: Actor::Agent,
                        result_check: Check::Actor(Actor::Builtin(Builtin::Commits)),
                        fail_action: FailAction::Halt,
                        ff_only: false,
                    }],
                },
            ),
            (
                "release".to_owned(),
                Flow {
                    name: "release".into(),
                    stages: vec![Stage {
                        name: "build".into(),
                        action: Actor::Agent,
                        result_check: Check::Actor(Actor::Builtin(Builtin::Commits)),
                        fail_action: FailAction::Halt,
                        ff_only: false,
                    }],
                },
            ),
        ])
    }

    fn ticket(frontmatter: &str, body: &str) -> String {
        format!("---\nname: Test ticket\nblocked_by: []\n{frontmatter}---\n{body}")
    }

    fn agent() -> AgentConfig {
        AgentConfig {
            default_target: "claude".into(),
            targets: BTreeMap::from([
                (
                    "claude".into(),
                    AgentTarget {
                        cmd: vec!["claude".into(), "{prompt}".into()],
                        model: None,
                        effort: None,
                    },
                ),
                (
                    "codex".into(),
                    AgentTarget {
                        cmd: vec![
                            "codex".into(),
                            "{model}".into(),
                            "{effort}".into(),
                            "{prompt}".into(),
                        ],
                        model: None,
                        effort: None,
                    },
                ),
            ]),
        }
    }

    /// Drops a ticket into a state a post cannot leave, the way a settled run
    /// would. Going through the run machinery here would say nothing extra
    /// about `post`.
    fn settle(store: &LocalSqlite, id: &str, state: &str) {
        let changed = store
            .db()
            .lock()
            .execute(
                "UPDATE tickets SET state = ?2 WHERE id = ?1",
                rusqlite::params![id, state],
            )
            .unwrap();
        assert_eq!(changed, 1);
    }

    #[test]
    fn reposting_a_settled_ticket_refreshes_content_without_queuing_an_trigger() {
        for state in ["merged", "failed", "needs_review"] {
            let (root, store) = world();
            let relative = ".agents/sloop/tickets/settled.md";
            let path = root.path().join(relative);
            std::fs::write(&path, ticket("", "# Original\n")).unwrap();
            handle(
                root.path(),
                &store,
                &post(relative, PostTrigger::Manual),
                2_000,
                "TICK",
                None,
                &flows(),
                "default",
            )
            .unwrap();
            settle(&store, "TICK-1", state);
            let stamped = std::fs::read_to_string(&path).unwrap();
            std::fs::write(&path, stamped.replace("# Original", "# Edited")).unwrap();

            let response = handle(
                root.path(),
                &store,
                &post(relative, PostTrigger::Auto),
                3_000,
                "TICK",
                None,
                &flows(),
                "default",
            )
            .unwrap();

            // The edit lands; only the trigger is withheld.
            assert_eq!(response["ticket"]["id"], "TICK-1");
            assert_eq!(response["created"], false);
            assert_eq!(
                response["ticket"]["state"], state,
                "a repost must not resurrect a {state} ticket"
            );
            assert!(
                store
                    .ticket("TICK-1")
                    .unwrap()
                    .unwrap()
                    .body
                    .unwrap()
                    .contains("# Edited")
            );
            assert!(response["trigger"].is_null());
            assert_eq!(
                response["trigger_suppressed"],
                serde_json::json!({"reason": "terminal_ticket", "state": state})
            );
            assert!(store.queued_triggers().unwrap().is_empty());
        }
    }

    #[test]
    fn reposting_a_settled_ticket_with_at_neither_creates_nor_reschedules_an_trigger() {
        let (root, store) = world();
        let relative = ".agents/sloop/tickets/timed.md";
        std::fs::write(root.path().join(relative), ticket("", "# Timed\n")).unwrap();
        let args = post(
            relative,
            PostTrigger::At {
                time: "03:00".into(),
            },
        );
        let first = handle_at(root.path(), &store, &args, 2_000, 10_000).unwrap();
        assert_eq!(first["trigger"]["eligible_at_ms"], 10_000);
        settle(&store, "TICK-1", "merged");

        let second = handle_at(root.path(), &store, &args, 3_000, 20_000).unwrap();

        assert!(second["trigger"].is_null());
        assert_eq!(second["trigger_suppressed"]["state"], "merged");
        // The trigger left over from before the merge keeps its original
        // time: the reschedule branch must not run for a settled ticket.
        let queued = store.queued_triggers().unwrap();
        assert_eq!(queued.len(), 1);
        assert_eq!(queued[0].eligible_at_ms, Some(10_000));
    }

    #[test]
    fn posting_twice_reuses_the_registration_and_trigger() {
        let (root, store) = world();
        std::fs::write(
            root.path().join(".agents/sloop/tickets/cooldown.md"),
            ticket("", "# Cooldowns\n"),
        )
        .unwrap();
        let args = post(".agents/sloop/tickets/cooldown.md", PostTrigger::Auto);

        let first = handle(
            root.path(),
            &store,
            &args,
            2_000,
            "TICK",
            None,
            &flows(),
            "default",
        )
        .unwrap();
        let second = handle(
            root.path(),
            &store,
            &args,
            3_000,
            "TICK",
            None,
            &flows(),
            "default",
        )
        .unwrap();
        assert_eq!(first["ticket"]["id"], second["ticket"]["id"]);
        assert_eq!(first["trigger"]["id"], second["trigger"]["id"]);
        let db = store.db();
        let connection = db.lock();
        let tickets: i64 = connection
            .query_row("SELECT COUNT(*) FROM tickets", [], |row| row.get(0))
            .unwrap();
        let triggers: i64 = connection
            .query_row("SELECT COUNT(*) FROM triggers", [], |row| row.get(0))
            .unwrap();
        assert_eq!(tickets, 1);
        assert_eq!(triggers, 1);
    }

    #[test]
    fn stale_source_version_rejects_update_without_clobbering_the_file() {
        let (root, store) = world();
        let relative = ".agents/sloop/tickets/cas.md";
        let path = root.path().join(relative);
        std::fs::write(&path, ticket("", "# Original\n")).unwrap();
        handle(
            root.path(),
            &store,
            &post(relative, PostTrigger::Manual),
            2_000,
            "TICK",
            None,
            &flows(),
            "default",
        )
        .unwrap();
        let original = std::fs::read_to_string(&path).unwrap();
        let replacement = original.replace("name: Test ticket", "name: Replacement");
        let expected = source_version(&original);
        let external_edit = original.replace("# Original", "# External edit");
        std::fs::write(&path, &external_edit).unwrap();
        let author = MarkdownWorkStateAuthor {
            root: root.path(),
            file_path: relative,
            worktree: "cas",
            work_state: &store,
            original_content: &original,
            final_content: &replacement,
            original_version: expected.clone(),
            trigger: None,
            now_ms: 3_000,
            trigger_result: std::sync::Mutex::new(serde_json::Value::Null),
        };
        let content = WorkTicket {
            id: "TICK-1".into(),
            project_id: "default".into(),
            name: "Replacement".into(),
            body: "# Replacement\n".into(),
            state: WorkTicketState::Ready,
            blocked_by: Vec::new(),
            attempts: 0,
            hints: ExecutionHints {
                worktree: Some("sloop/TICK-1".into()),
                trigger_id: None,
                target: None,
                model: None,
                effort: None,
                flow: Some("default".into()),
            },
            version: source_version(&replacement),
        };
        let ticket_ref = TicketRef {
            id: content.id.clone(),
            source: "local".into(),
            source_ref: Some(relative.into()),
        };

        let error = tokio::runtime::Runtime::new()
            .unwrap()
            .block_on(author.update(&ticket_ref, &content, &expected))
            .unwrap_err();

        assert!(matches!(
            error,
            SourceError::Rejected { message } if message.contains("source version conflict")
        ));
        assert_eq!(std::fs::read_to_string(path).unwrap(), external_edit);
        assert_eq!(store.ticket("TICK-1").unwrap().unwrap().name, "Test ticket");
    }

    #[test]
    fn trigger_insert_failure_leaves_idless_file_and_database_unchanged() {
        let (root, store) = world();
        let relative = ".agents/sloop/tickets/fail.md";
        let path = root.path().join(relative);
        let original = ticket("", "# Failure\n");
        std::fs::write(&path, &original).unwrap();
        store
            .db()
            .lock()
            .execute_batch(
                "CREATE TRIGGER reject_trigger BEFORE INSERT ON triggers
                 BEGIN SELECT RAISE(ABORT, 'forced trigger failure'); END;",
            )
            .unwrap();

        let error = handle(
            root.path(),
            &store,
            &post(relative, PostTrigger::Auto),
            2_000,
            "TICK",
            None,
            &flows(),
            "default",
        )
        .unwrap_err();

        assert!(error.to_string().contains("forced trigger failure"));
        assert_eq!(std::fs::read_to_string(path).unwrap(), original);
        assert!(store.ticket_ids().unwrap().is_empty());
        assert!(store.queued_triggers().unwrap().is_empty());
        let next_ordinal: i64 = store
            .db()
            .lock()
            .query_row(
                "SELECT next_ordinal FROM id_counters WHERE kind = 'trigger'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(next_ordinal, 1);
    }

    #[test]
    fn posting_at_queues_a_timed_trigger_and_reposting_reschedules_it() {
        let (root, store) = world();
        std::fs::write(
            root.path().join(".agents/sloop/tickets/timed.md"),
            ticket("", "# Timed\n"),
        )
        .unwrap();
        let args = post(
            ".agents/sloop/tickets/timed.md",
            PostTrigger::At {
                time: "03:00".into(),
            },
        );

        let first = handle_at(root.path(), &store, &args, 2_000, 10_000).unwrap();
        assert_eq!(first["ticket"]["state"], "ready");
        assert_eq!(first["trigger"]["kind"], "at");
        assert_eq!(first["trigger"]["eligible_at_ms"], 10_000);

        let second = handle_at(root.path(), &store, &args, 3_000, 20_000).unwrap();
        assert_eq!(second["trigger"]["id"], first["trigger"]["id"]);
        assert_eq!(second["trigger"]["eligible_at_ms"], 20_000);

        let queued = store.queued_triggers().unwrap();
        assert_eq!(queued.len(), 1);
        assert_eq!(queued[0].eligible_at_ms, Some(20_000));
    }

    #[test]
    fn posting_snapshots_the_default_target_and_reposting_refreshes_execution_values() {
        let (root, store) = world();
        let path = root.path().join(".agents/sloop/tickets/work.md");
        std::fs::write(&path, ticket("model: sonnet\neffort: medium\n", "# Work\n")).unwrap();
        let args = post(".agents/sloop/tickets/work.md", PostTrigger::Manual);
        let agent = agent();

        let first = handle(
            root.path(),
            &store,
            &args,
            2_000,
            "TICK",
            Some(&agent),
            &flows(),
            "default",
        )
        .unwrap();
        assert_eq!(first["ticket"]["target"], "claude");

        std::fs::write(
            &path,
            ticket(
                "id: TICK-1\nproject: default\ntarget: codex\nmodel: o3\neffort: high\n",
                "# Work\n",
            ),
        )
        .unwrap();
        let second = handle(
            root.path(),
            &store,
            &args,
            3_000,
            "TICK",
            Some(&agent),
            &flows(),
            "default",
        )
        .unwrap();
        assert_eq!(second["ticket"]["id"], first["ticket"]["id"]);
        assert_eq!(second["ticket"]["target"], "codex");
        assert_eq!(second["ticket"]["model"], "o3");
        assert_eq!(second["ticket"]["effort"], "high");
    }

    #[test]
    fn unknown_targets_are_rejected_before_registration_or_trigger() {
        let (root, store) = world();
        std::fs::write(
            root.path().join(".agents/sloop/tickets/work.md"),
            ticket("target: missing\n", "# Work\n"),
        )
        .unwrap();
        let args = post(".agents/sloop/tickets/work.md", PostTrigger::Auto);

        assert!(matches!(
            handle(root.path(), &store, &args, 2_000, "TICK", Some(&agent()), &flows(), "default"),
            Err(PostError::UnknownTarget(target)) if target == "missing"
        ));
        assert!(store.ticket_ids().unwrap().is_empty());
        assert!(store.queued_triggers().unwrap().is_empty());
    }

    #[test]
    fn selected_target_placeholders_require_ticket_values_before_registration() {
        let (root, store) = world();
        std::fs::write(
            root.path().join(".agents/sloop/tickets/work.md"),
            ticket("target: codex\neffort: high\n", "# Work\n"),
        )
        .unwrap();
        let args = post(".agents/sloop/tickets/work.md", PostTrigger::Manual);

        let error = handle(
            root.path(),
            &store,
            &args,
            2_000,
            "TICK",
            Some(&agent()),
            &flows(),
            "default",
        )
        .unwrap_err()
        .to_string();
        assert!(error.contains("agent target `codex`"), "{error}");
        assert!(error.contains("does not specify `model`"), "{error}");
        assert!(store.ticket_ids().unwrap().is_empty());
    }

    #[test]
    fn a_stamped_project_mismatching_the_request_is_a_conflict() {
        let (root, store) = world();
        std::fs::write(
            root.path().join(".agents/sloop/tickets/t.md"),
            ticket("id: T1\nproject: default\n", "# Work\n"),
        )
        .unwrap();
        let args = PostArgs {
            file: ".agents/sloop/tickets/t.md".into(),
            project: Some("other".into()),
            flow: None,
            trigger: PostTrigger::Manual,
        };

        assert!(matches!(
            handle(
                root.path(),
                &store,
                &args,
                2_000,
                "TICK",
                None,
                &flows(),
                "default"
            ),
            Err(PostError::ProjectConflict { .. })
        ));
    }

    #[test]
    fn an_unknown_project_is_rejected() {
        let (root, store) = world();
        std::fs::write(
            root.path().join(".agents/sloop/tickets/t.md"),
            ticket("", "# T\n"),
        )
        .unwrap();
        let args = PostArgs {
            file: ".agents/sloop/tickets/t.md".into(),
            project: Some("missing".into()),
            flow: None,
            trigger: PostTrigger::Manual,
        };

        assert!(matches!(
            handle(root.path(), &store, &args, 2_000, "TICK", None, &flows(), "default"),
            Err(PostError::UnknownProject(project)) if project == "missing"
        ));
    }

    #[test]
    fn a_missing_flow_is_stamped_with_the_default() {
        let (root, store) = world();
        let path = root.path().join(".agents/sloop/tickets/t.md");
        std::fs::write(&path, ticket("", "# T\n")).unwrap();
        let args = post(".agents/sloop/tickets/t.md", PostTrigger::Manual);

        let response = handle(
            root.path(),
            &store,
            &args,
            2_000,
            "TICK",
            None,
            &flows(),
            "default",
        )
        .unwrap();

        assert_eq!(response["ticket"]["flow"], "default");
        assert!(
            std::fs::read_to_string(&path)
                .unwrap()
                .contains("flow: default")
        );
    }

    #[test]
    fn an_explicit_flow_is_honored() {
        let (root, store) = world();
        std::fs::write(
            root.path().join(".agents/sloop/tickets/t.md"),
            ticket("flow: release\n", "# T\n"),
        )
        .unwrap();
        let args = post(".agents/sloop/tickets/t.md", PostTrigger::Manual);

        let response = handle(
            root.path(),
            &store,
            &args,
            2_000,
            "TICK",
            None,
            &flows(),
            "default",
        )
        .unwrap();

        assert_eq!(response["ticket"]["flow"], "release");
    }

    #[test]
    fn a_stamped_flow_mismatching_the_request_is_a_conflict() {
        let (root, store) = world();
        std::fs::write(
            root.path().join(".agents/sloop/tickets/t.md"),
            ticket("flow: release\n", "# T\n"),
        )
        .unwrap();
        let args = PostArgs {
            file: ".agents/sloop/tickets/t.md".into(),
            project: None,
            flow: Some("default".into()),
            trigger: PostTrigger::Manual,
        };

        assert!(matches!(
            handle(
                root.path(),
                &store,
                &args,
                2_000,
                "TICK",
                None,
                &flows(),
                "default"
            ),
            Err(PostError::FlowConflict { .. })
        ));
    }

    #[test]
    fn an_unknown_flow_is_rejected_and_names_known_flows() {
        let (root, store) = world();
        std::fs::write(
            root.path().join(".agents/sloop/tickets/t.md"),
            ticket("flow: bogus\n", "# T\n"),
        )
        .unwrap();
        let args = post(".agents/sloop/tickets/t.md", PostTrigger::Manual);

        let error = handle(
            root.path(),
            &store,
            &args,
            2_000,
            "TICK",
            None,
            &flows(),
            "default",
        )
        .unwrap_err()
        .to_string();
        assert!(error.contains("bogus"), "{error}");
        assert!(error.contains("default"), "{error}");
        assert!(error.contains("release"), "{error}");
        assert!(store.ticket_ids().unwrap().is_empty());
    }

    #[test]
    fn reindex_recovers_the_flow_binding_from_frontmatter_into_a_fresh_store() {
        let (root, store) = world();
        std::fs::write(
            root.path().join(".agents/sloop/tickets/t.md"),
            ticket("", "# T\n"),
        )
        .unwrap();
        let args = post(".agents/sloop/tickets/t.md", PostTrigger::Manual);
        handle(
            root.path(),
            &store,
            &args,
            2_000,
            "TICK",
            None,
            &flows(),
            "default",
        )
        .unwrap();
        drop(store);

        // A fresh store with no rows of its own must recover the flow binding
        // purely from the committed frontmatter that the first post stamped.
        let fresh_store =
            LocalSqlite::from_db(Db::open(&root.path().join("fresh.db"), 3_000).unwrap());
        fresh_store
            .upsert_local_project(
                "default",
                ".agents/sloop/projects/default.md",
                "Default",
                3_000,
            )
            .unwrap();
        let response = handle(
            root.path(),
            &fresh_store,
            &args,
            3_000,
            "TICK",
            None,
            &flows(),
            "default",
        )
        .unwrap();

        assert_eq!(response["ticket"]["id"], "TICK-1");
        assert_eq!(response["ticket"]["flow"], "default");
    }

    #[test]
    fn idless_tickets_get_monotonic_generated_ids() {
        let (root, store) = world();
        std::fs::create_dir(root.path().join(".agents/sloop/tickets/nested")).unwrap();
        std::fs::write(
            root.path().join(".agents/sloop/tickets/fix.md"),
            ticket("", "# A\n"),
        )
        .unwrap();
        std::fs::write(
            root.path().join(".agents/sloop/tickets/nested/fix.md"),
            ticket("", "# B\n"),
        )
        .unwrap();

        let first = handle(
            root.path(),
            &store,
            &post(".agents/sloop/tickets/fix.md", PostTrigger::Manual),
            2_000,
            "TICK",
            None,
            &flows(),
            "default",
        )
        .unwrap();
        let second = handle(
            root.path(),
            &store,
            &post(".agents/sloop/tickets/nested/fix.md", PostTrigger::Manual),
            2_100,
            "TICK",
            None,
            &flows(),
            "default",
        )
        .unwrap();
        assert_eq!(first["ticket"]["id"], "TICK-1");
        assert_eq!(second["ticket"]["id"], "TICK-2");
    }

    #[test]
    fn configured_prefix_and_explicit_high_water_mark_control_allocation() {
        let (root, store) = world();
        let explicit = root.path().join(".agents/sloop/tickets/explicit.md");
        let explicit_content = ticket(
            "id: WORK-9\nproject: default\nworktree: custom/work\nflow: default\n",
            "# Explicit\n",
        );
        std::fs::write(&explicit, &explicit_content).unwrap();
        handle(
            root.path(),
            &store,
            &post(".agents/sloop/tickets/explicit.md", PostTrigger::Manual),
            2_000,
            "WORK",
            None,
            &flows(),
            "default",
        )
        .unwrap();
        assert_eq!(std::fs::read_to_string(explicit).unwrap(), explicit_content);

        std::fs::write(
            root.path().join(".agents/sloop/tickets/unrelated.md"),
            ticket("id: OTHER-100\nproject: default\n", "# Unrelated\n"),
        )
        .unwrap();
        handle(
            root.path(),
            &store,
            &post(".agents/sloop/tickets/unrelated.md", PostTrigger::Manual),
            2_100,
            "WORK",
            None,
            &flows(),
            "default",
        )
        .unwrap();

        std::fs::write(
            root.path().join(".agents/sloop/tickets/generated.md"),
            ticket("", "# Generated\n"),
        )
        .unwrap();
        let generated = handle(
            root.path(),
            &store,
            &post(".agents/sloop/tickets/generated.md", PostTrigger::Manual),
            2_200,
            "WORK",
            None,
            &flows(),
            "default",
        )
        .unwrap();
        assert_eq!(generated["ticket"]["id"], "WORK-10");
    }

    #[test]
    fn paths_escaping_the_repository_are_rejected() {
        let (root, store) = world();
        let args = post("../outside.md", PostTrigger::Manual);

        assert!(matches!(
            handle(
                root.path(),
                &store,
                &args,
                2_000,
                "TICK",
                None,
                &flows(),
                "default"
            ),
            Err(PostError::OutsideRepository(_))
        ));
    }

    /// The repository root is always canonical in production, so an absolute
    /// path reaching the same file through a symlink has to resolve to it too.
    /// This is the normal case on macOS, where the temporary directory these
    /// tests run in is itself reached through a link into `/private`.
    #[test]
    fn absolute_paths_through_a_symlinked_root_stay_inside_the_repository() {
        let (root, store) = world();
        let link = tempdir().unwrap();
        let linked_root = link.path().join("repository");
        std::os::unix::fs::symlink(root.path(), &linked_root).unwrap();

        let ticket = linked_root.join(".agents/sloop/tickets/linked.md");
        std::fs::write(&ticket, "---\nname: Linked\nblocked_by: []\n---\n\nBody\n").unwrap();

        let posted = handle(
            root.path(),
            &store,
            &post(ticket.to_str().unwrap(), PostTrigger::Manual),
            2_000,
            "TICK",
            None,
            &flows(),
            "default",
        )
        .unwrap();
        assert_eq!(posted["ticket"]["name"], "Linked");
    }

    /// A lexical check accepts a link sitting in the ticket directory and then
    /// reads whatever it points at. Containment is about the bytes that get
    /// read, so the target decides.
    #[test]
    fn ticket_files_symlinked_out_of_the_repository_are_rejected() {
        let (root, store) = world();
        let outside = tempdir().unwrap();
        let target = outside.path().join("elsewhere.md");
        std::fs::write(
            &target,
            "---\nname: Elsewhere\nblocked_by: []\n---\n\nBody\n",
        )
        .unwrap();
        std::os::unix::fs::symlink(&target, root.path().join(".agents/sloop/tickets/escape.md"))
            .unwrap();

        assert!(matches!(
            handle(
                root.path(),
                &store,
                &post(".agents/sloop/tickets/escape.md", PostTrigger::Manual),
                2_000,
                "TICK",
                None,
                &flows(),
                "default",
            ),
            Err(PostError::OutsideRepository(_))
        ));
    }

    /// Containment is decided before the file is read, so resolution must not
    /// turn a missing ticket into a containment failure.
    #[test]
    fn missing_ticket_files_inside_the_directory_still_report_not_found() {
        let (root, store) = world();

        assert!(matches!(
            handle(
                root.path(),
                &store,
                &post(".agents/sloop/tickets/absent.md", PostTrigger::Manual),
                2_000,
                "TICK",
                None,
                &flows(),
                "default",
            ),
            Err(PostError::TicketFileNotFound(_))
        ));
    }

    #[test]
    fn paths_outside_the_ticket_directory_are_rejected() {
        let (root, store) = world();
        std::fs::write(root.path().join("elsewhere.md"), "# Elsewhere\n").unwrap();

        assert!(matches!(
            handle(
                root.path(),
                &store,
                &post("elsewhere.md", PostTrigger::Manual),
                2_000,
                "TICK",
                None,
                &flows(),
                "default",
            ),
            Err(PostError::OutsideTicketDirectory { .. })
        ));
    }
}