sloop-daemon 0.5.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
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
use std::ffi::OsString;
use std::fmt;
use std::io::{BufRead, BufReader, Write};
use std::os::unix::net::UnixStream;
use std::path::PathBuf;
use std::process::ExitCode;
use std::str::FromStr;

use clap::error::{ContextKind, ContextValue, ErrorKind};
use clap::{
    ArgGroup, Args, ColorChoice, CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum,
};
use serde_json::json;

mod init;
mod render;
mod style;
mod templates;

use self::style::Style;
use self::templates::TemplateKind;
use crate::protocol::{
    ConfidenceValue, EmptyArgs, ErrorBody, ErrorCode, EventsArgs, ListArgs, LogsArgs, NoteArgs,
    PostArgs, PostTrigger, Request, RequestEnvelope, RequestId, ResponseEnvelope, RunArgs,
    RunReferenceArgs, RunTrigger, ShowArgs, StopArgs, TicketReferenceArgs, VerdictArgs,
    VerdictValue,
};

/// `ready` is the line people misread: it is a precondition, not a promise.
/// Nothing dispatches until a trigger is queued for the ticket, so the state
/// says that before it says anything else.
const TICKET_STATES_HELP: &str = "Ticket states:
  ready         Nothing is stopping it - but it runs only once a trigger is
                queued for it and the gates are open. `sloop run` queues one.
  held          Prevented from running by an operator; release with `sloop ready`.
  blocked       Waiting for every ticket in `blocked_by` to be merged.
  claimed       Owned by an active run, including recovery.
  merged        Terminal: completed work was integrated into the default branch.
  failed        Terminal: the run did not succeed; `sloop retry` returns it to
                ready, and `sloop run` is what starts it again.
  needs_review  Terminal: the run could not be merged; inspect manually.";

const SHOW_LONG_ABOUT: &str =
    "Show the daemon, tickets, runs, and projects - sloop's one read verb.

REF_OR_PATTERN is resolved in this order; first match wins:

  1. nothing       -> the dashboard: daemon state plus recent tickets
  2. an exact ref  -> the full detail view for that thing
  3. anything else -> a filter: matching tickets, newest first

A ref is an exact ticket id (TICK-12), run alias (TICK-12-r1), run-id prefix
(749048f4), ticket name, or project id. An exact match always wins over pattern
interpretation.

A pattern matches ticket ids and names case-insensitively. Plain text is a
substring; regex metacharacters make it an unanchored regex, like grep. Quote
regexes in your shell: 'log.*'. A pattern always renders the list view, even
when it matches one ticket.

A run's detail is its stage table: one row per stage execution, suffixed `#N`
past the first attempt, with advisory failures marked `advisory` and any
panel's seats listed under their stage. `sloop logs <run> --stage <name>#<N>`
reads the output behind one of those rows.

--follow streams events for the shown scope. Ticket and run scopes exit when
they settle; dashboard, pattern, and project scopes run until interrupted.
--follow --quiet suppresses the stream and only returns the outcome.

EXIT CODES:
  0  shown successfully, or followed scope merged
  1  followed scope reached any other terminal outcome, or daemon error
  2  usage error, invalid pattern, or deprecated wait-alias timeout";

const SHOW_EXAMPLES: &str = "Examples:
  sloop show                      dashboard: daemon plus recent tickets
  sloop show -5                   dashboard with the 5 newest tickets
  sloop show TICK-12              everything about one ticket, including runs
  sloop show verdict              tickets mentioning \"verdict\"
  sloop show 'flow|merge' -5      5 newest tickets matching a regex
  sloop show TICK-12 --follow     watch a ticket until it settles
  sloop show TICK-12 -f -q        block silently; exit code is the outcome";

#[derive(Debug, Parser)]
#[command(
    name = "sloop",
    version,
    about = "Schedule coding agents",
    color = ColorChoice::Never
)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Option<Command>,
    /// Emit JSON envelopes instead of human-readable output.
    #[arg(long, global = true)]
    pub json: bool,
}

/// How responses are written. Envelopes are always produced internally;
/// `Human` translates them at the final write, carrying the styling decided
/// once here at the top level. `Json` has no style: an envelope is parsed,
/// never read, so it never carries an escape sequence.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OutputMode {
    Json,
    Human(Style),
}

#[derive(Debug, Subcommand)]
pub enum Command {
    /// Scaffold a Sloop project.
    Init,
    /// Print a commented canonical template for a file you author.
    ///
    /// Static compiled-in content: no daemon is contacted or started, and
    /// nothing is written. Redirect it where you want the file, for example
    /// `sloop template ticket > .agents/sloop/tickets/my-ticket.md`.
    Template {
        /// The file kind to print.
        #[arg(value_name = "KIND")]
        kind: TemplateKind,
    },
    /// Ensure the daemon is running.
    Daemon(DaemonCliArgs),
    /// Register a ticket file.
    Post(PostCliArgs),
    /// Enqueue a run.
    #[command(hide = true)]
    Run(RunCliArgs),
    /// Make a failed ticket ready to run again.
    #[command(hide = true)]
    Retry { ticket: String },
    /// Prevent a ready ticket from being dispatched.
    #[command(hide = true)]
    Hold { ticket: String },
    /// Release a held ticket for dispatch.
    #[command(hide = true)]
    Ready { ticket: String },
    /// List ticket names, states, and why they are not running.
    ///
    /// Tickets are ordered by registration time, newest first, whatever their
    /// state. Pass `--limit <N>`, `-n <N>`, or the `tail`-style shorthand
    /// `-<N>` to see only the N newest.
    #[command(hide = true)]
    List(ListCliArgs),
    /// Show daemon state.
    #[command(hide = true)]
    Status,
    /// Stop spawning new agents.
    #[command(hide = true)]
    Pause,
    /// Resume spawning agents.
    #[command(hide = true)]
    Resume,
    /// Stop the daemon.
    #[command(hide = true)]
    Stop {
        /// Cancel active runs instead of refusing to stop.
        #[arg(long)]
        force: bool,
    },
    /// Cancel a run and preserve its worktree.
    #[command(hide = true)]
    Cancel {
        /// Run alias, ticket reference, or run-id prefix.
        run: String,
    },
    /// Show daemon state, details, or filtered tickets; optionally follow live.
    #[command(
        about = "Show daemon state, details, or filtered tickets; optionally follow live",
        long_about = SHOW_LONG_ABOUT,
        after_help = SHOW_EXAMPLES
    )]
    Show(ShowCliArgs),
    /// Show output from a run.
    #[command(
        long_about = LOGS_LONG_ABOUT,
        after_help = "See `sloop show --help` for derived state and live activity."
    )]
    Logs {
        /// Run alias, ticket reference, or run-id prefix.
        run: String,
        /// Show only output captured by this stage: `<stage>`, or
        /// `<stage>#<attempt>` for one execution of a re-run stage.
        #[arg(long, value_name = "STAGE[#ATTEMPT]")]
        stage: Option<String>,
        /// Show the last N matching entries instead of the default 64.
        #[arg(long, value_name = "N")]
        tail: Option<u32>,
        /// Stream new output until the run reaches a terminal state.
        #[arg(long)]
        follow: bool,
    },
    /// Follow ticket and run activity as it happens.
    ///
    /// With no reference every event in the repository is streamed. With one,
    /// only events belonging to that scope are: a ticket covers the ticket and
    /// all of its runs, a project covers its tickets and their runs, and a run
    /// covers just that run. Repository-wide events, such as a daemon drain,
    /// belong to no scope and are streamed only by a bare `sloop watch`. An
    /// unknown reference fails immediately rather than streaming nothing.
    #[command(hide = true)]
    Watch {
        /// Ticket id or name, run alias or id prefix, or project id to scope to.
        r#ref: Option<String>,
        /// Number of recent events to show before following.
        #[arg(long, default_value_t = 20)]
        tail: u32,
    },
    /// Block until a run reaches a terminal state.
    #[command(hide = true)]
    Wait {
        /// Run alias, ticket reference, or run-id prefix.
        run: String,
        /// Give up after this many seconds.
        #[arg(long, default_value_t = 3600)]
        timeout: u64,
    },
    /// Rebuild local state from committed files and Git.
    #[command(hide = true)]
    Reindex,
    /// Show the current worker's assignment.
    #[command(hide = true)]
    Brief,
    /// Append an advisory note to the current run.
    #[command(hide = true)]
    Note {
        /// The note. It records an observation and moves nothing: no note
        /// passes a stage, and a stage's verdict comes from its result check.
        #[arg(required = true, trailing_var_arg = true, value_name = "TEXT")]
        text: Vec<String>,
    },
    /// Report the current stage's verdict.
    #[command(hide = true, long_about = VERDICT_LONG_ABOUT)]
    Verdict {
        /// `pass` or `fail`. The first report is final.
        verdict: VerdictCliValue,
        /// Why. Optional on a `reported` stage, required from a panel
        /// reviewer, and read by whoever opens `sloop show` next.
        #[arg(long, value_name = "TEXT")]
        reason: Option<String>,
        /// How sure you are. Defaults to `medium`; only ever recorded as
        /// evidence, never weighted into a panel's aggregation.
        #[arg(long)]
        confidence: Option<ConfidenceCliValue>,
    },
}

/// `verdict` is the only worker verb that moves a run, so its help says who is
/// allowed to call it before it says how. An agent that reports on a stage
/// which never asked for a report gets a denial, not a recorded verdict.
const VERDICT_LONG_ABOUT: &str = "\
Report the current stage's verdict.

Two callers may use it, each exactly once per stage execution:

  - the worker on a stage whose flow declares `result_check: reported`. It
    is the only thing that can pass such a stage; one that exits without
    reporting fails with `no verdict reported`.
  - a panel reviewer, when the stage's check is `result_check: { panel: ... }`.
    Its credential names the seat the report lands on, so no argument chooses
    one, and `--reason` is required.

The first report for an execution is final; a second is refused. A `return_to`
edge that re-enters the stage starts a fresh execution, which is owed its own
report.

`--confidence` takes `low`, `medium`, or `high` and defaults to `medium`. It is
recorded as evidence and shown by `sloop show`, and is never weighted into a
panel's quorum: a `fail` at low confidence counts exactly as much as one at
high.";

/// The selector grammar is the whole reason this verb needs long help: a stage
/// a backward edge re-entered has more than one page of output under one name.
const LOGS_LONG_ABOUT: &str = "\
Show output from a run — stdout and stderr, in capture order.

A bare read shows the last 64 entries, the way `tail` does: on a live run that
is the part worth reading. `--tail N` widens or narrows that window, and
`--follow` streams the run from its first entry instead. Whenever a window
hides output, the last line of the page says so — a page that says nothing
showed everything.

`--stage` narrows to one stage, named exactly as its flow names it. Add
`#<attempt>` to narrow further to a single execution: `--stage build#2` is the
second pass a `return_to` edge sent the walk through, and `--stage build` is
every pass together. The suffix is the same label `sloop show` prints in its
stage table, so a row read there is a selector that can be pasted back.

A stage the run's flow does not define is an error listing the ones it does,
rather than an empty page.";

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum VerdictCliValue {
    Pass,
    Fail,
}

/// clap renders the variants as the accepted values, so `--confidence 0.8`
/// fails with the valid list rather than being rounded into one of them.
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum ConfidenceCliValue {
    Low,
    Medium,
    High,
}

#[derive(Debug, Args)]
pub struct DaemonCliArgs {
    #[command(subcommand)]
    action: Option<DaemonAction>,
    #[arg(long, hide = true)]
    foreground: bool,
}

#[derive(Debug, Subcommand)]
enum DaemonAction {
    /// Drain active runs and restart with the binary currently installed.
    Restart,
}

#[derive(Debug, Args)]
#[command(
    after_help = "Ticket files need `name`, `blocked_by`, and a non-empty body. Run \
`sloop template ticket` for a commented example of every frontmatter field, or \
`sloop template flow` for the flow grammar that `--flow` selects.",
    group(
        ArgGroup::new("trigger")
            .args(["auto", "at", "manual", "hold"])
            .multiple(false)
    )
)]
pub struct PostCliArgs {
    /// Markdown ticket to register.
    file: PathBuf,
    /// Project receiving the ticket; defaults to `default`.
    #[arg(long, value_name = "PROJECT")]
    project: Option<String>,
    /// Flow the ticket binds to; defaults to the repository's default flow.
    #[arg(long, value_name = "FLOW")]
    flow: Option<String>,
    /// Queue one run for the next available opportunity (default).
    #[arg(long)]
    auto: bool,
    /// Queue one run for the next occurrence of a local time.
    #[arg(long, value_name = "TIME")]
    at: Option<LocalTime>,
    /// Register the ticket without creating a run.
    #[arg(long)]
    manual: bool,
    /// Register the ticket as held without creating a run.
    #[arg(long)]
    hold: bool,
}

#[derive(Debug, Args)]
pub struct ListCliArgs {
    /// Show only the N newest tickets; `-<N>` is shorthand, as in `tail -10`.
    #[arg(long, short = 'n', value_name = "N", value_parser = clap::value_parser!(u32).range(1..))]
    limit: Option<u32>,
}

#[derive(Debug, Default, Args)]
pub struct ShowCliArgs {
    /// Exact reference or ticket pattern; exact match wins.
    #[arg(value_name = "REF_OR_PATTERN")]
    reference: Option<String>,
    /// Stream events; ticket and run scopes exit when settled.
    #[arg(long, short = 'f')]
    follow: bool,
    /// With --follow, suppress output and return only the outcome code.
    #[arg(long, short = 'q', requires = "follow")]
    quiet: bool,
    /// At most N rows in list-shaped output; `-<N>` is shorthand.
    #[arg(long, short = 'n', value_name = "N", value_parser = clap::value_parser!(u32).range(1..))]
    limit: Option<u32>,
}

#[derive(Debug, Args)]
#[command(group(
    ArgGroup::new("trigger")
        .args(["at", "every", "overnight"])
        .multiple(false)
))]
pub struct RunCliArgs {
    /// Run a specific ticket instead of selecting ready work.
    ticket: Option<String>,
    /// Select ready work from one project.
    #[arg(long, value_name = "PROJECT", conflicts_with = "ticket")]
    project: Option<String>,
    /// Start at a local time, such as 03:00.
    #[arg(long, value_name = "TIME")]
    at: Option<LocalTime>,
    /// Recur at an interval, such as 30m.
    #[arg(long, value_name = "DURATION")]
    every: Option<DurationMs>,
    /// Run according to the configured overnight window.
    #[arg(long)]
    overnight: bool,
    /// Restrict selection to the comma-separated ticket IDs.
    #[arg(long, value_delimiter = ',', value_name = "TICKETS")]
    only: Option<Vec<String>>,
}

impl Cli {
    pub fn into_request(self) -> Result<Request, RequestConstructionError> {
        self.command
            .ok_or_else(|| {
                RequestConstructionError(
                    "bare `sloop` prints help and has no daemon request".into(),
                )
            })?
            .try_into()
    }
}

/// Shared by the dispatch path and `into_request` so the two cannot disagree
/// about which end of the log a bare read anchors to.
///
/// A one-shot read tails: it answers what a run is doing now. `--follow` pages
/// forward from the first entry, so it must stay head-anchored. The default is
/// the client's; on the socket `tail: null` still means "from the cursor".
fn logs_args(run: String, stage: Option<String>, tail: Option<u32>, follow: bool) -> LogsArgs {
    LogsArgs {
        run,
        stage,
        tail: tail.or((!follow).then_some(crate::run_log::PAGE_LIMIT as u32)),
        after: None,
    }
}

impl TryFrom<Command> for Request {
    type Error = RequestConstructionError;

    fn try_from(command: Command) -> Result<Self, Self::Error> {
        let empty = EmptyArgs::default;
        Ok(match command {
            Command::Init => Self::Init(empty()),
            Command::Template { .. } => {
                return Err(RequestConstructionError(
                    "template is printed locally and has no daemon request".into(),
                ));
            }
            Command::Daemon(args) => match args.action {
                Some(DaemonAction::Restart) => Self::Restart(empty()),
                None => Self::Daemon(empty()),
            },
            Command::Post(args) => Self::Post(args.try_into()?),
            Command::Run(args) => Self::Run(args.into()),
            Command::Retry { ticket } => Self::Retry(TicketReferenceArgs { ticket }),
            Command::Hold { ticket } => Self::Hold(TicketReferenceArgs { ticket }),
            Command::Ready { ticket } => Self::Ready(TicketReferenceArgs { ticket }),
            Command::List(args) => Self::List(ListArgs { limit: args.limit }),
            Command::Status => Self::Status(empty()),
            Command::Pause => Self::Pause(empty()),
            Command::Resume => Self::Resume(empty()),
            Command::Stop { force } => Self::Stop(StopArgs { force }),
            Command::Cancel { run } => Self::Cancel(RunReferenceArgs { run }),
            Command::Logs {
                run,
                stage,
                tail,
                follow,
            } => Self::Logs(logs_args(run, stage, tail, follow)),
            Command::Watch { r#ref, tail } => Self::Events(EventsArgs {
                after: None,
                tail: Some(tail),
                limit: None,
                scope: r#ref,
            }),
            Command::Wait { run, .. } => Self::Wait(RunReferenceArgs { run }),
            Command::Reindex => Self::Reindex(empty()),
            Command::Brief => Self::Brief(empty()),
            Command::Show(args) => Self::Show(ShowArgs {
                reference: args.reference,
                limit: args.limit,
            }),
            Command::Note { text } => Self::Note(NoteArgs {
                text: text.join(" "),
            }),
            Command::Verdict {
                verdict,
                reason,
                confidence,
            } => Self::Verdict(VerdictArgs {
                verdict: match verdict {
                    VerdictCliValue::Pass => VerdictValue::Pass,
                    VerdictCliValue::Fail => VerdictValue::Fail,
                },
                reason,
                confidence: confidence.map(|confidence| match confidence {
                    ConfidenceCliValue::Low => ConfidenceValue::Low,
                    ConfidenceCliValue::Medium => ConfidenceValue::Medium,
                    ConfidenceCliValue::High => ConfidenceValue::High,
                }),
            }),
        })
    }
}

impl TryFrom<PostCliArgs> for PostArgs {
    type Error = RequestConstructionError;

    fn try_from(args: PostCliArgs) -> Result<Self, Self::Error> {
        let file = args
            .file
            .into_os_string()
            .into_string()
            .map_err(|_| RequestConstructionError("ticket path must be valid UTF-8".into()))?;
        let trigger = if let Some(time) = args.at {
            PostTrigger::At { time: time.0 }
        } else if args.manual {
            PostTrigger::Manual
        } else if args.hold {
            PostTrigger::Hold
        } else {
            PostTrigger::Auto
        };

        Ok(Self {
            file,
            project: args.project,
            flow: args.flow,
            trigger,
        })
    }
}

impl From<RunCliArgs> for RunArgs {
    fn from(args: RunCliArgs) -> Self {
        let trigger = if let Some(time) = args.at {
            RunTrigger::At { local_time: time.0 }
        } else if let Some(interval) = args.every {
            RunTrigger::Every {
                interval_ms: interval.0,
            }
        } else if args.overnight {
            RunTrigger::Overnight
        } else {
            RunTrigger::Now
        };

        Self {
            ticket: args.ticket,
            project: args.project,
            trigger,
            only: args.only.unwrap_or_default(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RequestConstructionError(String);

impl fmt::Display for RequestConstructionError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.0)
    }
}

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

#[derive(Debug, Clone)]
struct LocalTime(String);

impl FromStr for LocalTime {
    type Err = String;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let (hour, minute) = value
            .split_once(':')
            .ok_or_else(|| "time must use HH:MM".to_owned())?;
        if hour.len() != 2 || minute.len() != 2 {
            return Err("time must use HH:MM".into());
        }
        let hour: u8 = hour.parse().map_err(|_| "hour must be numeric")?;
        let minute: u8 = minute.parse().map_err(|_| "minute must be numeric")?;
        if hour > 23 || minute > 59 {
            return Err("time must be between 00:00 and 23:59".into());
        }
        Ok(Self(value.to_owned()))
    }
}

#[derive(Debug, Clone, Copy)]
struct DurationMs(u64);

impl FromStr for DurationMs {
    type Err = String;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let digits = value.chars().take_while(char::is_ascii_digit).count();
        let (amount, unit) = value.split_at(digits);
        if amount.is_empty() || unit.is_empty() {
            return Err("duration must include a positive number and unit (ms, s, m, or h)".into());
        }
        let amount: u64 = amount
            .parse()
            .map_err(|_| "duration amount is too large".to_owned())?;
        if amount == 0 {
            return Err("duration must be greater than zero".into());
        }
        let multiplier = match unit {
            "ms" => 1,
            "s" => 1_000,
            "m" => 60_000,
            "h" => 3_600_000,
            _ => return Err("duration unit must be ms, s, m, or h".into()),
        };
        amount
            .checked_mul(multiplier)
            .map(Self)
            .ok_or_else(|| "duration is too large".into())
    }
}

pub fn run<I, T, O, E>(args: I, stdout: &mut O, stderr: &mut E) -> ExitCode
where
    I: IntoIterator<Item = T>,
    T: Into<OsString> + Clone,
    O: Write,
    E: Write,
{
    let mut args: Vec<OsString> = args.into_iter().map(Into::into).collect();
    let expanded_help = args.iter().any(|arg| arg == "--all")
        && args
            .iter()
            .any(|arg| arg == "--help" || arg == "-h" || arg == "help");
    if expanded_help {
        args.retain(|arg| arg != "--all");
    }
    expand_limit_shorthand(&mut args);

    let mut command = Cli::command();
    if expanded_help {
        let subcommands: Vec<String> = command
            .get_subcommands()
            .map(|subcommand| subcommand.get_name().to_owned())
            .collect();
        for subcommand in subcommands {
            command = command.mut_subcommand(subcommand, |subcommand| subcommand.hide(false));
        }
        command = command.after_help(TICKET_STATES_HELP);
    } else {
        command = command.after_help(
            "Read state with `sloop show` and raw output with `sloop logs`.\nRun `sloop show --help` for the complete read model or `sloop --help --all` for every command.",
        );
    }

    match command
        .clone()
        .try_get_matches_from(&args)
        .and_then(|matches| Cli::from_arg_matches(&matches))
    {
        Ok(cli) => {
            let mode = if cli.json {
                OutputMode::Json
            } else {
                OutputMode::Human(Style::detect())
            };
            match cli.command {
                Some(subcommand) => run_command(subcommand, mode, stdout, stderr),
                None => {
                    let help = command.render_help().to_string();
                    let help = help.trim_end();
                    write_plain_or(
                        mode,
                        stdout,
                        help,
                        &ResponseEnvelope::success(None, json!({"kind": "help", "text": help})),
                    )
                }
            }
        }
        Err(error) => {
            let mode = if args.iter().any(|arg| arg == "--json") {
                OutputMode::Json
            } else {
                OutputMode::Human(Style::detect())
            };
            match error.kind() {
                ErrorKind::DisplayHelp => write_plain_or(
                    mode,
                    stdout,
                    error.to_string().trim_end(),
                    &ResponseEnvelope::success(
                        None,
                        json!({"kind": "help", "text": error.to_string().trim_end()}),
                    ),
                ),
                ErrorKind::DisplayVersion => write_plain_or(
                    mode,
                    stdout,
                    concat!("sloop ", env!("CARGO_PKG_VERSION")),
                    &ResponseEnvelope::success(
                        None,
                        json!({"kind": "version", "version": env!("CARGO_PKG_VERSION")}),
                    ),
                ),
                _ => write_cli_error(
                    mode,
                    stderr,
                    augment_unknown_subcommand(&error, error.to_string().trim_end().to_owned()),
                ),
            }
        }
    }
}

/// Rewrites `sloop show -10` into `sloop show --limit=10`. clap lexes a bare
/// `-10` as the short flag `-1`, so the `head`/`tail` shorthand has to be
/// translated before parsing. Only arguments after a leading `show` or `list`
/// touched, so no other command can have a negative-looking value rewritten,
/// and only all-digit runs are: `-abc` and `-n` reach clap untouched and earn
/// its usage error. `-0` becomes `--limit=0`, which the parser's range rejects.
fn expand_limit_shorthand(args: &mut [OsString]) {
    let verb = args
        .iter()
        .skip(1)
        .position(|arg| arg != "--json")
        .map(|offset| offset + 1);
    let Some(verb) = verb.filter(|index| args[*index] == "show" || args[*index] == "list") else {
        return;
    };
    for argument in &mut args[verb + 1..] {
        let Some(digits) = argument.to_str().and_then(|arg| arg.strip_prefix('-')) else {
            continue;
        };
        if !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit()) {
            *argument = OsString::from(format!("--limit={digits}"));
        }
    }
}

/// Synonyms an agent is likely to type that clap's edit-distance matcher does
/// not catch, each mapped to the real verb it should have used. This is the one
/// place to add an alias; keep it small and keep every entry pointed at a verb
/// that exists. Suggestions are text only — nothing here executes.
fn subcommand_synonym(attempted: &str) -> Option<&'static str> {
    match attempted {
        "tickets" | "ls" | "queue" => Some("list"),
        "ps" => Some("status"),
        "start" => Some("run"),
        "kill" | "abort" => Some("cancel"),
        _ => None,
    }
}

/// Adds a remedy to clap's "unrecognized subcommand" error. clap already
/// appends a `tip:` line when the typo is a near-miss of a real verb, and that
/// text rides through the JSON envelope unchanged, so we leave those alone and
/// only fill the gap: when similarity matching finds nothing but our synonym
/// table does, point the caller at the verb they meant.
fn augment_unknown_subcommand(error: &clap::Error, rendered: String) -> String {
    if error.kind() != ErrorKind::InvalidSubcommand
        || error.get(ContextKind::SuggestedSubcommand).is_some()
    {
        return rendered;
    }
    let Some(attempted) = invalid_subcommand(error) else {
        return rendered;
    };
    let Some(verb) = subcommand_synonym(&attempted) else {
        return rendered;
    };
    let tip = format!(
        "\n\n  tip: `{attempted}` is not a verb; did you mean `{verb}`? run `sloop {verb}`"
    );
    match rendered.find("\n\nUsage:") {
        Some(index) => {
            let mut augmented = rendered;
            augmented.insert_str(index, &tip);
            augmented
        }
        None => rendered + &tip,
    }
}

fn invalid_subcommand(error: &clap::Error) -> Option<String> {
    match error.get(ContextKind::InvalidSubcommand) {
        Some(ContextValue::String(value)) => Some(value.clone()),
        _ => None,
    }
}

fn run_command(
    command: Command,
    mode: OutputMode,
    stdout: &mut impl Write,
    stderr: &mut impl Write,
) -> ExitCode {
    match command {
        Command::Init => run_init(mode, stdout, stderr),
        Command::Template { kind } => run_template(kind, mode, stdout),
        Command::Daemon(args) if args.foreground && args.action.is_none() => {
            match crate::daemon::serve_current_repository() {
                Ok(()) | Err(crate::daemon::DaemonError::AlreadyRunning) => ExitCode::SUCCESS,
                Err(_) => ExitCode::FAILURE,
            }
        }
        Command::Daemon(args) => {
            let (request, report_started) = match args.action {
                Some(DaemonAction::Restart) => (Request::Restart(EmptyArgs::default()), false),
                None => (Request::Daemon(EmptyArgs::default()), true),
            };
            run_daemon_request(request, report_started, mode, stdout, stderr)
        }
        Command::Stop { force } => run_stop_request(force, mode, stdout, stderr),
        Command::Wait { run, timeout } => {
            if !write_deprecation(stderr, "wait", "show --follow --quiet") {
                return ExitCode::FAILURE;
            }
            run_wait(run, timeout, mode, stdout, stderr)
        }
        Command::Watch { r#ref, tail } => {
            if !write_deprecation(stderr, "watch", "show --follow") {
                return ExitCode::FAILURE;
            }
            run_watch(r#ref, tail, mode, stdout, stderr)
        }
        Command::Logs {
            run,
            stage,
            tail,
            follow,
        } => run_logs(
            logs_args(run, stage, tail, follow),
            follow,
            mode,
            stdout,
            stderr,
        ),
        Command::List(args) => {
            if !write_deprecation(stderr, "list", "show") {
                return ExitCode::FAILURE;
            }
            run_daemon_request(
                Request::List(ListArgs { limit: args.limit }),
                false,
                mode,
                stdout,
                stderr,
            )
        }
        Command::Status => {
            if !write_deprecation(stderr, "status", "show") {
                return ExitCode::FAILURE;
            }
            run_show(ShowCliArgs::default(), mode, stdout, stderr)
        }
        Command::Show(args) => run_show(args, mode, stdout, stderr),
        command @ (Command::Post(_)
        | Command::Run(_)
        | Command::Retry { .. }
        | Command::Hold { .. }
        | Command::Ready { .. }
        | Command::Pause
        | Command::Resume
        | Command::Cancel { .. }
        | Command::Reindex) => match Request::try_from(command) {
            Ok(request) => run_daemon_request(request, false, mode, stdout, stderr),
            Err(error) => write_cli_error(mode, stderr, error.to_string()),
        },
        command @ (Command::Brief | Command::Note { .. } | Command::Verdict { .. }) => {
            match Request::try_from(command) {
                Ok(request) => run_worker_request(request, mode, stdout, stderr),
                Err(error) => write_cli_error(mode, stderr, error.to_string()),
            }
        }
    }
}

/// Writes plain text in human mode or the given envelope in JSON mode; used
/// for help and version, which have no verb-shaped payload.
fn write_plain_or(
    mode: OutputMode,
    output: &mut impl Write,
    text: &str,
    envelope: &ResponseEnvelope,
) -> ExitCode {
    match mode {
        OutputMode::Json => write_response(mode, None, output, envelope, ExitCode::SUCCESS),
        OutputMode::Human(_) => {
            if writeln!(output, "{text}").is_err() {
                return ExitCode::FAILURE;
            }
            ExitCode::SUCCESS
        }
    }
}

/// Prints a compiled-in template. Like `stop`, this verb never resurrects a
/// daemon — unlike `stop`, it never contacts one at all, because the answer
/// is static content baked into the binary. Plain mode writes the template
/// verbatim so it can be redirected straight into a file.
fn run_template(kind: TemplateKind, mode: OutputMode, stdout: &mut impl Write) -> ExitCode {
    let text = kind.text();
    match mode {
        OutputMode::Json => write_response(
            mode,
            Some("template"),
            stdout,
            &ResponseEnvelope::success(None, json!({"kind": kind.as_str(), "template": text})),
            ExitCode::SUCCESS,
        ),
        OutputMode::Human(_) => {
            if stdout.write_all(text.as_bytes()).is_err() {
                return ExitCode::FAILURE;
            }
            ExitCode::SUCCESS
        }
    }
}

fn run_init(mode: OutputMode, stdout: &mut impl Write, stderr: &mut impl Write) -> ExitCode {
    let cwd = match std::env::current_dir() {
        Ok(cwd) => cwd,
        Err(error) => {
            return write_response(
                mode,
                Some("init"),
                stderr,
                &ResponseEnvelope::failure(
                    None,
                    ErrorBody {
                        code: ErrorCode::Internal,
                        message: format!("cannot read current directory: {error}"),
                        details: json!({}),
                    },
                ),
                ExitCode::FAILURE,
            );
        }
    };
    match self::init::init(&cwd) {
        Ok(outcome) => write_response(
            mode,
            Some("init"),
            stdout,
            &ResponseEnvelope::success(
                None,
                json!({
                    "repository_root": outcome.repository_root.to_string_lossy(),
                    "created": outcome.created,
                    "existing": outcome.existing,
                }),
            ),
            ExitCode::SUCCESS,
        ),
        Err(error) => {
            let code = match error {
                self::init::InitError::Conflict { .. } => ErrorCode::Conflict,
                self::init::InitError::Io { .. } => ErrorCode::Internal,
            };
            write_response(
                mode,
                Some("init"),
                stderr,
                &ResponseEnvelope::failure(
                    None,
                    ErrorBody {
                        code,
                        message: error.to_string(),
                        details: json!({}),
                    },
                ),
                ExitCode::FAILURE,
            )
        }
    }
}

fn write_deprecation(stderr: &mut impl Write, old: &str, new: &str) -> bool {
    writeln!(
        stderr,
        "note: 'sloop {old}' is now 'sloop {new}'; this alias will be removed in a future release"
    )
    .is_ok()
}

fn run_show(
    args: ShowCliArgs,
    mode: OutputMode,
    stdout: &mut impl Write,
    stderr: &mut impl Write,
) -> ExitCode {
    let request_args = ShowArgs {
        reference: args.reference,
        limit: args.limit,
    };
    let worker_environment =
        std::env::var_os("SLOOP_SOCKET").is_some() || std::env::var_os("SLOOP_TOKEN").is_some();
    if worker_environment {
        if args.follow {
            return write_cli_error(
                mode,
                stderr,
                "workers cannot follow operator activity; worker `show` only reads its own ticket"
                    .into(),
            );
        }
        return run_worker_request(Request::Show(request_args), mode, stdout, stderr);
    }
    if args.follow {
        return follow_show(request_args, 20, None, args.quiet, mode, stdout, stderr);
    }
    match crate::daemon::request(Request::Show(request_args)) {
        Ok(result) if result.response.ok => write_response(
            mode,
            Some("show"),
            stdout,
            &result.response,
            ExitCode::SUCCESS,
        ),
        Ok(result) => {
            let exit = if result.response.error.as_ref().map(|error| error.code)
                == Some(ErrorCode::InvalidArguments)
            {
                ExitCode::from(2)
            } else {
                ExitCode::FAILURE
            };
            write_response(mode, Some("show"), stderr, &result.response, exit)
        }
        Err(error) => write_response(
            mode,
            Some("show"),
            stderr,
            &ResponseEnvelope::failure(None, error.error_body()),
            ExitCode::FAILURE,
        ),
    }
}

/// Polls the daemon until the run is terminal. The exit code is the outcome
/// (`0` only for `merged`), so scripts and CI can gate on a run directly.
/// Client-side wall-clock polling; the daemon stays stateless.
fn run_wait(
    run: String,
    timeout_secs: u64,
    mode: OutputMode,
    stdout: &mut impl Write,
    stderr: &mut impl Write,
) -> ExitCode {
    match crate::daemon::request(Request::Wait(RunReferenceArgs { run: run.clone() })) {
        Ok(result) if result.response.ok => {}
        Ok(result) => {
            return write_response(
                mode,
                Some("wait"),
                stderr,
                &result.response,
                ExitCode::FAILURE,
            );
        }
        Err(error) => {
            return write_response(
                mode,
                Some("wait"),
                stderr,
                &ResponseEnvelope::failure(None, error.error_body()),
                ExitCode::FAILURE,
            );
        }
    }
    follow_show(
        ShowArgs {
            reference: Some(run),
            limit: None,
        },
        0,
        Some(timeout_secs),
        true,
        mode,
        stdout,
        stderr,
    )
}

/// Follows the activity feed until interrupted. Same client-side polling
/// model as `wait`: each iteration asks the daemon for events past the
/// cursor from the previous page, so the daemon stays stateless and any
/// other client (a dashboard, a websocket bridge) can stream the same way.
/// In `--json` mode each event is written as one NDJSON line.
///
/// A `scope` reference rides along on every request and the daemon resolves
/// and applies it, so the filter stays part of the public protocol instead of
/// a CLI-only convenience. An unresolvable reference comes back as a
/// `not_found` failure on the very first request, before anything streams.
fn run_watch(
    scope: Option<String>,
    tail: u32,
    mode: OutputMode,
    stdout: &mut impl Write,
    stderr: &mut impl Write,
) -> ExitCode {
    follow_show(
        ShowArgs {
            reference: scope,
            limit: None,
        },
        tail,
        None,
        false,
        mode,
        stdout,
        stderr,
    )
}

fn follow_show(
    show: ShowArgs,
    tail: u32,
    timeout_secs: Option<u64>,
    quiet: bool,
    mode: OutputMode,
    stdout: &mut impl Write,
    stderr: &mut impl Write,
) -> ExitCode {
    let initial = match crate::daemon::request(Request::Show(show.clone())) {
        Ok(result) if result.response.ok => result.response.data.unwrap_or_default(),
        Ok(result) => {
            let exit = if result.response.error.as_ref().map(|error| error.code)
                == Some(ErrorCode::InvalidArguments)
            {
                ExitCode::from(2)
            } else {
                ExitCode::FAILURE
            };
            return write_response(mode, Some("show"), stderr, &result.response, exit);
        }
        Err(error) => {
            return write_response(
                mode,
                Some("show"),
                stderr,
                &ResponseEnvelope::failure(None, error.error_body()),
                ExitCode::FAILURE,
            );
        }
    };
    let settling_kind = matches!(initial["kind"].as_str(), Some("ticket" | "run"));
    let deadline = timeout_secs
        .map(|seconds| std::time::Instant::now() + std::time::Duration::from_secs(seconds));
    let mut cursor: Option<i64> = None;
    let mut settled_outcome: Option<bool> = None;
    loop {
        let args = match cursor {
            Some(after) => EventsArgs {
                after: Some(after),
                tail: None,
                limit: None,
                scope: show.reference.clone(),
            },
            None => EventsArgs {
                after: None,
                tail: Some(tail),
                limit: None,
                scope: show.reference.clone(),
            },
        };
        match crate::daemon::request(Request::Events(args)) {
            Ok(result) if result.response.ok => {
                let data = result.response.data.unwrap_or_default();
                let events = data["events"].as_array().cloned().unwrap_or_default();
                for event in &events {
                    if quiet {
                        continue;
                    }
                    let written = match mode {
                        OutputMode::Json => serde_json::to_writer(&mut *stdout, event)
                            .map_err(|_| ())
                            .and_then(|()| stdout.write_all(b"\n").map_err(|_| ())),
                        OutputMode::Human(_) => {
                            writeln!(stdout, "{}", format_event(event)).map_err(|_| ())
                        }
                    };
                    if written.is_err() {
                        return ExitCode::FAILURE;
                    }
                }
                if !quiet && stdout.flush().is_err() {
                    return ExitCode::FAILURE;
                }
                let next = data["next_cursor"].as_i64();
                let advanced = next.is_some() && next != cursor;
                if let Some(next) = next {
                    cursor = Some(next);
                }
                let caught_up = next == data["latest"].as_i64();
                if advanced && !caught_up {
                    continue;
                }
                if caught_up && let Some(merged) = settled_outcome {
                    return if merged {
                        ExitCode::SUCCESS
                    } else {
                        ExitCode::FAILURE
                    };
                }
                if settling_kind && caught_up {
                    match crate::daemon::request(Request::Show(show.clone())) {
                        Ok(result) if result.response.ok => {
                            let shown = result.response.data.unwrap_or_default();
                            let value = &shown["value"];
                            let terminal = match shown["kind"].as_str() {
                                Some("ticket") => matches!(
                                    value["state"].as_str(),
                                    Some("merged" | "failed" | "needs_review")
                                ),
                                Some("run") => value["terminal"] == json!(true),
                                _ => false,
                            };
                            if terminal {
                                settled_outcome = Some(value["state"] == "merged");
                                continue;
                            }
                        }
                        Ok(result) => {
                            return write_response(
                                mode,
                                Some("show"),
                                stderr,
                                &result.response,
                                ExitCode::FAILURE,
                            );
                        }
                        Err(error) => {
                            return write_response(
                                mode,
                                Some("show"),
                                stderr,
                                &ResponseEnvelope::failure(None, error.error_body()),
                                ExitCode::FAILURE,
                            );
                        }
                    }
                }
            }
            Ok(result) => {
                return write_response(
                    mode,
                    Some("show"),
                    stderr,
                    &result.response,
                    ExitCode::FAILURE,
                );
            }
            Err(error) => {
                return write_response(
                    mode,
                    Some("show"),
                    stderr,
                    &ResponseEnvelope::failure(None, error.error_body()),
                    ExitCode::FAILURE,
                );
            }
        }
        if deadline.is_some_and(|deadline| std::time::Instant::now() >= deadline) {
            let reference = show.reference.as_deref().unwrap_or("dashboard");
            return write_cli_error(mode, stderr, format!("timed out following `{reference}`"));
        }
        std::thread::sleep(std::time::Duration::from_millis(500));
    }
}

/// One page of captured output, or — with `--follow` — every page until the
/// run settles. Filtering is the daemon's job; the client only chooses when
/// to ask again.
fn run_logs(
    args: LogsArgs,
    follow: bool,
    mode: OutputMode,
    stdout: &mut impl Write,
    stderr: &mut impl Write,
) -> ExitCode {
    if !follow {
        return run_daemon_request(Request::Logs(args), false, mode, stdout, stderr);
    }
    follow_logs(args, mode, stdout, stderr)
}

/// Polls the daemon for pages past the cursor of the previous one, exactly
/// like `watch` does over the event feed. The daemon keeps no per-follower
/// state, so any other client can stream a run the same way.
///
/// A page is written when it carries entries, and once at the end so an empty
/// run still reports itself. Streaming stops only when the run is terminal
/// *and* the page reached the end of the log: a settled run can still have
/// unread output behind the cursor.
fn follow_logs(
    mut args: LogsArgs,
    mode: OutputMode,
    stdout: &mut impl Write,
    stderr: &mut impl Write,
) -> ExitCode {
    let mut written = false;
    loop {
        match crate::daemon::request(Request::Logs(args.clone())) {
            Ok(mut result) => {
                if !result.response.ok {
                    return write_response(
                        mode,
                        Some("logs"),
                        stderr,
                        &result.response,
                        ExitCode::FAILURE,
                    );
                }
                if written && let Some(data) = result.response.data.as_mut() {
                    data["note"] = serde_json::Value::Null;
                }
                let data = result.response.data.clone().unwrap_or_default();
                let complete = data["complete"] == json!(true);
                let settled = complete && data["terminal"] == json!(true);
                let entries = data["entries"].as_array().map_or(0, Vec::len);
                if entries > 0 || (settled && !written) {
                    if write_envelope(mode, Some("logs"), stdout, &result.response).is_err()
                        || stdout.flush().is_err()
                    {
                        return ExitCode::FAILURE;
                    }
                    written = true;
                }
                if let Some(next) = data["next_cursor"].as_u64() {
                    args.after = Some(next);
                }
                args.tail = None;
                if settled {
                    return ExitCode::SUCCESS;
                }
                if !complete {
                    continue;
                }
            }
            Err(error) => {
                return write_response(
                    mode,
                    Some("logs"),
                    stderr,
                    &ResponseEnvelope::failure(None, error.error_body()),
                    ExitCode::FAILURE,
                );
            }
        }
        std::thread::sleep(std::time::Duration::from_millis(200));
    }
}

/// Renders one activity event as a human `watch` line.
fn format_event(event: &serde_json::Value) -> String {
    let time = event["occurred_at_ms"]
        .as_i64()
        .and_then(crate::clock::format_timestamp)
        .unwrap_or_default();
    let run = event["run"].as_str().unwrap_or("?");
    let ticket = event["ticket"].as_str().unwrap_or("?");
    let data = &event["data"];
    match event["kind"].as_str().unwrap_or("?") {
        "run_claimed" => {
            let attempt = data["attempt"].as_i64().unwrap_or(1);
            format!("{time}  {ticket} claimed by {run} (attempt {attempt})")
        }
        "run_started" => format!("{time}  {run} started on {ticket}"),
        "run_finished" => {
            let outcome = data["outcome"].as_str().unwrap_or("?");
            let state = data["ticket_state"].as_str().unwrap_or("?");
            format!("{time}  {run} finished: {outcome} ({ticket} -> {state})")
        }
        "run_aborted" => format!("{time}  {run} aborted before launch ({ticket} back to ready)"),
        "run_worktree_cleaned" => format!("{time}  {run} worktree and branch removed"),
        "daemon_restart_requested" => {
            let active = data["active_runs"].as_u64().unwrap_or(0);
            let noun = if active == 1 { "run" } else { "runs" };
            format!("{time}  daemon draining for restart ({active} {noun} active)")
        }
        kind => format!("{time}  {kind} run={run} ticket={ticket}"),
    }
}

/// `stop` is the one operator verb that must never resurrect a daemon: an
/// unreachable socket already means the desired state.
fn run_stop_request(
    force: bool,
    mode: OutputMode,
    stdout: &mut impl Write,
    stderr: &mut impl Write,
) -> ExitCode {
    match crate::daemon::request_running(Request::Stop(StopArgs { force })) {
        Ok(Some(response)) if response.ok => {
            write_response(mode, Some("stop"), stdout, &response, ExitCode::SUCCESS)
        }
        Ok(Some(response)) => {
            write_response(mode, Some("stop"), stderr, &response, ExitCode::FAILURE)
        }
        Ok(None) => write_response(
            mode,
            Some("stop"),
            stdout,
            &ResponseEnvelope::success(None, json!({"stopping": false, "running": false})),
            ExitCode::SUCCESS,
        ),
        Err(error) => write_response(
            mode,
            Some("stop"),
            stderr,
            &ResponseEnvelope::failure(None, error.error_body()),
            ExitCode::FAILURE,
        ),
    }
}

fn run_daemon_request(
    request: Request,
    report_started: bool,
    mode: OutputMode,
    stdout: &mut impl Write,
    stderr: &mut impl Write,
) -> ExitCode {
    let verb = request.verb();
    match crate::daemon::request(request) {
        Ok(mut result) => {
            if report_started {
                let data = result
                    .response
                    .data
                    .as_mut()
                    .and_then(serde_json::Value::as_object_mut);
                if let Some(data) = data {
                    data.insert("started".into(), result.started.into());
                }
            }
            if result.response.ok {
                write_response(
                    mode,
                    Some(verb),
                    stdout,
                    &result.response,
                    ExitCode::SUCCESS,
                )
            } else {
                write_response(
                    mode,
                    Some(verb),
                    stderr,
                    &result.response,
                    ExitCode::FAILURE,
                )
            }
        }
        Err(error) => write_response(
            mode,
            Some(verb),
            stderr,
            &ResponseEnvelope::failure(None, error.error_body()),
            ExitCode::FAILURE,
        ),
    }
}

/// Sends a worker verb over the per-run socket injected by the agent adapter.
/// Worker verbs never resurrect a daemon: without a run's `SLOOP_SOCKET` and
/// `SLOOP_TOKEN` there is no state worth talking to, so they fail loudly. The
/// daemon's reply envelope is written verbatim; agents are the only callers
/// and the envelope is the API.
fn run_worker_request(
    request: Request,
    mode: OutputMode,
    stdout: &mut impl Write,
    stderr: &mut impl Write,
) -> ExitCode {
    let verb = request.verb();
    let socket = std::env::var_os("SLOOP_SOCKET");
    let token = std::env::var("SLOOP_TOKEN").ok();
    let (Some(socket), Some(token)) = (socket, token) else {
        return write_response(
            mode,
            Some(verb),
            stderr,
            &ResponseEnvelope::failure(
                None,
                ErrorBody {
                    code: ErrorCode::Unauthorized,
                    message: "worker verbs require SLOOP_SOCKET and SLOOP_TOKEN from a run".into(),
                    details: json!({}),
                },
            ),
            ExitCode::FAILURE,
        );
    };

    let envelope = RequestEnvelope::new(
        RequestId::new(format!("req-{}", std::process::id())),
        request,
        Some(token),
    );
    match worker_exchange(&socket, &envelope) {
        Ok(reply) => {
            let ok = serde_json::from_str::<ResponseEnvelope>(&reply)
                .map(|response| response.ok)
                .unwrap_or(false);
            let written = if ok {
                writeln!(stdout, "{}", reply.trim_end())
            } else {
                writeln!(stderr, "{}", reply.trim_end())
            };
            if written.is_err() {
                return ExitCode::FAILURE;
            }
            if ok {
                ExitCode::SUCCESS
            } else {
                ExitCode::FAILURE
            }
        }
        Err(message) => write_response(
            mode,
            Some(verb),
            stderr,
            &ResponseEnvelope::failure(
                None,
                ErrorBody {
                    code: ErrorCode::DaemonUnavailable,
                    message,
                    details: json!({}),
                },
            ),
            ExitCode::FAILURE,
        ),
    }
}

fn worker_exchange(socket: &std::ffi::OsStr, envelope: &RequestEnvelope) -> Result<String, String> {
    let mut stream = UnixStream::connect(socket)
        .map_err(|error| format!("cannot connect to worker socket: {error}"))?;
    let encoded = envelope
        .encode()
        .map_err(|error| format!("cannot encode request: {error}"))?;
    stream
        .write_all(encoded.as_bytes())
        .and_then(|()| stream.write_all(b"\n"))
        .map_err(|error| format!("cannot send request: {error}"))?;

    let mut reply = String::new();
    BufReader::new(stream)
        .read_line(&mut reply)
        .map_err(|error| format!("cannot read response: {error}"))?;
    if reply.trim_end().is_empty() {
        return Err("the daemon closed the connection without replying".into());
    }
    Ok(reply)
}

fn write_cli_error(mode: OutputMode, output: &mut impl Write, message: String) -> ExitCode {
    write_response(
        mode,
        None,
        output,
        &ResponseEnvelope::failure(
            None,
            ErrorBody {
                code: ErrorCode::InvalidArguments,
                message,
                details: json!({}),
            },
        ),
        ExitCode::from(2),
    )
}

fn write_response(
    mode: OutputMode,
    verb: Option<&str>,
    output: &mut impl Write,
    response: &ResponseEnvelope,
    success: ExitCode,
) -> ExitCode {
    if write_envelope(mode, verb, output, response).is_err() {
        return ExitCode::FAILURE;
    }
    success
}

/// Writes one envelope in the caller's mode. Split out of `write_response`
/// for the streaming verbs, which write many envelopes before choosing an
/// exit code.
fn write_envelope(
    mode: OutputMode,
    verb: Option<&str>,
    output: &mut impl Write,
    response: &ResponseEnvelope,
) -> Result<(), ()> {
    match mode {
        OutputMode::Json => serde_json::to_writer(&mut *output, response)
            .map_err(|_| ())
            .and_then(|()| output.write_all(b"\n").map_err(|_| ())),
        OutputMode::Human(style) => output
            .write_all(self::render::render(verb, response, style).as_bytes())
            .map_err(|_| ()),
    }
}

#[cfg(test)]
mod tests {
    use clap::{Parser, ValueEnum};
    use serde_json::{Value, json};

    use super::{Cli, expand_limit_shorthand, subcommand_synonym};
    use crate::protocol::{Capability, Request};

    /// Drives the full CLI entry point and returns the error envelope written
    /// to stderr, exactly as an agent using `--json` would receive it.
    fn error_envelope(args: &[&str]) -> Value {
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();
        let mut argv = vec!["sloop", "--json"];
        argv.extend_from_slice(args);
        super::run(argv, &mut stdout, &mut stderr);
        serde_json::from_slice(&stderr).expect("stderr carries a JSON envelope")
    }

    /// The rewrite is deliberately narrow: only `list`'s own arguments, and
    /// only all-digit ones. Everything else has to reach clap untouched, or a
    /// negative-looking value elsewhere would silently become a limit.
    #[test]
    fn the_limit_shorthand_expands_only_for_read_arguments() {
        let expanded = |argv: &[&str]| {
            let mut args: Vec<std::ffi::OsString> =
                argv.iter().map(std::ffi::OsString::from).collect();
            expand_limit_shorthand(&mut args);
            args.iter()
                .map(|arg| arg.to_string_lossy().into_owned())
                .collect::<Vec<_>>()
        };

        assert_eq!(
            expanded(&["sloop", "list", "-2"]),
            ["sloop", "list", "--limit=2"]
        );
        assert_eq!(
            expanded(&["sloop", "--json", "list", "-2"]),
            ["sloop", "--json", "list", "--limit=2"]
        );
        assert_eq!(expanded(&["sloop", "list", "-0"])[2], "--limit=0");
        assert_eq!(
            expanded(&["sloop", "show", "log", "-2"]),
            ["sloop", "show", "log", "--limit=2"]
        );
        for untouched in [
            ["sloop", "list", "-abc"].as_slice(),
            ["sloop", "list", "-n"].as_slice(),
            ["sloop", "post", "list", "-2"].as_slice(),
            ["sloop", "watch", "-2"].as_slice(),
        ] {
            assert_eq!(expanded(untouched), untouched, "{untouched:?}");
        }
    }

    #[test]
    fn unknown_subcommand_suggests_the_tickets_synonym() {
        let envelope = error_envelope(&["tickets"]);

        assert_eq!(envelope["error"]["code"], "invalid_arguments");
        let message = envelope["error"]["message"]
            .as_str()
            .expect("error message");
        assert!(
            message.contains("did you mean `list`") && message.contains("sloop list"),
            "synonym remedy missing from: {message}"
        );
    }

    #[test]
    fn unknown_subcommand_suggests_a_near_miss_spelling() {
        let envelope = error_envelope(&["statuss"]);

        let message = envelope["error"]["message"]
            .as_str()
            .expect("error message");
        assert!(
            message.contains("status"),
            "near-miss suggestion missing from: {message}"
        );
    }

    #[test]
    fn synonym_table_only_points_at_real_verbs() {
        use clap::CommandFactory;

        let verbs: Vec<String> = Cli::command()
            .get_subcommands()
            .map(|subcommand| subcommand.get_name().to_owned())
            .collect();
        for attempted in ["tickets", "ls", "queue", "ps", "start", "kill", "abort"] {
            let verb = subcommand_synonym(attempted).expect("synonym maps to a verb");
            assert!(
                verbs.iter().any(|known| known == verb),
                "synonym `{attempted}` points at unknown verb `{verb}`"
            );
        }
        assert!(subcommand_synonym("definitely-not-a-verb").is_none());
    }

    #[test]
    fn parses_every_documented_verb() {
        let commands: &[&[&str]] = &[
            &["sloop", "init"],
            &["sloop", "template", "ticket"],
            &["sloop", "template", "flow"],
            &["sloop", "template", "project"],
            &["sloop", "template", "config"],
            &["sloop", "daemon"],
            &["sloop", "post", "ticket.md", "--auto"],
            &["sloop", "post", "ticket.md", "--at", "03:00"],
            &["sloop", "post", "ticket.md", "--manual"],
            &["sloop", "post", "ticket.md", "--hold"],
            &["sloop", "run"],
            &["sloop", "run", "T1", "--at", "03:00"],
            &["sloop", "run", "--every", "30m", "--only", "T1,T7"],
            &["sloop", "run", "--overnight"],
            &["sloop", "retry", "T1"],
            &["sloop", "hold", "T1"],
            &["sloop", "ready", "T1"],
            &["sloop", "list"],
            &["sloop", "status"],
            &["sloop", "pause"],
            &["sloop", "resume"],
            &["sloop", "cancel", "R1"],
            &["sloop", "logs", "R1"],
            &["sloop", "logs", "R1", "--stage", "test"],
            &["sloop", "logs", "R1", "--tail", "50"],
            &[
                "sloop", "logs", "R1", "--stage", "test", "--tail", "5", "--follow",
            ],
            &["sloop", "watch"],
            &["sloop", "watch", "--tail", "50"],
            &["sloop", "watch", "T1"],
            &["sloop", "watch", "T1-r2", "--tail", "50"],
            &["sloop", "reindex"],
            &["sloop", "brief"],
            &["sloop", "show", "T1"],
            &["sloop", "note", "work", "in", "progress"],
            &["sloop", "verdict", "fail", "--reason", "changes requested"],
        ];

        for command in commands {
            Cli::try_parse_from(*command).unwrap_or_else(|error| {
                panic!("failed to parse {command:?}: {error}");
            });
        }
    }

    #[test]
    fn every_documented_verb_constructs_a_typed_request() {
        let commands: &[&[&str]] = &[
            &["sloop", "init"],
            &["sloop", "daemon"],
            &["sloop", "post", "ticket.md", "--auto"],
            &["sloop", "run"],
            &["sloop", "retry", "T1"],
            &["sloop", "hold", "T1"],
            &["sloop", "ready", "T1"],
            &["sloop", "list"],
            &["sloop", "status"],
            &["sloop", "pause"],
            &["sloop", "resume"],
            &["sloop", "cancel", "R1"],
            &["sloop", "logs", "R1"],
            &["sloop", "logs", "R1", "--stage", "test", "--tail", "5"],
            &["sloop", "watch"],
            &["sloop", "watch", "T1"],
            &["sloop", "reindex"],
            &["sloop", "brief"],
            &["sloop", "show", "T1"],
            &["sloop", "note", "working"],
            &["sloop", "verdict", "pass"],
        ];

        for command in commands {
            Cli::try_parse_from(*command)
                .unwrap()
                .into_request()
                .unwrap_or_else(|error| panic!("failed to construct {command:?}: {error}"));
        }
    }

    #[test]
    fn run_options_become_protocol_arguments() {
        let request = Cli::try_parse_from(["sloop", "run", "--every", "30m", "--only", "T1,T7"])
            .unwrap()
            .into_request()
            .unwrap();

        assert_eq!(
            serde_json::to_value(request).unwrap(),
            json!({
                "verb": "run",
                "args": {
                    "trigger": {"kind": "every", "interval_ms": 1_800_000},
                    "only": ["T1", "T7"]
                }
            })
        );
    }

    #[test]
    fn hold_becomes_a_distinct_post_trigger() {
        let request = Cli::try_parse_from(["sloop", "post", "ticket.md", "--hold"])
            .unwrap()
            .into_request()
            .unwrap();

        assert_eq!(
            serde_json::to_value(request).unwrap(),
            json!({
                "verb": "post",
                "args": {
                    "file": "ticket.md",
                    "trigger": {"kind": "hold"}
                }
            })
        );
    }

    #[test]
    fn worker_request_text_and_capability_are_preserved() {
        let request = Cli::try_parse_from(["sloop", "note", "work", "in", "progress"])
            .unwrap()
            .into_request()
            .unwrap();

        assert_eq!(request.capability(), Capability::Worker);
        assert_eq!(
            serde_json::to_value(request).unwrap(),
            json!({"verb": "note", "args": {"text": "work in progress"}})
        );
    }

    #[test]
    fn verdict_becomes_a_worker_request() {
        let request =
            Cli::try_parse_from(["sloop", "verdict", "fail", "--reason", "changes requested"])
                .unwrap()
                .into_request()
                .unwrap();

        assert_eq!(request.capability(), Capability::Worker);
        assert_eq!(
            serde_json::to_value(request).unwrap(),
            json!({
                "verb": "verdict",
                "args": {"verdict": "fail", "reason": "changes requested"}
            })
        );
    }

    #[test]
    fn operator_requests_are_classified_separately() {
        let request = Cli::try_parse_from(["sloop", "status"])
            .unwrap()
            .into_request()
            .unwrap();

        assert_eq!(request.capability(), Capability::Operator);
        assert!(matches!(request, Request::Status(_)));
    }

    /// Drives the full entry point and returns stdout, so these tests prove
    /// the verb answers without a daemon: the test process has no repository,
    /// no socket, and no `SLOOP_TOKEN`, and any daemon path would fail.
    fn stdout_of(args: &[&str]) -> String {
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();
        let mut argv = vec!["sloop"];
        argv.extend_from_slice(args);
        let code = super::run(argv, &mut stdout, &mut stderr);

        assert_eq!(
            format!("{code:?}"),
            format!("{:?}", std::process::ExitCode::SUCCESS),
            "stderr: {}",
            String::from_utf8_lossy(&stderr)
        );
        String::from_utf8(stdout).expect("stdout is UTF-8")
    }

    #[test]
    fn every_template_kind_prints_verbatim_without_a_daemon() {
        for kind in ["ticket", "flow", "project", "config"] {
            let printed = stdout_of(&["template", kind]);
            let expected = super::TemplateKind::from_str(kind, false)
                .expect("kind is accepted")
                .text();
            assert_eq!(printed, expected, "`sloop template {kind}` was rewritten");
        }
    }

    #[test]
    fn template_json_mode_wraps_the_text_in_an_envelope() {
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();
        super::run(
            ["sloop", "--json", "template", "flow"],
            &mut stdout,
            &mut stderr,
        );

        let envelope: Value = serde_json::from_slice(&stdout).expect("stdout carries an envelope");
        assert_eq!(envelope["ok"], true);
        assert_eq!(envelope["data"]["kind"], "flow");
        assert_eq!(
            envelope["data"]["template"].as_str(),
            Some(super::TemplateKind::Flow.text())
        );
    }

    #[test]
    fn an_unknown_template_kind_lists_the_valid_kinds() {
        let envelope = error_envelope(&["template", "readme"]);

        assert_eq!(envelope["error"]["code"], "invalid_arguments");
        let message = envelope["error"]["message"]
            .as_str()
            .expect("error message");
        for kind in ["ticket", "flow", "project", "config"] {
            assert!(message.contains(kind), "`{kind}` missing from: {message}");
        }
    }

    /// `template` answers from compiled-in content, so it deliberately has no
    /// protocol verb. Constructing a request must fail rather than silently
    /// routing it at the daemon.
    #[test]
    fn template_never_becomes_a_daemon_request() {
        let error = Cli::try_parse_from(["sloop", "template", "ticket"])
            .unwrap()
            .into_request()
            .expect_err("template has no daemon request");

        assert!(error.to_string().contains("printed locally"), "{error}");
    }

    #[test]
    fn post_help_points_at_the_ticket_template() {
        let help = stdout_of(&["post", "--help"]);

        assert!(help.contains("sloop template ticket"), "{help}");
        assert!(help.contains("sloop template flow"), "{help}");
    }

    #[test]
    fn invalid_time_and_duration_fail_during_cli_parsing() {
        assert!(Cli::try_parse_from(["sloop", "run", "--at", "25:00"]).is_err());
        assert!(Cli::try_parse_from(["sloop", "run", "--every", "later"]).is_err());
        assert!(Cli::try_parse_from(["sloop", "run", "--every", "0m"]).is_err());
    }

    #[test]
    fn run_accepts_only_one_trigger_mode() {
        let result = Cli::try_parse_from(["sloop", "run", "--at", "03:00", "--every", "30m"]);
        assert!(result.is_err());
    }

    #[test]
    fn post_defaults_to_auto_and_accepts_only_one_explicit_trigger_mode() {
        let request = Cli::try_parse_from(["sloop", "post", "ticket.md"])
            .unwrap()
            .into_request()
            .unwrap();
        assert_eq!(
            serde_json::to_value(request).unwrap(),
            json!({
                "verb": "post",
                "args": {
                    "file": "ticket.md",
                    "trigger": {"kind": "auto"}
                }
            })
        );
        assert!(Cli::try_parse_from(["sloop", "post", "ticket.md", "--auto", "--manual"]).is_err());
        assert!(Cli::try_parse_from(["sloop", "post", "ticket.md", "--manual", "--hold"]).is_err());
    }
}