postvak 0.5.0

A fast, simple mail client with automatic mailbox rules
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
use std::io::{self, BufRead, Write};
use std::path::{Path, PathBuf};
use std::sync::mpsc::Receiver;
use std::time::Duration;

use anyhow::{Context as _, Result, bail};
use clap::{Parser, Subcommand};

use postvak_core::account;
use postvak_core::config::{AccountConfig, Config, Identity, PasswordSource};
use postvak_core::credentials::Secret;
use postvak_core::daemon::Client;
use postvak_core::daemon::client::LazyClient;
use postvak_core::daemon::wire::Status;
use postvak_core::message::clean;
use postvak_core::paths::Paths;
use postvak_core::rules::{Action, CompiledRule, Rule, RuleFile};
use postvak_core::store::{Filter, Message, Store};
use postvak_core::sync::{self, Event};
use postvak_core::time;
use postvak_core::trash::Trash;

#[derive(Parser)]
#[command(
    name = "postvak",
    version,
    about = "A fast, simple mail client with automatic mailbox rules"
)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(clap::Args)]
struct Selection {
    /// Message uids in --folder, as `list` prints them
    #[arg(required = true)]
    uids: Vec<u32>,
    #[arg(long)]
    account: Option<String>,
    #[arg(long, default_value = "INBOX")]
    folder: String,
    /// Print what would happen without touching the server
    #[arg(long)]
    dry_run: bool,
}

#[derive(Clone, Copy, clap::ValueEnum)]
enum Mark {
    Flag,
    Read,
    Unflag,
    Unread,
}

#[derive(Subcommand)]
enum Command {
    /// Run the daemon in the foreground: sync all accounts continuously and apply rules; fails when a daemon already runs; Ctrl-C stops
    Run {
        /// Exit after this many seconds with no client connected; what auto-start uses
        #[arg(long, hide = true)]
        idle_exit: Option<u64>,
    },
    /// Inspect or stop the daemon that syncs your accounts; other commands start it when needed
    Daemon {
        #[command(subcommand)]
        command: DaemonCommand,
    },
    /// Open the mail window; starts the daemon when needed
    Gui {
        /// Draw with the software renderer and ignore the saved window layout, for when the window will not open;
        /// entered by itself after two starts in a row that died before the window showed
        #[arg(long)]
        safe_mode: bool,
    },
    /// Start the daemon at login: a launchd agent on macOS, a systemd user unit on Linux
    Service {
        #[command(subcommand)]
        command: ServiceCommand,
    },
    #[command(about = postvak_core::help::SYNC)]
    Sync {
        #[arg(long)]
        account: Option<String>,
    },
    /// List or save a message's attachments
    Attachment {
        #[command(subcommand)]
        command: AttachmentCommand,
    },
    /// Inspect and test rules.toml
    Rules {
        #[command(subcommand)]
        command: RulesCommand,
    },
    #[command(about = postvak_core::help::FOLDERS)]
    Folders {
        #[arg(long)]
        account: Option<String>,
        #[arg(long)]
        json: bool,
    },
    #[command(about = postvak_core::help::LIST)]
    List {
        #[arg(long)]
        account: Option<String>,
        #[arg(long, default_value = "INBOX")]
        folder: String,
        #[arg(long, default_value_t = 50)]
        limit: u32,
        #[arg(long)]
        json: bool,
        /// Group by conversation, the most recently active thread first
        #[arg(long)]
        threads: bool,
        /// Only unread messages; with --threads, threads with an unread message
        #[arg(long)]
        unread: bool,
        /// Only flagged messages; with --threads, threads with a flagged message
        #[arg(long)]
        flagged: bool,
        /// Only messages with attachments, guessed from the headers; with --threads, threads with one
        #[arg(long)]
        attachments: bool,
    },
    #[command(about = postvak_core::help::SEARCH)]
    Search {
        query: String,
        #[arg(long)]
        account: Option<String>,
        #[arg(long)]
        folder: Option<String>,
        /// Fetch and index missing bodies first; slow on a large folder
        #[arg(long)]
        bodies: bool,
        /// Ask the server too, which searches bodies not downloaded yet; each folder costs a round trip
        #[arg(long)]
        server: bool,
        #[arg(long, default_value_t = 50)]
        limit: u32,
        #[arg(long)]
        json: bool,
    },
    #[command(about = postvak_core::help::SHOW)]
    Show {
        uid: u32,
        #[arg(long)]
        account: Option<String>,
        #[arg(long, default_value = "INBOX")]
        folder: String,
        /// Print the raw RFC 5322 message instead of the text body
        #[arg(long)]
        raw: bool,
        #[arg(long)]
        json: bool,
    },
    #[command(about = postvak_core::help::UNSUBSCRIBE)]
    Unsubscribe {
        uid: u32,
        #[arg(long)]
        account: Option<String>,
        #[arg(long, default_value = "INBOX")]
        folder: String,
        /// Print what would happen without contacting the sender
        #[arg(long)]
        dry_run: bool,
        #[arg(long)]
        json: bool,
    },
    #[command(about = postvak_core::help::MARK)]
    Mark {
        #[arg(value_enum)]
        how: Mark,
        #[command(flatten)]
        selection: Selection,
    },
    #[command(about = postvak_core::help::MOVE)]
    Move {
        #[arg(long)]
        to: String,
        #[command(flatten)]
        selection: Selection,
    },
    #[command(about = postvak_core::help::ARCHIVE)]
    Archive {
        #[command(flatten)]
        selection: Selection,
    },
    #[command(about = postvak_core::help::DELETE)]
    Delete {
        #[command(flatten)]
        selection: Selection,
    },
    #[command(about = postvak_core::help::JUNK)]
    Junk {
        #[command(flatten)]
        selection: Selection,
        /// Not junk after all
        #[arg(long)]
        not: bool,
    },
    #[command(about = postvak_core::help::LOG)]
    Log {
        #[arg(long)]
        account: Option<String>,
        #[arg(long, default_value_t = 50)]
        limit: u32,
        #[arg(long)]
        json: bool,
    },
    /// Deleted mail kept for the retention period
    Trash {
        #[command(subcommand)]
        command: TrashCommand,
    },
    /// Manage accounts
    Account {
        #[command(subcommand)]
        command: AccountCommand,
    },
    /// List the local crash reports, newest first; they are never sent anywhere
    Crashes {
        #[command(subcommand)]
        command: Option<CrashesCommand>,
    },
    /// Print the agent guide: how an LLM should drive Postvak
    Guide,
    /// Serve Postvak to an agent host over MCP on stdio; hosts start this, see `postvak mcp install`
    #[command(args_conflicts_with_subcommands = true)]
    Mcp {
        /// Comma-separated: read, read:bodies, rules:propose, rules:write, files:write, mail:modify, accounts:write
        #[arg(long, default_value = postvak_core::help::MCP_DEFAULT_SCOPES)]
        scopes: String,
        /// Only this account; repeatable; default every account
        #[arg(long)]
        account: Vec<String>,
        #[command(subcommand)]
        command: Option<McpCommand>,
    },
}

#[derive(Subcommand)]
enum CrashesCommand {
    /// Print one crash report, by the id `postvak crashes` lists
    Show { id: String },
}

#[derive(Subcommand)]
enum DaemonCommand {
    #[command(about = postvak_core::help::STATUS)]
    Status {
        #[arg(long)]
        json: bool,
    },
    /// Stop the daemon; it starts again when a command needs it
    Stop,
}

#[derive(Subcommand)]
enum ServiceCommand {
    /// Install and start the service; stops a daemon that is already running so the service's takes over
    Install {
        /// Print the file and the commands and change nothing
        #[arg(long)]
        dry_run: bool,
    },
    /// Stop and remove the service
    Remove {
        /// Print the commands and change nothing
        #[arg(long)]
        dry_run: bool,
    },
}

#[derive(Subcommand)]
enum McpCommand {
    /// Register `postvak mcp` with an agent host; re-run it to change the scopes
    Install {
        #[arg(value_enum)]
        target: InstallTarget,
        /// Comma-separated: read, read:bodies, rules:propose, rules:write, files:write, mail:modify, accounts:write
        #[arg(long, default_value = postvak_core::help::MCP_DEFAULT_SCOPES)]
        scopes: String,
        /// Only this account; repeatable; default every account
        #[arg(long)]
        account: Vec<String>,
        /// Take the entry out again
        #[arg(long)]
        remove: bool,
        /// Print the change and write nothing
        #[arg(long)]
        dry_run: bool,
    },
}

#[derive(Clone, Copy, clap::ValueEnum)]
enum InstallTarget {
    ClaudeCode,
    ClaudeDesktop,
    Json,
}

#[derive(Subcommand)]
enum AttachmentCommand {
    #[command(about = postvak_core::help::ATTACHMENT_LIST)]
    List {
        uid: u32,
        #[arg(long)]
        account: Option<String>,
        #[arg(long, default_value = "INBOX")]
        folder: String,
        #[arg(long)]
        json: bool,
    },
    #[command(about = postvak_core::help::ATTACHMENT_SAVE)]
    Save {
        uid: u32,
        n: usize,
        #[arg(long, default_value = ".")]
        dir: PathBuf,
        #[arg(long)]
        account: Option<String>,
        #[arg(long, default_value = "INBOX")]
        folder: String,
    },
}

#[derive(Subcommand)]
enum RulesCommand {
    #[command(about = postvak_core::help::RULES_CHECK)]
    Check,
    /// Dry run: print what each rule would do to the cached messages; naming a rule previews it even while disabled
    Test {
        #[arg(conflicts_with = "stdin")]
        name: Option<String>,
        #[arg(long)]
        account: Option<String>,
        /// Preview one rule read as JSON from stdin instead of rules.toml
        #[arg(long)]
        stdin: bool,
    },
    #[command(about = postvak_core::help::RULES_SCHEMA)]
    Schema,
    /// Read one rule as JSON on stdin and add it disabled, for a human to approve
    Propose {
        /// Who proposes it, recorded as proposed_by = "cli:WHO"
        #[arg(long)]
        by: Option<String>,
    },
    #[command(about = postvak_core::help::RULES_APPROVE)]
    Approve { name: String },
    #[command(about = postvak_core::help::RULES_REJECT)]
    Reject { name: String },
    #[command(about = postvak_core::help::RULES_LIST)]
    List {
        #[arg(long)]
        json: bool,
    },
    #[command(about = postvak_core::help::RULES_APPLY_EXISTING)]
    ApplyExisting {
        name: String,
        #[arg(long)]
        account: Option<String>,
        #[arg(long)]
        dry_run: bool,
        /// Run even when the rule would permanently delete mail from the server
        #[arg(long)]
        yes: bool,
    },
}

#[derive(Subcommand)]
enum TrashCommand {
    #[command(about = postvak_core::help::TRASH_LIST)]
    List {
        #[arg(long)]
        account: Option<String>,
    },
    #[command(about = postvak_core::help::TRASH_RESTORE)]
    Restore {
        file: String,
        #[arg(long)]
        account: Option<String>,
    },
    #[command(about = postvak_core::help::TRASH_PURGE)]
    Purge {
        #[arg(long)]
        account: Option<String>,
    },
}

#[derive(Subcommand)]
enum AccountCommand {
    #[command(about = postvak_core::help::ACCOUNT_ADD)]
    Add,
    #[command(about = postvak_core::help::ACCOUNT_LIST)]
    List {
        #[arg(long)]
        json: bool,
    },
}

pub fn run() -> Result<()> {
    let cli = if opened_as_mac_app() {
        Cli {
            command: Command::Gui { safe_mode: false },
        }
    } else {
        Cli::parse()
    };
    let paths = match std::env::var_os("POSTVAK_HOME") {
        Some(home) => Ok(Paths::under(Path::new(&home))),
        None => Paths::discover(),
    };
    if let Ok(paths) = &paths {
        postvak_core::crash::install(paths.crash_dir(), process(&cli.command));
    }
    // The window explains its own startup errors, since it may have no terminal to print them in.
    if let Command::Gui { safe_mode } = cli.command {
        return cmd_gui(paths, safe_mode);
    }
    let paths = paths?;
    let config = Config::load(&paths.config_file())?;
    match cli.command {
        Command::Run { idle_exit } => cmd_run(&paths, idle_exit),
        Command::Crashes { command } => cmd_crashes(command, &paths),
        Command::Daemon { command } => cmd_daemon(command, &paths),
        Command::Gui { safe_mode } => cmd_gui(Ok(paths), safe_mode),
        Command::Service { command } => cmd_service(command, &paths),
        Command::Sync { account } => cmd_sync(&config, &paths, account.as_deref()),
        Command::Attachment { command } => cmd_attachment(command, &config, &paths),
        Command::Rules { command } => cmd_rules(command, &config, &paths),
        Command::Folders { account, json } => {
            for acc in select_accounts(&config, account.as_deref())? {
                let store = Store::open_account(&paths, &acc.name)?;
                for f in store.folders()? {
                    let total = store.message_count(&f.name)?;
                    let unread = store.unread_count(&f.name)?;
                    if json {
                        print_json(postvak_core::output::folder(&acc.name, &f, total, unread));
                    } else {
                        println!("{}\t{}\t{total}\t{unread}", acc.name, clean(&f.name, false));
                    }
                }
            }
            Ok(())
        }
        Command::List {
            account,
            folder,
            limit,
            json,
            threads,
            unread,
            flagged,
            attachments,
        } => {
            let filter = Filter {
                unread,
                flagged,
                attachments,
            };
            for acc in select_accounts(&config, account.as_deref())? {
                let store = Store::open_account(&paths, &acc.name)?;
                if threads {
                    for thread in store.threads(&folder, limit, filter)? {
                        for (m, depth) in thread.iter().zip(postvak_core::output::depths(&thread)) {
                            if json {
                                let mut value = serde_json::to_value(m)?;
                                value["depth"] = depth.into();
                                print_json(postvak_core::output::with_account(&acc.name, &value)?);
                            } else {
                                println!("{}", message_line(&acc.name, m, depth));
                            }
                        }
                    }
                    continue;
                }
                for m in store.messages(&folder, limit, filter)? {
                    if json {
                        print_json(postvak_core::output::with_account(&acc.name, &m)?);
                    } else {
                        println!("{}", message_line(&acc.name, &m, 0));
                    }
                }
            }
            Ok(())
        }
        Command::Search {
            query,
            account,
            folder,
            bodies,
            server,
            limit,
            json,
        } => {
            let daemon = LazyClient::new(&paths);
            for acc in select_accounts(&config, account.as_deref())? {
                let store = Store::open_account(&paths, &acc.name)?;
                if bodies && store.lacks_bodies(folder.as_deref())? {
                    eprintln!(
                        "{}: fetching missing bodies; this can take a while on a large folder",
                        acc.name
                    );
                    if let Err(e) = fetch_bodies(&daemon, &acc.name, folder.as_deref()) {
                        eprintln!(
                            "{}: {}; searching the bodies already stored",
                            acc.name,
                            clean(&format!("{e:#}"), false)
                        );
                    }
                }
                let mut found = store.search(&query, folder.as_deref(), limit)?;
                if server {
                    match daemon.search_server(&acc.name, folder.as_deref(), &query) {
                        Ok(hits) => {
                            found = postvak_core::actions::with_server_hits(
                                &store, found, &hits, limit,
                            )?
                        }
                        Err(e) => eprintln!(
                            "{}: {}; showing local results only",
                            acc.name,
                            clean(&format!("{e:#}"), false)
                        ),
                    }
                }
                for m in found {
                    if json {
                        print_json(postvak_core::output::with_account(&acc.name, &m)?);
                    } else {
                        println!("{}", message_line(&acc.name, &m, 0));
                    }
                }
            }
            Ok(())
        }
        Command::Unsubscribe {
            uid,
            account,
            folder,
            dry_run,
            json,
        } => {
            let (acc, _store, msg) =
                open_message(&config, &paths, account.as_deref(), &folder, uid)?;
            let report = postvak_core::unsubscribe::unsubscribe(&msg.headers, dry_run)?;
            if json {
                print_json(postvak_core::output::with_account(&acc.name, &report)?);
            } else {
                println!("{}", unsubscribe_line(&report));
            }
            Ok(())
        }
        Command::Show {
            uid,
            account,
            folder,
            raw,
            json,
        } => {
            let (acc, store, msg) =
                open_message(&config, &paths, account.as_deref(), &folder, uid)?;
            let body = LazyClient::new(&paths).raw_message(&acc.name, &store, &msg)?;
            if raw {
                io::stdout().write_all(&body)?;
            } else if json {
                print_json(
                    serde_json::json!({ "account": acc.name, "message": msg, "body_text": postvak_core::message::body_text(&body) }),
                );
            } else {
                println!(
                    "From: {}\nTo: {}\nSubject: {}\n",
                    clean(msg.from_addr.as_deref().unwrap_or(""), false),
                    clean(msg.to_addr.as_deref().unwrap_or(""), false),
                    clean(msg.subject.as_deref().unwrap_or(""), false)
                );
                println!("{}", clean(&postvak_core::message::body_text(&body), true));
            }
            Ok(())
        }
        Command::Mark { how, selection } => {
            let action = match how {
                Mark::Flag => Action::Flag,
                Mark::Read => Action::MarkRead,
                Mark::Unflag => Action::Unflag,
                Mark::Unread => Action::MarkUnread,
            };
            cmd_act(&config, &paths, selection, action)
        }
        Command::Move { to, selection } => {
            if to.trim().is_empty() {
                bail!("--to must name a folder");
            }
            cmd_act(&config, &paths, selection, Action::Move(to))
        }
        Command::Archive { selection } => cmd_act(&config, &paths, selection, Action::Archive),
        Command::Delete { selection } => cmd_act(&config, &paths, selection, Action::Trash),
        Command::Junk { selection, not } => {
            let action = if not { Action::NotJunk } else { Action::Junk };
            cmd_act(&config, &paths, selection, action)
        }
        Command::Log {
            account,
            limit,
            json,
        } => {
            for acc in select_accounts(&config, account.as_deref())? {
                let store = Store::open_account(&paths, &acc.name)?;
                for e in store.log(limit)? {
                    if json {
                        print_json(postvak_core::output::with_account(&acc.name, &e)?);
                    } else {
                        println!(
                            "{}  {}  {:<20} {:<12} {}/{}  {}",
                            acc.name,
                            time::date_time(e.at),
                            clean(&e.rule_name, false),
                            clean(&e.action, false),
                            clean(&e.folder, false),
                            e.uid,
                            clean(e.subject.as_deref().unwrap_or(""), false)
                        );
                    }
                }
            }
            Ok(())
        }
        Command::Trash { command } => cmd_trash(command, &config, &paths),
        Command::Account { command } => match command {
            AccountCommand::Add => cmd_account_add(config, &paths),
            AccountCommand::List { json } => {
                for acc in &config.accounts {
                    if json {
                        print_json(postvak_core::output::account(acc));
                    } else {
                        println!(
                            "{}\t{}\t{}:{}",
                            acc.name,
                            clean(&acc.username, false),
                            acc.host,
                            acc.port
                        );
                    }
                }
                Ok(())
            }
        },
        Command::Guide => {
            print!("{}", postvak_core::help::AGENT_GUIDE);
            Ok(())
        }
        Command::Mcp {
            scopes,
            account,
            command,
        } => cmd_mcp(&config, &paths, &scopes, &account, command),
    }
}

/// Runs a direct action on the selected uids; `--dry-run` only reads the local store.
fn cmd_act(config: &Config, paths: &Paths, selection: Selection, action: Action) -> Result<()> {
    let acc = single_account(config, selection.account.as_deref())?;
    let store = Store::open_account(paths, &acc.name)?;
    let folder = clean(&selection.folder, false);
    if selection.dry_run {
        let mut missing = 0;
        for &uid in &selection.uids {
            match store.message(&selection.folder, uid)? {
                Some(m) => println!(
                    "{}  {folder}/{uid}  {}",
                    postvak_core::actions::planned_effect(&store, &m, &action)?,
                    clean(m.subject.as_deref().unwrap_or(""), false)
                ),
                None => {
                    eprintln!("{folder}/{uid}: not in the local store");
                    missing += 1;
                }
            }
        }
        if missing > 0 {
            bail!("{missing} messages are not in the local store; run `postvak sync` first");
        }
        return Ok(());
    }
    let results = LazyClient::new(paths).apply(
        &acc.name,
        &selection.folder,
        &selection.uids,
        &action,
        postvak_core::actions::RULE_NAME,
    )?;
    let mut failed = 0;
    for (uid, result) in &results {
        if let Err(message) = result {
            eprintln!("{folder}/{uid}: {}", clean(message, false));
            failed += 1;
        }
    }
    println!(
        "{}: {} of {} messages",
        clean(&action.command_label(), false),
        results.len() - failed,
        results.len()
    );
    if failed > 0 {
        bail!("{failed} of {} messages failed", results.len());
    }
    Ok(())
}

fn unsubscribe_line(report: &postvak_core::unsubscribe::Report) -> String {
    let url = clean(&report.url, false);
    match (report.method, report.done) {
        (_, true) => "unsubscribed: the sender's server accepted it".to_string(),
        ("one_click", false) => format!("would unsubscribe by one-click POST to {url}"),
        ("mail", false) => format!("send a mail to unsubscribe: {url}"),
        _ => format!("open this page to unsubscribe: {url}"),
    }
}

/// Asks the daemon to fetch the missing bodies.
fn fetch_bodies(daemon: &LazyClient, account: &str, folder: Option<&str>) -> Result<()> {
    let fetch = sync::Command::FetchBodies {
        folder: folder.map(str::to_string),
    };
    daemon.request(account, fetch, |reply| match reply {
        Event::BodiesFetched { .. } => Ok(()),
        other => Err(other),
    })
}

fn cmd_sync(config: &Config, paths: &Paths, account: Option<&str>) -> Result<()> {
    let accounts = select_accounts(config, account)?;
    if accounts.is_empty() {
        return Ok(());
    }
    let names: Vec<&str> = accounts.iter().map(|acc| acc.name.as_str()).collect();
    let client = Client::connect_or_start(paths)?;
    let events = client.subscribe()?;
    std::thread::scope(|scope| {
        let printer = scope.spawn(|| print_new_mail(events, &names));
        let mut failed = false;
        for name in &names {
            failed |= !sync_account(&client, name);
        }
        // Closing the connection ends the event stream once the printer has drained it.
        drop(client);
        let _ = printer.join();
        if failed {
            bail!("sync failed for at least one account or folder");
        }
        Ok(())
    })
}

/// Prints the new mail of `accounts` until the stream ends.
fn print_new_mail(events: Receiver<Event>, accounts: &[&str]) {
    for event in &events {
        if let Event::NewMail { account, .. } = &event
            && accounts.contains(&account.as_str())
        {
            postvak_core::daemon::report(&event);
        }
    }
}

/// Syncs one account through the daemon and reports it with its pass's errors; false when it failed or had any.
fn sync_account(client: &Client, name: &str) -> bool {
    match client.request(name, sync::Command::SyncNow) {
        Ok(event) => {
            postvak_core::daemon::report(&event);
            let errors = match &event {
                Event::Synced { errors, .. } => errors.as_slice(),
                _ => &[],
            };
            for message in errors {
                postvak_core::daemon::report_error(name, message);
            }
            errors.is_empty()
        }
        Err(e) => {
            postvak_core::daemon::report_error(name, &format!("{e:#}"));
            false
        }
    }
}

fn print_status(status: &Status) {
    let minutes = status.uptime_secs / 60;
    println!(
        "pid {}, version {}, up {}h {}m, {} clients",
        status.pid,
        status.version,
        minutes / 60,
        minutes % 60,
        status.clients
    );
    for account in &status.accounts {
        let activity = account
            .activity
            .as_ref()
            .map_or("starting".into(), ToString::to_string);
        println!("{}  {activity}", account.name);
    }
}

fn cmd_daemon(command: DaemonCommand, paths: &Paths) -> Result<()> {
    let Some(client) = Client::connect_any_version(paths)? else {
        let json = matches!(command, DaemonCommand::Status { json: true });
        println!("{}", if json { "null" } else { "no daemon running" });
        return Ok(());
    };
    match command {
        DaemonCommand::Status { json } => {
            let status = client.status()?;
            if json {
                print_json(postvak_core::output::status(&status)?);
            } else {
                print_status(&status);
            }
        }
        DaemonCommand::Stop => {
            let pid = client.stop_and_wait(paths)?;
            println!("stopped the daemon (pid {pid})");
        }
    }
    Ok(())
}

fn cmd_service(command: ServiceCommand, paths: &Paths) -> Result<()> {
    let text = match command {
        ServiceCommand::Install { dry_run } => {
            postvak_core::daemon::service::install(paths, dry_run)?
        }
        ServiceCommand::Remove { dry_run } => postvak_core::daemon::service::remove(dry_run)?,
    };
    println!("{text}");
    Ok(())
}

fn cmd_attachment(command: AttachmentCommand, config: &Config, paths: &Paths) -> Result<()> {
    let (uid, account, folder) = match &command {
        AttachmentCommand::List {
            uid,
            account,
            folder,
            ..
        }
        | AttachmentCommand::Save {
            uid,
            account,
            folder,
            ..
        } => (*uid, account.as_deref(), folder.as_str()),
    };
    let (acc, store, msg) = open_message(config, paths, account, folder, uid)?;
    let raw = LazyClient::new(paths).raw_message(&acc.name, &store, &msg)?;
    match command {
        AttachmentCommand::List { json, .. } => {
            for a in postvak_core::message::attachments(&raw) {
                if json {
                    print_json(postvak_core::output::with_account(&acc.name, &a)?);
                } else {
                    println!(
                        "{}  {}  {}  {}",
                        a.index,
                        clean(&a.content_type, false),
                        a.size,
                        clean(a.name.as_deref().unwrap_or("-"), false)
                    );
                }
            }
        }
        AttachmentCommand::Save { n, dir, .. } => {
            let path = postvak_core::message::save_attachment(&raw, n, &dir)
                .with_context(|| format!("saving attachment {n}"))?;
            println!("{}", clean(&path.display().to_string(), false));
        }
    }
    Ok(())
}

fn select_accounts<'a>(config: &'a Config, name: Option<&str>) -> Result<Vec<&'a AccountConfig>> {
    match name {
        Some(n) => Ok(vec![
            config
                .account(n)
                .with_context(|| format!("no account named '{n}'"))?,
        ]),
        None => Ok(config.accounts.iter().collect()),
    }
}

fn single_account<'a>(config: &'a Config, name: Option<&str>) -> Result<&'a AccountConfig> {
    match (name, config.accounts.len()) {
        (Some(n), _) => config
            .account(n)
            .with_context(|| format!("no account named '{n}'")),
        (None, 1) => Ok(&config.accounts[0]),
        (None, 0) => bail!("no accounts configured; run `postvak account add`"),
        (None, _) => bail!("several accounts configured; pass --account"),
    }
}

/// The account, its store and the stored message `folder/uid`.
fn open_message<'a>(
    config: &'a Config,
    paths: &Paths,
    account: Option<&str>,
    folder: &str,
    uid: u32,
) -> Result<(&'a AccountConfig, Store, Message)> {
    let acc = single_account(config, account)?;
    let store = Store::open_account(paths, &acc.name)?;
    let msg = store
        .message(folder, uid)?
        .with_context(|| format!("no message {}/{uid}", clean(folder, false)))?;
    Ok((acc, store, msg))
}

/// One `--json` line, every string cleaned as in MCP results, so an agent reading it sees no hidden text.
fn print_json(value: serde_json::Value) {
    println!("{}", postvak_core::output::clean_value(value, false));
}

/// `account  * INBOX/42  date  from  subject`; `*` marks unread, `depth` indents the subject in thread views.
fn message_line(account: &str, m: &Message, depth: usize) -> String {
    format!(
        "{account}  {} {:<14}  {}  {:<30}  {}{}",
        if m.is_seen() { " " } else { "*" },
        clean(&format!("{}/{}", m.folder, m.uid), false),
        time::date_time(m.internaldate),
        truncate(&clean(m.from_addr.as_deref().unwrap_or(""), false), 30),
        "  ".repeat(depth),
        clean(m.subject.as_deref().unwrap_or(""), false)
    )
}

fn truncate(s: &str, width: usize) -> String {
    let mut out: String = s.chars().take(width).collect();
    if s.chars().count() > width {
        out.pop();
        out.push('…');
    }
    out
}

/// Finder and the Dock start Postvak.app with no arguments; that opens the window rather than printing help.
/// The process a crash report names.
fn process(command: &Command) -> &'static str {
    match command {
        Command::Gui { .. } => "gui",
        Command::Mcp { command: None, .. } => "mcp",
        Command::Run { .. } => "daemon",
        _ => "cli",
    }
}

fn cmd_crashes(command: Option<CrashesCommand>, paths: &Paths) -> Result<()> {
    let dir = paths.crash_dir();
    match command {
        None => {
            let ids = postvak_core::crash::list(&dir)?;
            if ids.is_empty() {
                eprintln!("no crash reports in {}", dir.display());
            }
            for id in ids {
                println!("{id}");
            }
        }
        Some(CrashesCommand::Show { id }) => print!("{}", postvak_core::crash::show(&dir, &id)?),
    }
    Ok(())
}

fn opened_as_mac_app() -> bool {
    use std::io::IsTerminal as _;
    cfg!(target_os = "macos")
        && std::env::current_exe().is_ok_and(|exe| {
            let args: Vec<_> = std::env::args_os().skip(1).collect();
            postvak_core::paths::launched_as_app(&exe, &args, io::stdin().is_terminal())
        })
}

#[cfg(feature = "gui")]
fn cmd_gui(paths: Result<Paths>, safe_mode: bool) -> Result<()> {
    postvak_gui::run(paths, safe_mode)
}

#[cfg(not(feature = "gui"))]
fn cmd_gui(_paths: Result<Paths>, _safe_mode: bool) -> Result<()> {
    bail!("this postvak was built without the GUI; install it with the default features")
}

#[cfg(feature = "mcp")]
fn cmd_mcp(
    config: &Config,
    paths: &Paths,
    scopes: &str,
    accounts: &[String],
    command: Option<McpCommand>,
) -> Result<()> {
    match command {
        None => postvak_mcp::run(config, paths, scopes, accounts),
        Some(McpCommand::Install {
            target,
            scopes,
            account,
            remove,
            dry_run,
        }) => {
            use postvak_mcp::install::{Target, install};
            if let Some(name) = account.iter().find(|name| config.account(name).is_none()) {
                bail!("no account named '{name}'");
            }
            let target = match target {
                InstallTarget::ClaudeCode => Target::ClaudeCode,
                InstallTarget::ClaudeDesktop => Target::ClaudeDesktop,
                InstallTarget::Json => Target::Json,
            };
            let (stdout, hint) = install(target, &scopes, &account, remove, dry_run)?;
            print!("{stdout}");
            if let Some(hint) = hint {
                eprint!("{hint}");
            }
            Ok(())
        }
    }
}

#[cfg(not(feature = "mcp"))]
fn cmd_mcp(
    _config: &Config,
    _paths: &Paths,
    _scopes: &str,
    _accounts: &[String],
    _command: Option<McpCommand>,
) -> Result<()> {
    bail!("this postvak was built without the MCP server; install it with the default features")
}

/// Starts even without accounts: a login service would otherwise restart it in a loop, and accounts added to
/// config.toml later start on their own.
fn cmd_run(paths: &Paths, idle_exit: Option<u64>) -> Result<()> {
    // Test hook: lets tests idle an auto-started daemon out in seconds.
    let override_secs = std::env::var("POSTVAK_IDLE_EXIT_SECS")
        .ok()
        .and_then(|secs| secs.parse().ok());
    let options = match idle_exit.map(|secs| override_secs.unwrap_or(secs)) {
        Some(secs) => postvak_core::daemon::Options::auto_started(Duration::from_secs(secs)),
        None => postvak_core::daemon::Options::foreground(),
    };
    postvak_core::daemon::run(paths, options)
}

fn cmd_rules(command: RulesCommand, config: &Config, paths: &Paths) -> Result<()> {
    match command {
        RulesCommand::Check => {
            println!("{} rules ok", compiled_rules(paths, None)?.len());
            Ok(())
        }
        RulesCommand::List { json } => {
            let file = postvak_core::rules::load(&paths.rules_file())?;
            for r in &file.rules {
                if json {
                    print_json(postvak_core::output::rule(r));
                } else {
                    println!(
                        "{}\t{}\t{}",
                        if r.enabled { "on " } else { "off" },
                        clean(&r.name, false),
                        clean(r.proposed_by.as_deref().unwrap_or(""), false)
                    );
                }
            }
            Ok(())
        }
        RulesCommand::ApplyExisting {
            name,
            account,
            dry_run,
            yes,
        } => {
            let rules = vec![postvak_core::rules::enabled_rule(
                &paths.rules_file(),
                &name,
            )?];
            let accounts: Vec<&AccountConfig> = select_accounts(config, account.as_deref())?
                .into_iter()
                .filter(|acc| rules.iter().any(|r| r.applies_to_account(&acc.name)))
                .collect();
            if dry_run {
                for acc in accounts {
                    let store = Store::open_account(paths, &acc.name)?;
                    print_planned_actions(&rules, &store, acc, &acc.identity()?)?;
                }
                return Ok(());
            }
            if !yes {
                confirm_expunges(&rules, paths, &accounts)?;
            }
            let mut failed = false;
            let daemon = LazyClient::new(paths);
            for acc in accounts {
                let (evaluated, actions, errors) = daemon.apply_rule(&acc.name, &name)?;
                failed |= !errors.is_empty();
                for message in &errors {
                    postvak_core::daemon::report_error(&acc.name, message);
                }
                println!("{}: {actions} actions on {evaluated} messages", acc.name);
            }
            if failed {
                bail!("some actions failed; see the errors above");
            }
            Ok(())
        }
        RulesCommand::Test {
            name,
            account,
            stdin,
        } => {
            let rules = if stdin {
                let mut rule = read_rule_json()?;
                rule.enabled = true;
                postvak_core::rules::compile(&RuleFile { rules: vec![rule] })?
            } else {
                let mut rules = compiled_rules(paths, name.as_deref())?;
                if name.is_some() {
                    rules.iter_mut().for_each(|r| r.rule.enabled = true);
                }
                rules
            };
            for acc in select_accounts(config, account.as_deref())? {
                let store = Store::open_account(paths, &acc.name)?;
                print_planned_actions(&rules, &store, acc, &acc.identity()?)?;
            }
            Ok(())
        }
        RulesCommand::Schema => {
            print!("{}", postvak_core::rules::schema());
            Ok(())
        }
        RulesCommand::Propose { by } => {
            let rule = read_rule_json()?;
            let name = rule.name.clone();
            let by = by.map_or_else(|| "cli".to_string(), |who| format!("cli:{who}"));
            postvak_core::rules::edit::propose(&paths.rules_file(), rule, &by)?;
            println!(
                "proposed '{}'; it stays disabled until a human runs `postvak rules approve`",
                clean(&name, false)
            );
            Ok(())
        }
        RulesCommand::Approve { name } => {
            let accounts: Vec<String> =
                config.accounts.iter().map(|acc| acc.name.clone()).collect();
            postvak_core::rules::edit::approve_from_now(paths, &accounts, &name, time::now())?;
            println!(
                "enabled '{}'; it acts on mail that arrives from now on",
                clean(&name, false)
            );
            Ok(())
        }
        RulesCommand::Reject { name } => {
            postvak_core::rules::edit::reject(&paths.rules_file(), &name)?;
            println!("removed proposal '{}'", clean(&name, false));
            Ok(())
        }
    }
}

fn read_rule_json() -> Result<Rule> {
    serde_json::from_reader(io::stdin().lock()).context("reading one rule as JSON from stdin")
}

/// Compiles rules with `first_seen_at` left at 0 and without touching any store, so previews are
/// side-effect free and cover mail that predates the rule. A `name` that matches no rule is an error.
fn compiled_rules(paths: &Paths, name: Option<&str>) -> Result<Vec<CompiledRule>> {
    let file = postvak_core::rules::load(&paths.rules_file())?;
    let compiled: Vec<CompiledRule> = postvak_core::rules::compile(&file)?
        .into_iter()
        .filter(|r| name.is_none_or(|n| n == r.rule.name))
        .collect();
    if let Some(name) = name
        && compiled.is_empty()
    {
        bail!("no rule named '{name}'");
    }
    Ok(compiled)
}

/// Asks before a rule expunges existing mail, since the server copy is gone for good; refuses without a terminal.
fn confirm_expunges(
    rules: &[CompiledRule],
    paths: &Paths,
    accounts: &[&AccountConfig],
) -> Result<()> {
    use std::io::IsTerminal as _;
    let mut any = false;
    for acc in accounts {
        let store = Store::open_account(paths, &acc.name)?;
        let warning = postvak_core::actions::expunge_warning(
            rules,
            &store,
            acc,
            &acc.identity()?,
            time::now(),
        )?;
        if let Some(warning) = warning {
            any = true;
            eprintln!("{warning}");
        }
    }
    if !any {
        return Ok(());
    }
    if !io::stdin().is_terminal() {
        bail!(
            "refusing to delete without confirmation; check with --dry-run, then rerun with --yes"
        );
    }
    if prompt("Type yes to continue")? != "yes" {
        bail!("cancelled");
    }
    Ok(())
}

fn print_planned_actions(
    rules: &[CompiledRule],
    store: &Store,
    account: &AccountConfig,
    identity: &Identity,
) -> Result<()> {
    for p in postvak_core::actions::planned(rules, store, account, identity, time::now())? {
        println!(
            "{}\t{}/{}\t{}\t{}",
            clean(&p.rule, false),
            clean(&p.message.folder, false),
            p.message.uid,
            clean(&p.action.label(), false),
            clean(p.message.subject.as_deref().unwrap_or(""), false)
        );
    }
    Ok(())
}

fn cmd_trash(command: TrashCommand, config: &Config, paths: &Paths) -> Result<()> {
    match command {
        TrashCommand::List { account } => {
            for acc in select_accounts(config, account.as_deref())? {
                for e in Trash::new(paths.trash_dir(&acc.name)).list()? {
                    let subject = e.headers().subject.unwrap_or_default();
                    println!(
                        "{}  {}  {}/{}  {}  {}",
                        acc.name,
                        time::date_time(e.saved_at),
                        clean(&e.folder, false),
                        e.uid,
                        clean(&subject, false),
                        clean(&e.path.display().to_string(), false)
                    );
                }
            }
            Ok(())
        }
        TrashCommand::Restore { file, account } => {
            let acc = single_account(config, account.as_deref())?;
            let folder = LazyClient::new(paths).restore(&acc.name, std::path::absolute(&file)?)?;
            println!(
                "restored to {}; rules leave restored mail alone",
                clean(&folder, false)
            );
            Ok(())
        }
        TrashCommand::Purge { account } => {
            for acc in select_accounts(config, account.as_deref())? {
                let removed = Trash::new(paths.trash_dir(&acc.name))
                    .purge(acc.trash_retention_days, time::now())?;
                println!("{}: removed {removed}", acc.name);
            }
            Ok(())
        }
    }
}

fn cmd_account_add(mut config: Config, paths: &Paths) -> Result<()> {
    let name = prompt("Account name (letters, digits, - _)")?;
    let host = prompt("IMAP host")?;
    let port: u16 = prompt("Port [993]")?.parse().unwrap_or(993);
    let ca_file = {
        let answer = prompt("Extra trusted CA file (PEM, absolute path) [none]")?;
        if answer.is_empty() {
            None
        } else {
            Some(PathBuf::from(answer))
        }
    };
    let username = prompt("Username")?;
    let address = {
        let a = prompt(&format!("Email address [{username}]"))?;
        if a.is_empty() { None } else { Some(a) }
    };
    let storage = prompt("Password storage: (k)eyring or (c)ommand [k]")?;
    let password = if storage.starts_with('c') {
        PasswordSource::Command {
            command: prompt("Password command")?,
        }
    } else {
        PasswordSource::Keyring { keyring: true }
    };
    let account = AccountConfig {
        port,
        address,
        ca_file,
        ..AccountConfig::new(&name, &host, &username, password)
    };
    account::check(&config, &account)?;
    let secret = match &account.password {
        PasswordSource::Command { .. } => None,
        PasswordSource::Keyring { .. } => {
            Some(Secret::new(rpassword::prompt_password("Password: ")?))
        }
    };
    account::add(&mut config, paths, account, secret)?;
    println!("saved to {}", paths.config_file().display());
    let client = Client::connect_or_start(paths)?;
    account::await_started(&client, &name, account::START_TIMEOUT)?;
    if !sync_account(&client, &name) {
        bail!(
            "the first sync of '{name}' failed; check the login and run `postvak account add` again"
        );
    }
    Ok(())
}

fn prompt(label: &str) -> Result<String> {
    print!("{label}: ");
    io::stdout().flush()?;
    let mut line = String::new();
    io::stdin().lock().read_line(&mut line)?;
    Ok(line.trim().to_string())
}

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

    #[test]
    fn cli_reference_is_current() {
        let path = concat!(env!("CARGO_MANIFEST_DIR"), "/docs/src/cli.md");
        let generated = clap_markdown::help_markdown::<Cli>();
        if std::env::var_os("POSTVAK_BLESS").is_some() {
            std::fs::write(path, &generated).unwrap();
        }
        assert_eq!(
            std::fs::read_to_string(path).unwrap(),
            generated,
            "docs/src/cli.md is stale; run POSTVAK_BLESS=1 cargo test"
        );
    }

    #[test]
    fn unsubscribe_line_says_what_happened_or_what_to_open() {
        use postvak_core::unsubscribe::Report;
        let line = |method, done| {
            unsubscribe_line(&Report {
                method,
                url: "https://list.example/u".into(),
                done,
            })
        };
        assert_eq!(
            line("one_click", true),
            "unsubscribed: the sender's server accepted it"
        );
        assert_eq!(
            line("one_click", false),
            "would unsubscribe by one-click POST to https://list.example/u"
        );
        assert_eq!(
            line("link", false),
            "open this page to unsubscribe: https://list.example/u"
        );
        assert!(line("mail", false).starts_with("send a mail to unsubscribe: "));
    }
}