jump-core 2.1.2

Search engine, ranking, and plugin host for the jump launcher
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
// Copyright 2026 entro314-labs
// SPDX-License-Identifier: MPL-2.0

//! Alfred-style plugin host.
//!
//! pop-launcher already has a plugin system, and it keeps working — anything
//! installed under `/usr/lib/pop-launcher/plugins` shows up for free through the
//! service. But writing one means implementing the full stateful IPC protocol
//! (indices, activation, context menus, cancellation), which is far more than a
//! shell script should have to do.
//!
//! This host covers the other end of that range: a manifest plus an executable
//! that receives the query on argv and prints JSON. It is deliberately a subset
//! of Alfred's Script Filter format so existing workflow scripts mostly port by
//! changing the manifest.
//!
//! ## Layout
//!
//! ```text
//! ~/.local/share/jump/plugins/github/
//!   manifest.toml
//!   search.sh
//! ```
//!
//! ```toml
//! name = "GitHub"
//! description = "Search your repositories"
//! keyword = "gh"          # optional; omit to run on every query
//! query = "./search.sh"   # invoked as: query <text>
//! activate = "./open.sh"  # invoked as: activate <arg>
//! icon = "github"         # optional icon-theme name or path
//! timeout_ms = 1000       # optional; up to 3000 for slow keyworded plugins
//! ```
//!
//! Items may carry Alfred's `uid` (a stable identity, which is what feeds the
//! launcher's frecency ranking) and `autocomplete` (text that replaces the
//! query on Tab).
//!
//! ## Isolation
//!
//! A plugin is an arbitrary program on the interactive path, so it is held to a
//! hard deadline. Exceeding it (180 ms by default, raised for a keyworded
//! plugin with `timeout_ms`) kills the process and drops its results rather
//! than delaying the frame — a broken plugin degrades its own results and
//! nothing else.

use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::Duration;

use serde::Deserialize;
use tokio::process::Command;

use crate::model::{Icon, Item, ItemKey, Mod, Source};

/// A plugin that has not answered by this point is abandoned for this query.
///
/// Chosen to sit under a 100 ms interaction budget while leaving room for a
/// script that shells out to a local index. A plugin that genuinely needs
/// longer — a network search behind a keyword — raises it with `timeout_ms`,
/// up to [`MAX_QUERY_TIMEOUT`]; stale results are discarded by the frontend's
/// query guard, so a slow answer can be late without being wrong.
const QUERY_TIMEOUT: Duration = Duration::from_millis(180);

/// Hard ceiling on a manifest's `timeout_ms`.
///
/// Three seconds is generous for anything interactive; past it a plugin is not
/// answering a keystroke, it is running a job.
const MAX_QUERY_TIMEOUT: Duration = Duration::from_millis(3000);

/// Ceiling on a plugin's stdout, so a runaway script cannot exhaust memory.
///
/// Enforced while reading: a plugin is cut off at this many bytes, never
/// buffered in full first.
const MAX_OUTPUT_BYTES: usize = 1 << 20;

/// How much of a plugin's stderr is kept for the log line or lint report.
/// The rest is read and discarded, so a chatty plugin cannot stall on a full
/// pipe.
const MAX_STDERR_BYTES: usize = 16 << 10;

/// Why a query command produced no output to parse.
#[derive(Debug, thiserror::Error)]
enum RunError {
    #[error("failed to run: {0}")]
    Io(#[from] std::io::Error),
    #[error("exceeded its {} ms deadline and was killed", .0.as_millis())]
    Deadline(Duration),
    #[error("printed more than {MAX_OUTPUT_BYTES} bytes and was killed")]
    TooLarge,
    #[error("exited {status}; stderr: {stderr}")]
    Failed {
        status: std::process::ExitStatus,
        stderr: String,
    },
}

/// Run a query command under `deadline` and the output cap, returning its
/// stdout.
///
/// The command leads its own process group, and overrunning either limit —
/// or the query being abandoned, by dropping this future — kills the whole
/// group: a shell script's background jobs are part of the query that
/// started them, and must not outlive its dropped results. A command that
/// finishes in time keeps anything it deliberately left behind (a cache
/// refresh with its output redirected, say).
async fn run_query(
    program: &Path,
    directory: &Path,
    text: &str,
    deadline: Duration,
) -> Result<Vec<u8>, RunError> {
    use tokio::io::AsyncReadExt;

    let mut child = Command::new(program)
        .arg(text)
        .current_dir(directory)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .process_group(0)
        .kill_on_drop(true)
        .spawn()?;
    // The group id is the child's pid, which cannot be reused while the
    // child or anything else in its group is alive.
    let mut group = GroupKill(child.id());
    let stdout = child.stdout.take().expect("stdout is piped");
    let stderr = child.stderr.take().expect("stderr is piped");

    // Drained on its own task so it progresses while stdout is read, and
    // ends when the group is killed and the pipe closes.
    let stderr = tokio::spawn(async move {
        let mut kept = Vec::new();
        let mut limited = stderr.take(MAX_STDERR_BYTES as u64);
        let read = limited.read_to_end(&mut kept).await;
        let drained = tokio::io::copy(&mut limited.into_inner(), &mut tokio::io::sink()).await;
        if let Err(error) = read.and(drained) {
            tracing::debug!(%error, "plugin stderr read failed");
        }
        String::from_utf8_lossy(&kept).trim().to_owned()
    });

    let run = async {
        let mut output = Vec::new();
        stdout
            .take(MAX_OUTPUT_BYTES as u64 + 1)
            .read_to_end(&mut output)
            .await?;
        if output.len() > MAX_OUTPUT_BYTES {
            return Err(RunError::TooLarge);
        }
        let status = child.wait().await?;
        // It exited on its own: whatever it left running was left on purpose.
        group.disarm();
        Ok((status, output))
    };

    match tokio::time::timeout(deadline, run).await {
        Ok(Ok((status, output))) if status.success() => Ok(output),
        Ok(Ok((status, _))) => Err(RunError::Failed {
            status,
            stderr: stderr.await.unwrap_or_default(),
        }),
        // On both of these `group` is still armed and kills on return.
        Ok(Err(error)) => Err(error),
        Err(_) => Err(RunError::Deadline(deadline)),
    }
}

/// `SIGKILL`s a plugin's whole process group when dropped, unless
/// [disarmed](Self::disarm).
///
/// A drop guard rather than a call on the error paths, because the query
/// future can also be dropped from outside: the launcher abandons a query
/// the moment the next keystroke supersedes it. `kill_on_drop` then reaches
/// only the script itself.
///
/// Through `kill(1)`, as [`crate::process::terminate`] does, rather than a
/// syscall binding: this runs only when a query was abandoned or a plugin
/// misbehaved. It is spawned, not awaited — a destructor cannot wait — and
/// tokio reaps the dropped `kill` process in the background.
struct GroupKill(Option<u32>);

impl GroupKill {
    fn disarm(&mut self) {
        self.0 = None;
    }
}

impl Drop for GroupKill {
    fn drop(&mut self) {
        let Some(group) = self.0 else {
            return;
        };
        let spawned = Command::new("kill")
            .args(["-KILL", "--", &format!("-{group}")])
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn();
        if let Err(error) = spawned {
            tracing::warn!(group, %error, "could not kill plugin process group");
        }
    }
}

/// Whether `text` can be a plugin keyword: one non-empty word. A keyword is
/// matched up to the first space of the query, so one containing whitespace
/// could never match. The manifest, the Settings override and the Alfred
/// importer all hold keywords to this.
#[must_use]
pub fn is_keyword(text: &str) -> bool {
    !text.is_empty() && !text.contains(char::is_whitespace)
}

/// Parsed `manifest.toml`.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct Manifest {
    /// Human-readable name, shown as the result category.
    pub name: String,
    /// One-line explanation, shown as the result subtitle.
    #[serde(default)]
    pub description: String,
    /// When set, the plugin only runs for queries starting with this word.
    /// When absent the plugin runs on every query and must be fast.
    #[serde(default)]
    pub keyword: Option<String>,
    /// Executable invoked with the query text as a single argument.
    pub query: String,
    /// Executable invoked with the selected item's `arg` on activation.
    /// Without it, activation falls back to the `query` program with
    /// `--activate`.
    #[serde(default)]
    pub activate: Option<String>,
    /// Icon-theme name or path used for items that do not specify their own.
    #[serde(default)]
    pub icon: Option<String>,
    /// Query deadline override in milliseconds, clamped to a hard ceiling.
    /// Only a keyworded plugin may raise it past the interactive default.
    #[serde(default)]
    pub timeout_ms: Option<u64>,
}

impl Manifest {
    /// The deadline this plugin's query command runs under while it answers
    /// to `keyword` — the effective one, which a user override may have
    /// added or removed.
    ///
    /// `timeout_ms` is clamped to 50 ms–3 s, and without a keyword it can
    /// only lower the interactive default: an always-on plugin runs on every
    /// keystroke, and letting it hold a process for seconds each time is
    /// exactly what the default exists to prevent.
    #[must_use]
    pub fn timeout(&self, keyword: Option<&str>) -> Duration {
        let requested = self.timeout_ms.map_or(QUERY_TIMEOUT, |ms| {
            Duration::from_millis(ms).clamp(Duration::from_millis(50), MAX_QUERY_TIMEOUT)
        });
        if keyword.is_some() {
            requested
        } else {
            requested.min(QUERY_TIMEOUT)
        }
    }
}

/// One item emitted by a plugin. A subset of Alfred's Script Filter schema.
#[derive(Debug, Clone, Deserialize)]
struct PluginItem {
    title: String,
    #[serde(default)]
    subtitle: String,
    /// Payload handed back on activation. Defaults to the title.
    #[serde(default)]
    arg: Option<String>,
    /// Icon-theme name or path. Alfred nests this under an object; both the
    /// bare string and `{ "path": "..." }` forms are accepted.
    #[serde(default)]
    icon: Option<PluginIcon>,
    /// Alfred marks unselectable rows with `valid: false`.
    #[serde(default = "default_valid")]
    valid: bool,
    /// Stable identity across queries, Alfred's `uid`. When present it keys
    /// the row — which is what lets frecency learn plugin items — and rows
    /// with the same uid keep their widget state across keystrokes.
    #[serde(default)]
    uid: Option<String>,
    /// Text that replaces the query on Tab, Alfred's `autocomplete`.
    #[serde(default)]
    autocomplete: Option<String>,
    /// State carried from query to activation, Alfred's `variables`: exported
    /// as environment variables to the activation command. Merged over the
    /// response's top-level `variables`, the item's own winning.
    #[serde(default)]
    variables: std::collections::HashMap<String, String>,
    /// Alternate actions on modifier+Enter, Alfred's `mods`, keyed by the
    /// modifier name. Alfred's `cmd` is accepted and mapped to Super, which
    /// is the key in that position on a PC keyboard.
    #[serde(default)]
    mods: std::collections::HashMap<String, PluginMod>,
}

/// One alternate action as a plugin writes it.
#[derive(Debug, Clone, Deserialize)]
struct PluginMod {
    #[serde(default)]
    subtitle: String,
    #[serde(default)]
    arg: Option<String>,
    /// Alfred lets a mod be switched off without removing it.
    #[serde(default = "default_valid")]
    valid: bool,
    #[serde(default)]
    variables: std::collections::HashMap<String, String>,
}

/// Modifier names a plugin may use, normalised to what the frontend binds.
///
/// Anything unrecognised is dropped rather than guessed at: a mod nobody can
/// press is worse than no mod, because it takes a row in the action panel.
fn normalise_modifier(name: &str) -> Option<&'static str> {
    match name.trim().to_lowercase().as_str() {
        "ctrl" | "control" => Some("ctrl"),
        "alt" | "option" => Some("alt"),
        "shift" => Some("shift"),
        // Alfred's `cmd` is the key in the Super position on a PC keyboard.
        "cmd" | "command" | "super" | "meta" => Some("super"),
        _ => None,
    }
}

const fn default_valid() -> bool {
    true
}

#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
enum PluginIcon {
    Named(String),
    Path {
        #[serde(alias = "name")]
        path: String,
    },
}

impl PluginIcon {
    fn into_icon(self) -> Icon {
        match self {
            Self::Named(name) | Self::Path { path: name } => Icon::Name(name),
        }
    }
}

#[derive(Debug, Clone, Deserialize)]
struct PluginResponse {
    items: Vec<PluginItem>,
    /// Variables applied to every item, Alfred's top-level `variables`.
    #[serde(default)]
    variables: std::collections::HashMap<String, String>,
    /// Seconds after which the same query should run again, Alfred's `rerun`
    /// — how a progress-reporting or polling plugin streams updates.
    #[serde(default)]
    rerun: Option<f64>,
}

/// Bounds on a plugin's `rerun` interval. Alfred allows 0.1–5.0 s; the floor
/// here is higher because every rerun forks a process, and a launcher that
/// respawns scripts ten times a second shows up in power measurements.
const RERUN_RANGE: std::ops::RangeInclusive<f64> = 0.5..=5.0;

/// A completed plugin query: the items, plus how long until the plugins that
/// asked to be re-run should see the same query again.
#[derive(Debug, Clone, Default)]
pub struct QueryResults {
    /// Everything the plugins returned, concatenated.
    pub items: Vec<Item>,
    /// Soonest requested rerun across the plugins that answered.
    pub rerun: Option<Duration>,
}

/// The item's variables over the response's, sorted for a stable identity —
/// the result lives inside [`Source::Plugin`], which is compared by `Eq`.
fn merge_variables(
    response: &std::collections::HashMap<String, String>,
    item: std::collections::HashMap<String, String>,
) -> Vec<(String, String)> {
    let mut merged = response.clone();
    merged.extend(item);
    let mut variables: Vec<(String, String)> = merged.into_iter().collect();
    variables.sort();
    variables
}

/// A discovered plugin: its manifest plus the directory it lives in.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Plugin {
    /// The parsed `manifest.toml`.
    pub manifest: Manifest,
    /// Where the plugin lives. Commands are resolved relative to it.
    pub directory: PathBuf,
    /// Directory name, used as the stable plugin identifier.
    pub id: String,
}

impl Plugin {
    /// Resolve a manifest command against the plugin directory so `./search.sh`
    /// works regardless of the launcher's working directory.
    fn resolve(&self, command: &str) -> PathBuf {
        let path = Path::new(command);
        if path.is_absolute() {
            path.to_path_buf()
        } else {
            self.directory.join(path)
        }
    }

    /// Whether this plugin should run for `query`, and the text it should see.
    ///
    /// A keyworded plugin receives the query with its keyword stripped, matching
    /// Alfred: typing `gh jump` hands the plugin `jump`. The host passes the
    /// *effective* keyword, so a user override replaces the manifest's here.
    #[must_use]
    pub fn match_query_as<'a>(&self, keyword: Option<&str>, query: &'a str) -> Option<&'a str> {
        match keyword {
            None => Some(query),
            Some(keyword) => {
                let rest = query.strip_prefix(keyword)?;
                match rest.strip_prefix(' ') {
                    Some(rest) => Some(rest.trim_start()),
                    // Bare keyword with nothing after it: run with an empty
                    // query so the plugin can show a default list.
                    None if rest.is_empty() => Some(""),
                    None => None,
                }
            }
        }
    }

    /// [`Self::match_query_as`] with the manifest's own keyword.
    #[must_use]
    pub fn match_query<'a>(&self, query: &'a str) -> Option<&'a str> {
        self.match_query_as(self.manifest.keyword.as_deref(), query)
    }

    /// Run the plugin's query command under `deadline` and parse its
    /// results, plus the rerun interval it asked for, if any.
    async fn query(&self, text: &str, deadline: Duration) -> (Vec<Item>, Option<Duration>) {
        let program = self.resolve(&self.manifest.query);

        let stdout = match run_query(&program, &self.directory, text, deadline).await {
            Ok(stdout) => stdout,
            Err(error) => {
                tracing::warn!(plugin = %self.id, ?program, %error, "plugin query dropped");
                return (Vec::new(), None);
            }
        };

        let response: PluginResponse = match serde_json::from_slice(&stdout) {
            Ok(response) => response,
            Err(error) => {
                tracing::warn!(plugin = %self.id, %error, "plugin emitted invalid JSON");
                return (Vec::new(), None);
            }
        };

        let fallback_icon = self.manifest.icon.as_ref().map(|n| Icon::Name(n.clone()));
        let PluginResponse {
            items,
            variables: response_variables,
            rerun,
        } = response;

        // NaN and absurd values from a script must not become a timer.
        let rerun = rerun.filter(|seconds| seconds.is_finite()).map(|seconds| {
            Duration::from_secs_f64(seconds.clamp(*RERUN_RANGE.start(), *RERUN_RANGE.end()))
        });

        let items = items
            .into_iter()
            .filter(|item| item.valid)
            .map(|item| {
                let arg = item.arg.unwrap_or_else(|| item.title.clone());
                let variables = merge_variables(&response_variables, item.variables);

                // Alternates inherit the item's arg and variables unless they
                // override them, which is what makes the common case — same
                // payload, different action — a two-line mod.
                let mut mods: Vec<Mod> = item
                    .mods
                    .into_iter()
                    .filter(|(_, alternate)| alternate.valid)
                    .filter_map(|(modifier, alternate)| {
                        let modifier = normalise_modifier(&modifier)?;
                        let mut merged: std::collections::HashMap<String, String> =
                            variables.iter().cloned().collect();
                        merged.extend(alternate.variables);
                        let mut alternate_variables: Vec<(String, String)> =
                            merged.into_iter().collect();
                        alternate_variables.sort();

                        Some(Mod {
                            modifier: modifier.to_owned(),
                            subtitle: alternate.subtitle,
                            arg: alternate.arg.unwrap_or_else(|| arg.clone()),
                            variables: alternate_variables,
                        })
                    })
                    .collect();
                // HashMap iteration order is not stable; the action panel is.
                mods.sort_by(|a, b| a.modifier.cmp(&b.modifier));
                // Prefer the uid: an item whose arg changes with the query — a
                // search URL, say — would otherwise get a new identity every
                // keystroke, and frecency could never learn it.
                let identity = item.uid.as_deref().unwrap_or(&arg);
                Item {
                    // Namespaced by plugin id so two plugins returning the same
                    // title stay distinct rows.
                    key: ItemKey(format!("plugin:{}:{identity}", self.id)),
                    // Plugin items are not addressable by pop-launcher indice.
                    id: 0,
                    title: item.title,
                    subtitle: if item.subtitle.is_empty() {
                        self.manifest.description.clone()
                    } else {
                        item.subtitle
                    },
                    icon: item
                        .icon
                        .map(PluginIcon::into_icon)
                        .or_else(|| fallback_icon.clone()),
                    category_icon: fallback_icon.clone(),
                    window: None,
                    source: Source::Plugin {
                        plugin: self.id.clone(),
                        arg,
                        variables,
                        mods,
                    },
                    autocomplete: item.autocomplete,
                    score: 0.0,
                }
            })
            .collect();

        (items, rerun)
    }

    /// Run the plugin's activation command for `arg`.
    ///
    /// `variables` — the item's merged `variables`, Alfred-style — are
    /// exported into the command's environment, which is how a plugin carries
    /// state from query to activation without encoding it all into `arg`.
    ///
    /// Spawned detached: the launcher dismisses immediately and does not wait
    /// for the action to finish.
    pub fn activate(&self, arg: &str, variables: &[(String, String)]) {
        let (program, extra) = match self.manifest.activate.as_deref() {
            Some(activate) => (self.resolve(activate), Vec::new()),
            None => (
                self.resolve(&self.manifest.query),
                vec!["--activate".to_owned()],
            ),
        };

        let result = Command::new(&program)
            .envs(variables.iter().map(|(key, value)| (key, value)))
            .args(extra)
            .arg(arg)
            .current_dir(&self.directory)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn();

        match result {
            Ok(mut child) => {
                // Reap in the background so the child does not become a zombie.
                tokio::spawn(async move {
                    let _ = child.wait().await;
                });
            }
            Err(error) => {
                tracing::error!(plugin = %self.id, ?program, %error, "failed to activate plugin item");
            }
        }
    }
}

/// All discovered plugins.
#[derive(Debug, Default, Clone)]
pub struct PluginHost {
    plugins: Vec<Plugin>,
    /// Plugin ids the user has switched off. They stay discovered — the
    /// settings window needs to list them — but never run.
    disabled: std::collections::HashSet<String>,
    /// Per-plugin keyword overrides: the alias mechanism. An entry replaces
    /// the manifest's keyword without editing the plugin; an empty string
    /// removes the keyword, making the plugin run on every query.
    keyword_overrides: std::collections::HashMap<String, String>,
}

impl PluginHost {
    /// Discover plugins in [`Self::roots`].
    #[must_use]
    pub fn discover() -> Self {
        Self::discover_in(&Self::roots())
    }

    /// Where plugins are discovered, in shadowing order: the user's data
    /// directory, then the system data directories (`$XDG_DATA_DIRS`, so
    /// distro packages under `/usr/share/jump/plugins` are picked up with no
    /// configuration).
    ///
    /// The user's directory is searched first and wins on an id collision, so
    /// copying a packaged plugin into `~/.local/share/jump/plugins` to modify
    /// it shadows the packaged one rather than duplicating it.
    #[must_use]
    pub fn roots() -> Vec<PathBuf> {
        let mut roots: Vec<PathBuf> = dirs::data_dir()
            .map(|dir| dir.join("jump").join("plugins"))
            .into_iter()
            .collect();

        let system = std::env::var_os("XDG_DATA_DIRS")
            .filter(|value| !value.is_empty())
            .map_or_else(
                || {
                    vec![
                        PathBuf::from("/usr/local/share"),
                        PathBuf::from("/usr/share"),
                    ]
                },
                |value| std::env::split_paths(&value).collect(),
            );
        roots.extend(
            system
                .into_iter()
                .map(|dir| dir.join("jump").join("plugins")),
        );
        roots
    }

    /// Discover plugins under `roots`, earlier roots shadowing later ones.
    ///
    /// Directories without a readable manifest are skipped with a warning; a
    /// malformed plugin must never prevent the launcher from starting.
    #[must_use]
    pub fn discover_in(roots: &[PathBuf]) -> Self {
        let mut plugins: Vec<Plugin> = Vec::new();

        for root in roots {
            let entries = match std::fs::read_dir(root) {
                Ok(entries) => entries,
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
                Err(error) => {
                    tracing::warn!(%error, ?root, "failed to read plugin directory");
                    continue;
                }
            };

            for entry in entries.flatten() {
                let directory = entry.path();
                if !directory.is_dir() {
                    continue;
                }

                let Some(id) = directory
                    .file_name()
                    .and_then(|name| name.to_str())
                    .map(ToOwned::to_owned)
                else {
                    continue;
                };

                if plugins.iter().any(|plugin| plugin.id == id) {
                    tracing::debug!(plugin = %id, ?directory, "shadowed by an earlier root");
                    continue;
                }

                let manifest_path = directory.join("manifest.toml");
                let contents = match std::fs::read_to_string(&manifest_path) {
                    Ok(contents) => contents,
                    Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
                    Err(error) => {
                        tracing::warn!(%error, ?manifest_path, "failed to read plugin manifest");
                        continue;
                    }
                };

                let manifest: Manifest = match toml::from_str(&contents) {
                    Ok(manifest) => manifest,
                    Err(error) => {
                        tracing::warn!(%error, ?manifest_path, "invalid plugin manifest");
                        continue;
                    }
                };

                tracing::info!(plugin = %id, keyword = ?manifest.keyword, "loaded plugin");
                plugins.push(Plugin {
                    manifest,
                    directory,
                    id,
                });
            }
        }

        Self {
            plugins,
            disabled: std::collections::HashSet::new(),
            keyword_overrides: std::collections::HashMap::new(),
        }
    }

    /// Take the plugins from a fresh discovery, keeping the user's disabled
    /// set and keyword overrides, which belong to settings rather than to
    /// what is on disk. Returns whether the plugin set actually changed.
    pub fn replace_plugins(&mut self, discovered: Self) -> bool {
        if self.plugins == discovered.plugins {
            return false;
        }
        self.plugins = discovered.plugins;
        true
    }

    /// Replace the set of switched-off plugins, e.g. when settings change.
    pub fn set_disabled<I, S>(&mut self, ids: I)
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.disabled = ids.into_iter().map(Into::into).collect();
    }

    /// Replace the keyword overrides, e.g. when settings change.
    pub fn set_keyword_overrides<I, K, V>(&mut self, overrides: I)
    where
        I: IntoIterator<Item = (K, V)>,
        K: Into<String>,
        V: Into<String>,
    {
        self.keyword_overrides = overrides
            .into_iter()
            .map(|(id, keyword)| (id.into(), keyword.into()))
            .collect();
    }

    /// The keyword `plugin` currently answers to: the user's override when
    /// one exists (empty meaning "no keyword"), else the manifest's.
    #[must_use]
    pub fn effective_keyword<'a>(&'a self, plugin: &'a Plugin) -> Option<&'a str> {
        match self.keyword_overrides.get(&plugin.id) {
            Some(keyword) if keyword.is_empty() => None,
            Some(keyword) => Some(keyword.as_str()),
            None => plugin.manifest.keyword.as_deref(),
        }
    }

    /// Every discovered plugin, the switched-off ones included, with whether
    /// each is currently enabled. This is the settings window's list.
    pub fn all(&self) -> impl Iterator<Item = (&Plugin, bool)> {
        self.plugins
            .iter()
            .map(|plugin| (plugin, !self.disabled.contains(&plugin.id)))
    }

    /// Whether no plugins were discovered.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.plugins.is_empty()
    }

    /// Look up an *enabled* plugin. Activation goes through here, so a plugin
    /// disabled between query and click does nothing rather than running.
    #[must_use]
    pub fn get(&self, id: &str) -> Option<&Plugin> {
        self.plugins
            .iter()
            .filter(|plugin| !self.disabled.contains(&plugin.id))
            .find(|plugin| plugin.id == id)
    }

    /// Query every plugin that matches, concurrently.
    ///
    /// Plugins run in parallel and share the same deadline, so total latency is
    /// the slowest matching plugin rather than the sum.
    pub async fn query(&self, text: &str) -> QueryResults {
        let matching: Vec<_> = self
            .plugins
            .iter()
            .filter(|plugin| !self.disabled.contains(&plugin.id))
            .filter_map(|plugin| {
                plugin
                    .match_query_as(self.effective_keyword(plugin), text)
                    .map(|query| (plugin, query))
            })
            .collect();

        if matching.is_empty() {
            return QueryResults::default();
        }

        // A keyworded plugin takes over the query entirely: once the user types
        // `gh …` they are addressing that plugin, not searching their apps.
        let keyworded: Vec<_> = matching
            .iter()
            .filter(|(plugin, _)| self.effective_keyword(plugin).is_some())
            .collect();

        let selected: Vec<_> = if keyworded.is_empty() {
            matching.iter().collect()
        } else {
            keyworded
        };

        let futures = selected.into_iter().map(|(plugin, query)| {
            let deadline = plugin.manifest.timeout(self.effective_keyword(plugin));
            plugin.query(query, deadline)
        });

        let mut results = QueryResults::default();
        for (items, rerun) in futures::future::join_all(futures).await {
            results.items.extend(items);
            // The soonest rerun wins: a plugin that asked to stream must not
            // be held to a slower neighbour's interval.
            results.rerun = match (results.rerun, rerun) {
                (Some(a), Some(b)) => Some(a.min(b)),
                (a, b) => a.or(b),
            };
        }
        results
    }

    /// Whether a keyworded plugin claims this query, meaning pop-launcher
    /// results should be suppressed.
    #[must_use]
    pub fn is_claimed(&self, text: &str) -> bool {
        self.plugins
            .iter()
            .filter(|plugin| !self.disabled.contains(&plugin.id))
            .any(|plugin| {
                let keyword = self.effective_keyword(plugin);
                keyword.is_some() && plugin.match_query_as(keyword, text).is_some()
            })
    }
}

/// What `lint` found. Errors stop the plugin working; warnings do not.
#[derive(Debug, Default)]
pub struct LintReport {
    /// Problems that stop the plugin from working at all.
    pub errors: Vec<String>,
    /// Problems worth fixing that do not stop it working.
    pub warnings: Vec<String>,
    /// Items the sample query produced, when it ran at all.
    pub items: usize,
}

impl LintReport {
    /// Whether nothing blocking was found. Warnings are still allowed.
    #[must_use]
    pub fn is_clean(&self) -> bool {
        self.errors.is_empty()
    }
}

/// Check a plugin directory: the manifest, the commands it names, and the
/// output of one sample query against the item schema.
///
/// This *runs* the plugin's query command — that is the point: the schema
/// violations that break a plugin live in its output, not its manifest.
pub async fn lint(directory: &Path, sample_query: &str) -> LintReport {
    let mut report = LintReport::default();

    let manifest_path = directory.join("manifest.toml");
    let contents = match std::fs::read_to_string(&manifest_path) {
        Ok(contents) => contents,
        Err(error) => {
            report
                .errors
                .push(format!("cannot read {}: {error}", manifest_path.display()));
            return report;
        }
    };

    let manifest: Manifest = match toml::from_str(&contents) {
        Ok(manifest) => manifest,
        Err(error) => {
            report
                .errors
                .push(format!("manifest does not parse: {error}"));
            return report;
        }
    };

    if let Some(keyword) = manifest.keyword.as_deref() {
        if !is_keyword(keyword) {
            report.errors.push(format!(
                "keyword {keyword:?} must be one non-empty word — it is matched \
                 up to the first space of the query"
            ));
        }
    } else {
        report.warnings.push(
            "no keyword: the plugin runs on every keystroke and must answer \
             well inside 180 ms"
                .to_owned(),
        );
    }

    if let Some(ms) = manifest.timeout_ms {
        let applied = manifest.timeout(manifest.keyword.as_deref()).as_millis();
        if u128::from(ms) != applied {
            let why = if manifest.keyword.is_none() && applied == QUERY_TIMEOUT.as_millis() {
                " — only a keyworded plugin may take longer than the interactive default"
            } else {
                ""
            };
            report
                .warnings
                .push(format!("timeout_ms = {ms} is clamped to {applied} ms{why}"));
        }
    }

    let check_command = |report: &mut LintReport, label: &str, command: &str| {
        let path = if Path::new(command).is_absolute() {
            PathBuf::from(command)
        } else {
            directory.join(command)
        };
        if !path.is_file() {
            report
                .errors
                .push(format!("{label} command {} does not exist", path.display()));
            return;
        }
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let executable = path
                .metadata()
                .map(|meta| meta.permissions().mode() & 0o111 != 0)
                .unwrap_or(false);
            if !executable {
                report.errors.push(format!(
                    "{label} command {} is not executable (chmod +x)",
                    path.display()
                ));
            }
        }
    };
    check_command(&mut report, "query", &manifest.query);
    if let Some(activate) = manifest.activate.as_deref() {
        check_command(&mut report, "activate", activate);
    }
    if !report.errors.is_empty() {
        return report;
    }

    // Run the sample query exactly the way the launcher would.
    let plugin = Plugin {
        manifest,
        directory: directory.to_path_buf(),
        id: directory
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or("plugin")
            .to_owned(),
    };
    let program = plugin.resolve(&plugin.manifest.query);
    let stdout = match run_query(
        &program,
        &plugin.directory,
        sample_query,
        plugin.manifest.timeout(plugin.manifest.keyword.as_deref()),
    )
    .await
    {
        Ok(stdout) => stdout,
        Err(error) => {
            report.errors.push(format!("query command {error}"));
            return report;
        }
    };

    match serde_json::from_slice::<PluginResponse>(&stdout) {
        Ok(response) => {
            report.items = response.items.len();
            if response.items.is_empty() {
                report
                    .warnings
                    .push("sample query produced no items".to_owned());
            }
            for item in &response.items {
                if item.uid.is_none() {
                    report.warnings.push(format!(
                        "item {:?} has no uid — without one, usage ranking \
                         cannot learn it",
                        item.title
                    ));
                }
            }
        }
        Err(error) => {
            report
                .errors
                .push(format!("output is not valid script-filter JSON: {error}"));
        }
    }

    report
}

/// The keyword, and plugin directory name, `jump plugin new <name>` derives
/// from `name`: lowercased, with runs of whitespace joined by dashes.
///
/// `None` when that cannot name a directory inside the plugin root — empty,
/// hidden, or containing a path separator — so `../x` cannot scaffold
/// outside it.
#[must_use]
pub fn scaffold_keyword(name: &str) -> Option<String> {
    let keyword = name
        .to_lowercase()
        .split_whitespace()
        .collect::<Vec<_>>()
        .join("-");
    let usable =
        !keyword.is_empty() && !keyword.starts_with('.') && !keyword.contains(['/', '\\', '\0']);
    usable.then_some(keyword)
}

/// Write a runnable plugin skeleton for `name` into a new directory under
/// `root`, named by [`scaffold_keyword`]. Returns the directory and the
/// keyword.
///
/// Refuses to touch a directory that already exists — a scaffolder that can
/// overwrite a real plugin is a footgun, not a convenience. `name` is
/// arbitrary user text, so it reaches the manifest as an escaped TOML string
/// and the script as a quoted shell variable, never as syntax.
///
/// # Errors
///
/// [`std::io::ErrorKind::InvalidInput`] if `name` yields no usable
/// directory name, [`std::io::ErrorKind::AlreadyExists`] if the directory is
/// already there, and any I/O error from creating the directory or writing
/// the files in it.
pub fn scaffold(root: &Path, name: &str) -> std::io::Result<(PathBuf, String)> {
    let Some(keyword) = scaffold_keyword(name) else {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            format!("{name:?} does not make a plugin directory name"),
        ));
    };
    let directory = root.join(&keyword);
    if directory.exists() {
        return Err(std::io::Error::new(
            std::io::ErrorKind::AlreadyExists,
            format!("{} already exists", directory.display()),
        ));
    }
    std::fs::create_dir_all(&directory)?;

    let toml_string = |text: &str| toml::Value::String(text.to_owned()).to_string();
    std::fs::write(
        directory.join("manifest.toml"),
        format!(
            "name = {}\n\
             description = \"Describe what this plugin searches\"\n\
             keyword = {}\n\
             query = \"./search.sh\"\n\
             # activate = \"./open.sh\"   # separate action command, optional\n\
             icon = \"system-search-symbolic\"\n\
             # timeout_ms = 1000          # up to 3000 for slow keyworded plugins\n",
            toml_string(name),
            toml_string(&keyword),
        ),
    )?;

    // Single-quoted for the shell: only a quote itself needs escaping there.
    let shell_name = name.replace('\'', r"'\''");
    let script = directory.join("search.sh");
    std::fs::write(
        &script,
        format!(
            "#!/bin/sh\n\
             # jump runs this with the query as $1 and reads script-filter\n\
             # JSON from stdout. Without an `activate` command in the\n\
             # manifest, activation re-runs this script as: search.sh\n\
             # --activate <arg>.\n\
             if [ \"$1\" = \"--activate\" ]; then\n\
             \t# \"$2\" is the chosen item's arg.\n\
             \texit 0\n\
             fi\n\
             \n\
             name='{shell_name}'\n\
             query=\"$1\"\n\
             # Text going into a JSON string needs its backslashes and quotes\n\
             # escaped.\n\
             json() {{ printf '%s' \"$1\" | sed 's/[\\\\\"]/\\\\&/g'; }}\n\
             printf '{{\"items\":[{{\"uid\":\"hello\",\"title\":\"Hello %s\",\
             \"subtitle\":\"%s\",\"arg\":\"%s\"}}]}}' \
             \"$(json \"${{query:-world}}\")\" \"$(json \"$name\")\" \"$(json \"$query\")\"\n"
        ),
    )?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755))?;
    }
    Ok((directory, keyword))
}

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

    fn plugin(keyword: Option<&str>) -> Plugin {
        Plugin {
            manifest: Manifest {
                name: "Test".to_owned(),
                description: String::new(),
                keyword: keyword.map(ToOwned::to_owned),
                query: "./q".to_owned(),
                activate: None,
                icon: None,
                timeout_ms: None,
            },
            directory: PathBuf::from("/tmp"),
            id: "test".to_owned(),
        }
    }

    #[test]
    fn keywordless_plugin_sees_whole_query() {
        assert_eq!(plugin(None).match_query("hello there"), Some("hello there"));
    }

    #[test]
    fn keyword_is_stripped() {
        assert_eq!(plugin(Some("gh")).match_query("gh jump"), Some("jump"));
    }

    #[test]
    fn bare_keyword_yields_empty_query() {
        assert_eq!(plugin(Some("gh")).match_query("gh"), Some(""));
    }

    #[test]
    fn a_keyword_is_one_non_empty_word() {
        assert!(is_keyword("gh"));
        assert!(is_keyword("=="));
        for bad in ["", "gh x", " gh", "gh\t"] {
            assert!(!is_keyword(bad), "{bad:?}");
        }
    }

    #[test]
    fn keyword_requires_word_boundary() {
        // "ghost" must not be read as the "gh" keyword plus "ost".
        assert_eq!(plugin(Some("gh")).match_query("ghost"), None);
    }

    #[test]
    fn non_matching_keyword_is_skipped() {
        assert_eq!(plugin(Some("gh")).match_query("firefox"), None);
    }

    #[test]
    fn timeout_is_clamped_to_the_ceiling() {
        let mut manifest = plugin(None).manifest;
        let keyword = Some("gh");
        assert_eq!(manifest.timeout(keyword), Duration::from_millis(180));

        manifest.timeout_ms = Some(60_000);
        assert_eq!(manifest.timeout(keyword), Duration::from_millis(3000));

        manifest.timeout_ms = Some(1);
        assert_eq!(manifest.timeout(keyword), Duration::from_millis(50));
    }

    #[test]
    fn only_a_keyworded_plugin_may_raise_its_deadline() {
        // An always-on plugin runs on every keystroke; `timeout_ms` exists so
        // a keyworded network plugin can be slow, not so every plugin can.
        let mut manifest = plugin(None).manifest;
        manifest.timeout_ms = Some(3000);
        assert_eq!(manifest.timeout(None), Duration::from_millis(180));
        assert_eq!(manifest.timeout(Some("gh")), Duration::from_millis(3000));

        manifest.timeout_ms = Some(100);
        assert_eq!(manifest.timeout(None), Duration::from_millis(100));
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn the_host_holds_an_always_on_plugin_to_the_interactive_deadline() {
        // The deadline follows the keyword the plugin answers to right now,
        // so an override that removes the keyword removes the allowance.
        let root = tempfile::tempdir().expect("tempdir");
        let mut slow = scripted(
            root.path(),
            "#!/bin/sh\nsleep 0.5\necho '{\"items\":[{\"title\":\"late\"}]}'\n",
            Some(3000),
        );
        slow.id = "slow".to_owned();
        let mut host = PluginHost {
            plugins: vec![slow],
            ..PluginHost::default()
        };
        assert_eq!(host.query("t x").await.items.len(), 1);

        // Empty is the proof: the script answers after half a second, so an
        // answer here could only mean the 180 ms deadline was not applied.
        // (A wall-clock bound on top of that measured how busy the machine
        // was, and failed when it was.)
        host.set_keyword_overrides([("slow", "")]);
        assert!(host.query("x").await.items.is_empty());
    }

    #[test]
    fn uid_and_autocomplete_parse_from_alfred_json() {
        let response: PluginResponse = serde_json::from_str(
            r#"{"items":[
                {"uid":"repo","title":"jump","arg":"https://example.com/?q=jump",
                 "autocomplete":"gh jump ", "icon":{"path":"/tmp/icon.png"}},
                {"title":"plain"}
            ]}"#,
        )
        .expect("alfred json parses");

        assert_eq!(response.items[0].uid.as_deref(), Some("repo"));
        assert_eq!(response.items[0].autocomplete.as_deref(), Some("gh jump "));
        assert_eq!(response.items[1].uid, None);
    }

    #[test]
    fn rerun_parses_and_is_clamped_sanely() {
        let parse = |json: &str| -> Option<f64> {
            serde_json::from_str::<PluginResponse>(json)
                .expect("json parses")
                .rerun
        };
        assert_eq!(parse(r#"{"items":[]}"#), None);
        assert_eq!(parse(r#"{"items":[],"rerun":1.5}"#), Some(1.5));

        // The clamp applied where the value becomes a timer.
        let clamp = |seconds: f64| seconds.clamp(*RERUN_RANGE.start(), *RERUN_RANGE.end());
        assert_eq!(clamp(0.1), 0.5);
        assert_eq!(clamp(60.0), 5.0);
        assert_eq!(clamp(2.0), 2.0);
    }

    #[test]
    fn mods_normalise_inherit_and_override() {
        let response: PluginResponse = serde_json::from_str(
            r#"{"variables":{"SESSION":"abc"},
                "items":[{"title":"repo","arg":"main",
                  "mods":{
                    "cmd":{"subtitle":"Open on the web","arg":"https://example.com"},
                    "alt":{"subtitle":"Copy","variables":{"MODE":"copy"}},
                    "shift":{"subtitle":"Off","valid":false},
                    "hyper":{"subtitle":"Unbindable"}
                  }}]}"#,
        )
        .expect("alfred json parses");

        let item = &response.items[0];
        assert_eq!(normalise_modifier("cmd"), Some("super"));
        assert_eq!(normalise_modifier("Control"), Some("ctrl"));
        assert_eq!(normalise_modifier("hyper"), None);

        // valid:false and unbindable modifiers are dropped before they can
        // take a row in the action panel.
        let usable: Vec<&String> = item
            .mods
            .iter()
            .filter(|(_, m)| m.valid)
            .filter(|(name, _)| normalise_modifier(name).is_some())
            .map(|(name, _)| name)
            .collect();
        assert_eq!(usable.len(), 2);

        // An alternate without its own arg inherits the item's.
        assert_eq!(item.mods["alt"].arg, None);
        assert_eq!(item.mods["cmd"].arg.as_deref(), Some("https://example.com"));
    }

    #[test]
    fn item_variables_win_over_response_variables() {
        let response: PluginResponse = serde_json::from_str(
            r#"{"variables":{"SESSION":"abc","MODE":"list"},
                "items":[{"title":"one","variables":{"MODE":"open"}},
                         {"title":"two"}]}"#,
        )
        .expect("alfred json parses");

        let merged = merge_variables(&response.variables, response.items[0].variables.clone());
        assert_eq!(
            merged,
            vec![
                ("MODE".to_owned(), "open".to_owned()),
                ("SESSION".to_owned(), "abc".to_owned()),
            ]
        );

        // An item without its own variables inherits the response's.
        let inherited = merge_variables(&response.variables, response.items[1].variables.clone());
        assert_eq!(inherited.len(), 2);
        assert!(inherited.contains(&("MODE".to_owned(), "list".to_owned())));
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn scaffold_produces_a_plugin_that_lints_clean() {
        let root = tempfile::tempdir().expect("tempdir");

        let (directory, keyword) = scaffold(root.path(), "Demo").expect("scaffold succeeds");
        assert_eq!(directory, root.path().join("demo"));
        assert_eq!(keyword, "demo");
        // Refuses to overwrite what it just made.
        assert!(scaffold(root.path(), "Demo").is_err());

        let report = lint(&directory, "hello").await;
        assert!(report.is_clean(), "unexpected errors: {:?}", report.errors);
        assert_eq!(report.items, 1);
        assert!(report.warnings.is_empty(), "{:?}", report.warnings);
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_scaffold_name_is_data_not_syntax() {
        // The name is whatever the user typed; quotes, `%` and `'` must reach
        // the manifest and the output as text, not break either.
        let root = tempfile::tempdir().expect("tempdir");
        let name = r#"It's "100%" done"#;
        let (directory, keyword) = scaffold(root.path(), name).expect("scaffold succeeds");
        assert_eq!(keyword, r#"it's-"100%"-done"#);

        let manifest: Manifest = toml::from_str(
            &std::fs::read_to_string(directory.join("manifest.toml")).expect("manifest"),
        )
        .expect("the manifest parses");
        assert_eq!(manifest.name, name);

        let output = std::process::Command::new(directory.join("search.sh"))
            .arg(r#"say "hi" \"#)
            .output()
            .expect("the script runs");
        let response: serde_json::Value =
            serde_json::from_slice(&output.stdout).expect("the output is JSON");
        let item = &response["items"][0];
        assert_eq!(item["subtitle"], name);
        assert_eq!(item["title"], r#"Hello say "hi" \"#);
    }

    #[test]
    fn a_scaffold_cannot_name_a_directory_outside_the_root() {
        for name in ["../x", "a/b", ".hidden", "   ", ""] {
            assert_eq!(scaffold_keyword(name), None, "{name:?}");
        }
        assert_eq!(scaffold_keyword("My  Plugin").as_deref(), Some("my-plugin"));
        let root = tempfile::tempdir().expect("tempdir");
        let error = scaffold(&root.path().join("plugins"), "../x").expect_err("refused");
        assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
        assert!(!root.path().join("x").exists());
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn lint_reports_missing_and_broken_pieces() {
        let root = tempfile::tempdir().expect("tempdir");

        // No manifest at all.
        let report = lint(root.path(), "x").await;
        assert!(!report.is_clean());

        // A manifest naming a command that does not exist.
        let directory = root.path().join("broken");
        std::fs::create_dir_all(&directory).expect("dir");
        std::fs::write(
            directory.join("manifest.toml"),
            "name = \"Broken\"\nkeyword = \"two words\"\nquery = \"./missing.sh\"\n",
        )
        .expect("manifest");
        let report = lint(&directory, "x").await;
        assert_eq!(report.errors.len(), 2, "{:?}", report.errors);
    }

    /// A plugin in a fresh directory whose query command is `script`.
    fn scripted(root: &Path, script: &str, timeout_ms: Option<u64>) -> Plugin {
        use std::os::unix::fs::PermissionsExt;

        let path = root.join("q");
        std::fs::write(&path, script).expect("script");
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).expect("chmod");
        let mut plugin = plugin(Some("t"));
        plugin.directory = root.to_path_buf();
        plugin.manifest.timeout_ms = timeout_ms;
        plugin
    }

    /// Whether `pid` is still a running process (a zombie counts as gone).
    fn alive(pid: u32) -> bool {
        std::fs::read_to_string(format!("/proc/{pid}/stat")).is_ok_and(|stat| {
            stat.rsplit(") ")
                .next()
                .is_some_and(|rest| !rest.starts_with('Z'))
        })
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn oversized_output_is_refused_without_waiting_for_the_deadline() {
        // The cap is a memory bound, so it has to be enforced while reading:
        // a plugin that has already printed more than the cap is cut off
        // there, not buffered in full until it exits or the deadline fires.
        let root = tempfile::tempdir().expect("tempdir");
        let plugin = scripted(
            root.path(),
            "#!/bin/sh\nhead -c 2000000 /dev/zero\nsleep 5\n",
            Some(3000),
        );

        let started = std::time::Instant::now();
        let (items, _) = plugin.query("x", plugin.manifest.timeout(Some("t"))).await;
        assert!(items.is_empty());
        assert!(
            started.elapsed() < Duration::from_millis(1500),
            "took {:?}: output was buffered until the deadline",
            started.elapsed()
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn an_overrunning_plugin_is_killed_with_its_children() {
        // "Killed" has to mean everything the plugin started for this query,
        // not just the script: a shell's background job would otherwise keep
        // running, detached, after its results were dropped.
        //
        // A second, not the 100 ms this once used: on a machine busy enough
        // for the shell to take longer than that to start, the deadline
        // killed the script before it had a child to record.
        let root = tempfile::tempdir().expect("tempdir");
        let plugin = scripted(
            root.path(),
            "#!/bin/sh\nsleep 30 &\necho $! > child.pid\nwait\n",
            Some(1000),
        );

        let (items, _) = plugin.query("x", plugin.manifest.timeout(Some("t"))).await;
        assert!(items.is_empty());

        assert!(
            !outlives(&root.path().join("child.pid")).await,
            "the plugin's child outlived the deadline"
        );
    }

    /// Whether the process whose pid was written to `pid_file` is still
    /// running two seconds on. Kills it either way, so a failing test does
    /// not leave a stray behind for the rest of the suite.
    async fn outlives(pid_file: &Path) -> bool {
        let pid: u32 = std::fs::read_to_string(pid_file)
            .expect("the script recorded its child")
            .trim()
            .parse()
            .expect("pid");
        let deadline = std::time::Instant::now() + Duration::from_secs(2);
        while alive(pid) && std::time::Instant::now() < deadline {
            tokio::time::sleep(Duration::from_millis(20)).await;
        }
        let survived = alive(pid);
        if survived {
            let _ = std::process::Command::new("kill")
                .args(["-KILL", &pid.to_string()])
                .status();
        }
        survived
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn an_abandoned_query_is_killed_with_its_children() {
        // The launcher drops a query's future when the next keystroke
        // supersedes it; that has to stop the plugin, not just forget it.
        let root = tempfile::tempdir().expect("tempdir");
        let plugin = scripted(
            root.path(),
            "#!/bin/sh\nsleep 30 &\necho $! > child.pid\nwait\n",
            Some(3000),
        );
        let pid_file = root.path().join("child.pid");

        let running = tokio::spawn(async move {
            let deadline = plugin.manifest.timeout(Some("t"));
            plugin.query("x", deadline).await
        });
        let started = std::time::Instant::now();
        let recorded =
            |path: &Path| std::fs::read_to_string(path).is_ok_and(|pid| pid.ends_with('\n'));
        while !recorded(&pid_file) && started.elapsed() < Duration::from_secs(2) {
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        running.abort();
        assert!(running.await.is_err_and(|error| error.is_cancelled()));

        assert!(
            !outlives(&pid_file).await,
            "the abandoned query's child kept running"
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn lint_applies_the_launchers_output_cap() {
        // Lint promises to run the plugin exactly the way the launcher does,
        // so output the launcher would drop cannot lint clean.
        let root = tempfile::tempdir().expect("tempdir");
        let directory = root.path().join("big");
        std::fs::create_dir_all(&directory).expect("dir");
        std::fs::write(
            directory.join("manifest.toml"),
            "name = \"Big\"\nkeyword = \"big\"\nquery = \"./q\"\n",
        )
        .expect("manifest");
        scripted(
            &directory,
            "#!/bin/sh\nprintf '{\"items\":[{\"uid\":\"a\",\"title\":\"'\n\
             head -c 1100000 /dev/zero | tr '\\0' a\nprintf '\"}]}'\n",
            None,
        );

        let report = lint(&directory, "x").await;
        assert!(!report.is_clean(), "oversized output linted clean");
    }

    #[test]
    fn discovery_walks_roots_in_order_and_user_shadows_system() {
        let user = tempfile::tempdir().expect("tempdir");
        let system = tempfile::tempdir().expect("tempdir");

        let write = |root: &std::path::Path, id: &str, name: &str| {
            let dir = root.join(id);
            std::fs::create_dir_all(&dir).expect("plugin dir");
            std::fs::write(
                dir.join("manifest.toml"),
                format!("name = \"{name}\"\nquery = \"./q\"\n"),
            )
            .expect("manifest");
        };

        write(user.path(), "shared", "User copy");
        write(user.path(), "mine", "User only");
        write(system.path(), "shared", "System copy");
        write(system.path(), "packaged", "System only");
        // A directory without a manifest is not a plugin.
        std::fs::create_dir_all(system.path().join("junk")).expect("junk dir");

        let host =
            PluginHost::discover_in(&[user.path().to_path_buf(), system.path().to_path_buf()]);

        let mut ids: Vec<&str> = host.all().map(|(plugin, _)| plugin.id.as_str()).collect();
        ids.sort_unstable();
        assert_eq!(ids, ["mine", "packaged", "shared"]);

        // The user's copy shadowed the packaged one.
        let shared = host.get("shared").expect("shared plugin");
        assert_eq!(shared.manifest.name, "User copy");
    }

    #[test]
    fn a_fresh_discovery_keeps_the_users_settings() {
        // Rediscovery replaces what is on disk, never what the user chose:
        // a switched-off plugin must stay off, and an alias must survive.
        let root = tempfile::tempdir().expect("tempdir");
        let write = |id: &str| {
            let dir = root.path().join(id);
            std::fs::create_dir_all(&dir).expect("plugin dir");
            std::fs::write(
                dir.join("manifest.toml"),
                "name = \"P\"\nkeyword = \"p\"\nquery = \"./q\"\n",
            )
            .expect("manifest");
        };
        write("old");
        let roots = [root.path().to_path_buf()];
        let mut host = PluginHost::discover_in(&roots);
        host.set_disabled(["old"]);
        host.set_keyword_overrides([("new", "n")]);

        assert!(!host.replace_plugins(PluginHost::discover_in(&roots)));

        write("new");
        assert!(host.replace_plugins(PluginHost::discover_in(&roots)));
        assert!(
            host.get("old").is_none(),
            "the disabled plugin came back on"
        );
        let new = host.get("new").expect("the new plugin was picked up");
        assert_eq!(host.effective_keyword(new), Some("n"));
    }

    #[test]
    fn keyword_overrides_replace_and_remove_the_manifest_keyword() {
        let mut host = PluginHost {
            plugins: vec![plugin(Some("gh"))],
            disabled: std::collections::HashSet::new(),
            keyword_overrides: std::collections::HashMap::new(),
        };

        // Manifest keyword applies untouched.
        assert!(host.is_claimed("gh jump"));

        // An override is a rename: the old keyword stops answering.
        host.set_keyword_overrides([("test", "g")]);
        assert!(host.is_claimed("g jump"));
        assert!(!host.is_claimed("gh jump"));

        // An empty override removes the keyword entirely: the plugin runs on
        // every query and claims none.
        host.set_keyword_overrides([("test", "")]);
        assert!(!host.is_claimed("g jump"));
        assert!(!host.is_claimed("gh jump"));
        let plugin = &host.plugins[0];
        assert_eq!(host.effective_keyword(plugin), None);

        // Overrides for unknown plugins are inert.
        host.set_keyword_overrides([("other", "x")]);
        assert!(host.is_claimed("gh jump"));
    }

    #[test]
    fn disabled_plugins_neither_run_nor_activate() {
        let mut host = PluginHost {
            plugins: vec![plugin(Some("gh"))],
            disabled: std::collections::HashSet::new(),
            keyword_overrides: std::collections::HashMap::new(),
        };

        assert!(host.is_claimed("gh jump"));
        assert!(host.get("test").is_some());

        host.set_disabled(["test"]);
        assert!(!host.is_claimed("gh jump"));
        assert!(host.get("test").is_none());
        // Still listed for the settings window, marked disabled.
        assert_eq!(host.all().map(|(_, on)| on).collect::<Vec<_>>(), [false]);
    }
}