yapi-core 0.4.2

Coding agent core: sessions, compaction, settings, resources, built-in tools, system prompt, packages, extension runner and MCP. An internal library of yapi, with no stable API.
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
//! Every resource that settings, packages and the agent and project
//! directories provide, each enabled or not, in load precedence order.
//!
//! Port of `DefaultPackageManager.resolve` and its pattern rules in
//! `core/package-manager.ts` in pi `v1.0.0`. yapi also loads `.wasm` native
//! extensions wherever pi loads `.ts` and `.js` ones.

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

use yapi_types::rpc::SourceInfo;
use yapi_types::settings::FilteredPackage;

use crate::chest::ChestError;
use crate::chest::manifest::read_package_meta;
use crate::glob;
use crate::tools::path::{relative, resolve_lexically};

/// A kind of resource.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ResourceType {
    /// Extension entry files.
    Extensions,
    /// Skill files.
    Skills,
    /// Prompt template files.
    Prompts,
    /// Theme files.
    Themes,
}

impl ResourceType {
    /// Every kind, in pi's order.
    pub const ALL: [ResourceType; 4] = [
        ResourceType::Extensions,
        ResourceType::Skills,
        ResourceType::Prompts,
        ResourceType::Themes,
    ];

    /// The settings and manifest key.
    pub fn key(self) -> &'static str {
        match self {
            ResourceType::Extensions => "extensions",
            ResourceType::Skills => "skills",
            ResourceType::Prompts => "prompts",
            ResourceType::Themes => "themes",
        }
    }

    fn matches_file(self, name: &str) -> bool {
        match self {
            ResourceType::Extensions => is_extension_file(name),
            ResourceType::Skills | ResourceType::Prompts => name.ends_with(".md"),
            ResourceType::Themes => name.ends_with(".json"),
        }
    }
}

/// Whether file `name` is an extension yapi loads: pi's extension files,
/// and yapi's native extensions.
pub fn is_extension_file(name: &str) -> bool {
    name.ends_with(".ts") || name.ends_with(".js") || name.ends_with(".wasm")
}

/// A resource and whether it loads.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Resolved {
    /// Its path and where it comes from.
    pub info: SourceInfo,
    /// Whether settings leave it on.
    pub enabled: bool,
}

/// pi's `ResolvedPaths`: resolved resources by kind.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ResolvedPaths {
    /// Extensions.
    pub extensions: Vec<Resolved>,
    /// Skills.
    pub skills: Vec<Resolved>,
    /// Prompt templates.
    pub prompts: Vec<Resolved>,
    /// Themes.
    pub themes: Vec<Resolved>,
    /// Extensions another source named again, each under that source,
    /// which does not load them: by the same path, or by another path to
    /// the same file.
    pub shadowed: Vec<SourceInfo>,
    /// Packages whose `chest.toml` does not parse, each by its folder with
    /// why. Their resources resolve as if it were absent.
    pub problems: Vec<(String, String)>,
    /// What a project-only run keeps of the user's resources, while
    /// [`resolve`] collects them.
    pub(crate) keep: Option<Keep>,
    /// The canonical paths of chest's resources so far, by kind, with
    /// their place in the list, while [`resolve`] collects them.
    pub(crate) chest_files: Vec<(ResourceType, PathBuf, usize)>,
}

/// [`ProjectOnly`] with the folders its patterns resolve against.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct Keep {
    only: ProjectOnly,
    agent_dir: PathBuf,
    home: PathBuf,
}

impl ResolvedPaths {
    /// The resources of `kind`.
    pub fn of(&self, kind: ResourceType) -> &[Resolved] {
        match kind {
            ResourceType::Extensions => &self.extensions,
            ResourceType::Skills => &self.skills,
            ResourceType::Prompts => &self.prompts,
            ResourceType::Themes => &self.themes,
        }
    }

    fn of_mut(&mut self, kind: ResourceType) -> &mut Vec<Resolved> {
        match kind {
            ResourceType::Extensions => &mut self.extensions,
            ResourceType::Skills => &mut self.skills,
            ResourceType::Prompts => &mut self.prompts,
            ResourceType::Themes => &mut self.themes,
        }
    }

    /// Adds the resource at `path` with `metadata` unless it is listed.
    fn add(&mut self, kind: ResourceType, path: &Path, metadata: &SourceInfo, enabled: bool) {
        let path = path.to_string_lossy().into_owned();
        if path.is_empty() {
            return;
        }
        let info = SourceInfo {
            path,
            ..metadata.clone()
        };
        // Before anything else, so a user's copy left out never shadows a
        // project's copy of the same file.
        if let Some(keep) = &self.keep
            && info.scope == "user"
            && info.source != "builtin"
            && !keep.only.keeps(&info, kind, &keep.agent_dir, &keep.home)
        {
            return;
        }
        // A chest entry's file also takes the other spellings of its path,
        // such as discovery's through a linked folder. One lookup a resource.
        let chest = info.source.starts_with("chest:");
        let canonical = (chest || self.chest_files.iter().any(|(other, ..)| *other == kind))
            .then(|| std::fs::canonicalize(&info.path).ok())
            .flatten();
        let same_file = canonical.as_ref().and_then(|file| {
            let mut files = self.chest_files.iter();
            let found = files.find(|(other, path, _)| *other == kind && path == file);
            found.map(|(_, _, index)| *index)
        });
        let list = self.of_mut(kind);
        let listed = list
            .iter()
            .position(|resource| resource.info.path == info.path)
            .or(same_file);
        if let Some(index) = listed {
            let listed = &list[index].info;
            let other = (&listed.source, &listed.scope) != (&info.source, &info.scope);
            if kind == ResourceType::Extensions && other {
                self.shadowed.push(info);
            }
            return;
        }
        let index = list.len();
        list.push(Resolved { info, enabled });
        if let (true, Some(file)) = (chest, canonical) {
            self.chest_files.push((kind, file, index));
        }
    }

    /// The enabled resources of `kind`, in order.
    pub fn enabled(&self, kind: ResourceType) -> impl Iterator<Item = &SourceInfo> {
        self.of(kind)
            .iter()
            .filter(|resource| resource.enabled)
            .map(|resource| &resource.info)
    }
}

/// A package to collect from, after pi's deduplication.
#[derive(Clone, Debug, PartialEq)]
pub struct PackageInput {
    /// The source as written in settings.
    pub source: String,
    /// `user`, `project` or `temporary`.
    pub scope: String,
    /// Where it is installed: a directory, or a file for a local file.
    pub root: PathBuf,
    /// The settings entry's filters, when it is an object.
    pub filter: Option<FilteredPackage>,
}

/// What [`resolve`] reads.
#[derive(Clone, Debug, Default)]
pub struct ResolveInput<'a> {
    /// The project's directory, whose ancestors' `.agents/skills` are
    /// project skills: the working directory unless the run names another.
    pub cwd: PathBuf,
    /// The agent directory.
    pub agent_dir: PathBuf,
    /// The project's directory of yapi files, `<cwd>/.yapi`.
    pub project_dir: PathBuf,
    /// The home directory, for `~/.agents/skills`.
    pub home: PathBuf,
    /// Whether the project's own resources load.
    pub project_trusted: bool,
    /// Installed packages, project entries first.
    pub packages: Vec<PackageInput>,
    /// Skill folders a package manager placed, each one skill of the
    /// package its source and scope name.
    pub skills: Vec<PackageInput>,
    /// The user's `extensions`, `skills`, `prompts` and `themes` settings.
    pub user: [&'a [String]; 4],
    /// The project's.
    pub project: [&'a [String]; 4],
    /// Built-in extension names.
    pub builtins: &'a [&'a str],
    /// In a project-only run, what it keeps of the user's resources. The
    /// user's others are left out.
    pub project_only: Option<ProjectOnly>,
}

/// The path prefix naming a built-in extension.
pub const BUILTIN_PREFIX: &str = "builtin:";

fn to_posix(path: &str) -> String {
    path.replace('\\', "/")
}

fn base_name(path: &Path) -> String {
    path.file_name()
        .map(|name| name.to_string_lossy().into_owned())
        .unwrap_or_default()
}

/// pi's `matchesAnyPattern`: a glob against the path relative to `base`,
/// the file name or the whole path, and for `SKILL.md` its directory too.
fn matches_any_pattern(file: &Path, patterns: &[String], base: &Path) -> bool {
    let rel = relative(base, file);
    let name = base_name(file);
    let whole = to_posix(&file.to_string_lossy());
    let parent = (name == "SKILL.md").then(|| file.parent()).flatten();
    patterns.iter().any(|pattern| {
        let pattern = to_posix(pattern);
        // minimatch keeps a leading `./`, which no relative path, name or
        // absolute path has.
        if pattern.starts_with("./") {
            return false;
        }
        if glob::matches(&pattern, &rel)
            || glob::matches(&pattern, &name)
            || glob::matches(&pattern, &whole)
        {
            return true;
        }
        parent.is_some_and(|parent| {
            glob::matches(&pattern, &relative(base, parent))
                || glob::matches(&pattern, &base_name(parent))
                || glob::matches(&pattern, &to_posix(&parent.to_string_lossy()))
        })
    })
}

/// pi's `matchesAnyExactPattern`: the path relative to `base` or the whole
/// path, without a leading `./`, and for `SKILL.md` its directory too.
fn matches_any_exact_pattern(file: &Path, patterns: &[String], base: &Path) -> bool {
    if patterns.is_empty() {
        return false;
    }
    let rel = relative(base, file);
    let whole = to_posix(&file.to_string_lossy());
    let parent = (base_name(file) == "SKILL.md")
        .then(|| file.parent())
        .flatten();
    patterns.iter().any(|pattern| {
        let pattern = pattern
            .strip_prefix("./")
            .or_else(|| pattern.strip_prefix(".\\"))
            .unwrap_or(pattern);
        let pattern = to_posix(pattern);
        if pattern == rel || pattern == whole {
            return true;
        }
        parent.is_some_and(|parent| {
            pattern == relative(base, parent) || pattern == to_posix(&parent.to_string_lossy())
        })
    })
}

fn is_override(entry: &str) -> bool {
    entry.starts_with(['!', '+', '-'])
}

fn is_pattern(entry: &str) -> bool {
    is_override(entry) || entry.contains(['*', '?'])
}

fn has_glob(entry: &str) -> bool {
    entry.contains(['*', '?'])
}

fn stripped<'a>(entries: impl Iterator<Item = &'a String>, sign: char) -> Vec<String> {
    entries
        .filter_map(|entry| entry.strip_prefix(sign).map(str::to_owned))
        .collect()
}

/// pi's `isEnabledByOverrides`: `!` globs disable, then `+` paths enable,
/// then `-` paths disable.
pub fn is_enabled_by_overrides(file: &Path, entries: &[String], base: &Path) -> bool {
    let excludes = stripped(entries.iter(), '!');
    let force_includes = stripped(entries.iter(), '+');
    let force_excludes = stripped(entries.iter(), '-');
    let mut enabled = true;
    if !excludes.is_empty() && matches_any_pattern(file, &excludes, base) {
        enabled = false;
    }
    if matches_any_exact_pattern(file, &force_includes, base) {
        enabled = true;
    }
    if matches_any_exact_pattern(file, &force_excludes, base) {
        enabled = false;
    }
    enabled
}

/// pi's `applyPatterns`: plain globs select (all when there are none), `!`
/// globs remove, `+` paths add back and `-` paths remove.
pub fn apply_patterns(all: &[PathBuf], patterns: &[String], base: &Path) -> HashSet<PathBuf> {
    let includes: Vec<String> = patterns
        .iter()
        .filter(|pattern| !is_override(pattern))
        .cloned()
        .collect();
    let excludes = stripped(patterns.iter(), '!');
    let force_includes = stripped(patterns.iter(), '+');
    let force_excludes = stripped(patterns.iter(), '-');
    let mut result: Vec<PathBuf> = if includes.is_empty() {
        all.to_vec()
    } else {
        all.iter()
            .filter(|file| matches_any_pattern(file, &includes, base))
            .cloned()
            .collect()
    };
    if !excludes.is_empty() {
        result.retain(|file| !matches_any_pattern(file, &excludes, base));
    }
    for file in all {
        if !result.contains(file) && matches_any_exact_pattern(file, &force_includes, base) {
            result.push(file.clone());
        }
    }
    if !force_excludes.is_empty() {
        result.retain(|file| !matches_any_exact_pattern(file, &force_excludes, base));
    }
    result.into_iter().collect()
}

/// pi's `applyAutoloadDisabledPatterns`: each pattern turns the files it
/// names on (`+`, plain) or off (`-`, `!`), the last one deciding.
fn apply_autoload_disabled_patterns(
    all: &[PathBuf],
    patterns: &[String],
    base: &Path,
) -> Vec<(PathBuf, bool)> {
    let mut result: Vec<(PathBuf, bool)> = Vec::new();
    for pattern in patterns {
        let target = if is_override(pattern) {
            pattern[1..].to_owned()
        } else {
            pattern.clone()
        };
        let enabled = !pattern.starts_with(['-', '!']);
        let exact = pattern.starts_with(['+', '-']);
        for file in all {
            let found = if exact {
                matches_any_exact_pattern(file, std::slice::from_ref(&target), base)
            } else {
                matches_any_pattern(file, std::slice::from_ref(&target), base)
            };
            if found {
                match result.iter_mut().find(|(path, _)| path == file) {
                    Some(entry) => entry.1 = enabled,
                    None => result.push((file.clone(), enabled)),
                }
            }
        }
    }
    result
}

/// The rules of `.gitignore`, `.ignore` and `.fdignore` files met while
/// walking a directory, as a subset of the `ignore` package pi uses.
#[derive(Clone, Debug, Default)]
struct Ignore {
    rules: Vec<(String, bool)>,
}

impl Ignore {
    /// pi's `addIgnoreRules`: the rules in `dir`, prefixed with its path
    /// relative to `root`.
    fn add_dir(&mut self, dir: &Path, root: &Path) {
        let rel = relative(root, dir);
        let prefix = if rel.is_empty() {
            String::new()
        } else {
            format!("{rel}/")
        };
        for name in [".gitignore", ".ignore", ".fdignore"] {
            let Ok(text) = std::fs::read_to_string(dir.join(name)) else {
                continue;
            };
            for line in text.lines() {
                let trimmed = line.trim();
                if trimmed.is_empty() || (trimmed.starts_with('#') && !trimmed.starts_with("\\#")) {
                    continue;
                }
                let (mut pattern, negated) = match line.strip_prefix('!') {
                    Some(rest) => (rest, true),
                    None => (
                        line.strip_prefix('\\')
                            .filter(|rest| rest.starts_with('!'))
                            .unwrap_or(line),
                        false,
                    ),
                };
                pattern = pattern.strip_prefix('/').unwrap_or(pattern);
                self.rules
                    .push((format!("{prefix}{}", pattern.trim_end()), negated));
            }
        }
    }

    /// Whether `path`, relative to the walk's root and ending in `/` for a
    /// directory, is ignored.
    fn ignores(&self, path: &str) -> bool {
        let dir = path.ends_with('/');
        let path = path.trim_end_matches('/');
        let mut ignored = false;
        for (pattern, negated) in &self.rules {
            if rule_matches(pattern, path, dir) {
                ignored = !negated;
            }
        }
        ignored
    }
}

/// One rule against a relative path. A rule with a `/` is anchored to the
/// root, and one without matches a name at any depth. Walks skip dot entries
/// before asking, so wildcards need not match them.
fn rule_matches(pattern: &str, path: &str, dir: bool) -> bool {
    let (pattern, dir_only) = match pattern.strip_suffix('/') {
        Some(pattern) => (pattern, true),
        None => (pattern, false),
    };
    if dir_only && !dir {
        return false;
    }
    if pattern.contains('/') {
        glob::matches(pattern, path)
    } else {
        glob::matches(pattern, path.rsplit('/').next().unwrap_or(path))
    }
}

struct Entry {
    path: PathBuf,
    is_dir: bool,
    is_file: bool,
    name: String,
}

/// A directory's entries, sorted by name, following symbolic links.
fn read_dir(dir: &Path) -> Vec<Entry> {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return Vec::new();
    };
    let mut out: Vec<Entry> = entries
        .flatten()
        .filter_map(|entry| {
            let path = entry.path();
            let metadata = std::fs::metadata(&path).ok()?;
            Some(Entry {
                name: entry.file_name().to_string_lossy().into_owned(),
                is_dir: metadata.is_dir(),
                is_file: metadata.is_file(),
                path,
            })
        })
        .collect();
    out.sort_by(|a, b| a.name.cmp(&b.name));
    out
}

/// pi's `collectFiles`: files of `kind` under `dir`, recursively, skipping
/// dot entries, `node_modules` and ignored paths.
fn collect_files(dir: &Path, kind: ResourceType, ignore: &mut Ignore, root: &Path) -> Vec<PathBuf> {
    let mut files = Vec::new();
    if !dir.exists() {
        return files;
    }
    ignore.add_dir(dir, root);
    for entry in read_dir(dir) {
        if entry.name.starts_with('.') || entry.name == "node_modules" {
            continue;
        }
        let rel = relative(root, &entry.path);
        let probe = if entry.is_dir { format!("{rel}/") } else { rel };
        if ignore.ignores(&probe) {
            continue;
        }
        if entry.is_dir {
            files.extend(collect_files(&entry.path, kind, ignore, root));
        } else if entry.is_file && kind.matches_file(&entry.name) {
            files.push(entry.path);
        }
    }
    files
}

/// Where skills are discovered: pi's own directories take `.md` files at the
/// top, `.agents` directories only below it.
#[derive(Clone, Copy, PartialEq, Eq)]
enum SkillMode {
    Pi,
    Agents,
}

/// pi's `collectSkillEntries`: a directory with a `SKILL.md` is one skill.
/// Otherwise, its `.md` files (by mode) and the skills of its directories.
fn collect_skill_entries(
    dir: &Path,
    mode: SkillMode,
    ignore: &mut Ignore,
    root: &Path,
) -> Vec<PathBuf> {
    let mut entries = Vec::new();
    if !dir.exists() {
        return entries;
    }
    ignore.add_dir(dir, root);
    let listing = read_dir(dir);
    if let Some(skill) = listing.iter().find(|entry| entry.name == "SKILL.md")
        && skill.is_file
        && !ignore.ignores(&relative(root, &skill.path))
    {
        entries.push(skill.path.clone());
        return entries;
    }
    for entry in listing {
        if entry.name.starts_with('.') || entry.name == "node_modules" {
            continue;
        }
        let rel = relative(root, &entry.path);
        let markdown = entry.is_file
            && entry.name.ends_with(".md")
            && !ignore.ignores(&rel)
            && ((mode == SkillMode::Pi && dir == root)
                || (mode == SkillMode::Agents && dir != root));
        if markdown {
            entries.push(entry.path);
            continue;
        }
        if !entry.is_dir || ignore.ignores(&format!("{rel}/")) {
            continue;
        }
        entries.extend(collect_skill_entries(&entry.path, mode, ignore, root));
    }
    entries
}

/// pi's `collectAutoPromptEntries` and `collectAutoThemeEntries`: the files
/// of `kind` directly in `dir`.
fn collect_top_files(dir: &Path, kind: ResourceType) -> Vec<PathBuf> {
    if !dir.exists() {
        return Vec::new();
    }
    let mut ignore = Ignore::default();
    ignore.add_dir(dir, dir);
    read_dir(dir)
        .into_iter()
        .filter(|entry| !entry.name.starts_with('.') && entry.name != "node_modules")
        .filter(|entry| !ignore.ignores(&relative(dir, &entry.path)))
        .filter(|entry| entry.is_file && kind.matches_file(&entry.name))
        .map(|entry| entry.path)
        .collect()
}

/// pi's `collectAutoExtensionEntries`: a directory's own entry points, else
/// its extension files and the entry points of its directories.
fn collect_auto_extension_entries(dir: &Path) -> Vec<PathBuf> {
    if !dir.exists() {
        return Vec::new();
    }
    if let Some(entries) = crate::extensions::discovery::entries(dir) {
        return entries;
    }
    let mut ignore = Ignore::default();
    ignore.add_dir(dir, dir);
    let mut entries = Vec::new();
    for entry in read_dir(dir) {
        if entry.name.starts_with('.') || entry.name == "node_modules" {
            continue;
        }
        let rel = relative(dir, &entry.path);
        let probe = if entry.is_dir { format!("{rel}/") } else { rel };
        if ignore.ignores(&probe) {
            continue;
        }
        if entry.is_file && is_extension_file(&entry.name) {
            entries.push(entry.path);
        } else if entry.is_dir {
            entries.extend(crate::extensions::discovery::entries(&entry.path).unwrap_or_default());
        }
    }
    entries
}

/// pi's `collectResourceFiles`.
fn collect_resource_files(dir: &Path, kind: ResourceType) -> Vec<PathBuf> {
    match kind {
        ResourceType::Skills => {
            collect_skill_entries(dir, SkillMode::Pi, &mut Ignore::default(), dir)
        }
        ResourceType::Extensions => collect_auto_extension_entries(dir),
        _ => collect_files(dir, kind, &mut Ignore::default(), dir),
    }
}

/// pi's `collectFilesFromPaths`: files as they are, directories collected.
fn collect_files_from_paths(paths: &[PathBuf], kind: ResourceType) -> Vec<PathBuf> {
    let mut files = Vec::new();
    for path in paths {
        let Ok(metadata) = std::fs::metadata(path) else {
            continue;
        };
        if metadata.is_file() {
            files.push(path.clone());
        } else if metadata.is_dir() {
            files.extend(collect_resource_files(path, kind));
        }
    }
    files
}

/// pi's `readPiManifest`, extended kind by kind: each resource list comes
/// from the package's `chest.toml` `[package]`, else its `package.json`
/// `yapi` key, else its `pi` key, as [`read_package_meta`] reads them. A list is
/// `None` when no source lists the kind.
#[derive(Default)]
pub(crate) struct Manifest {
    lists: [Option<Vec<String>>; 4],
}

impl Manifest {
    /// The manifest of the package at `root`, or `None` when no source
    /// decides its resources, so the conventional folders apply. With it, why
    /// its `chest.toml` was left out, as [`read_package_meta`] says.
    pub(crate) fn read(root: &Path) -> (Option<Manifest>, Option<ChestError>) {
        let (meta, problem) = read_package_meta(root);
        let lists = ResourceType::ALL.map(|kind| meta.resources.get(kind.key()).cloned());
        (meta.manifest.then_some(Manifest { lists }), problem)
    }

    /// The entries of `kind`, when listed.
    pub(crate) fn get(&self, kind: ResourceType) -> Option<&Vec<String>> {
        self.lists[kind as usize].as_ref()
    }
}

/// pi's `expandPackageGlob`: matches under `root` with no dot segment,
/// sorted.
fn expand_package_glob(pattern: &str, root: &Path) -> Vec<PathBuf> {
    fn walk(root: &Path, dir: &Path, out: &mut Vec<String>) {
        for entry in read_dir(dir) {
            let rel = relative(root, &entry.path);
            out.push(rel);
            if entry.is_dir && entry.name != "node_modules" && !entry.name.starts_with('.') {
                walk(root, &entry.path, out);
            }
        }
    }
    let mut all = Vec::new();
    walk(root, root, &mut all);
    let mut found: Vec<PathBuf> = all
        .into_iter()
        .filter(|rel| rel.split('/').all(|segment| !segment.starts_with('.')))
        .filter(|rel| glob::matches(pattern, rel))
        .map(|rel| root.join(rel))
        .collect();
    found.sort();
    found
}

/// pi's `collectFilesFromManifestEntries`.
fn manifest_files(entries: &[String], root: &Path, kind: ResourceType) -> Vec<PathBuf> {
    let resolved: Vec<PathBuf> = entries
        .iter()
        .filter(|entry| !is_override(entry))
        .flat_map(|entry| {
            if has_glob(entry) {
                expand_package_glob(entry, root)
            } else {
                vec![resolve_lexically(root, Path::new(entry))]
            }
        })
        .collect();
    collect_files_from_paths(&resolved, kind)
}

fn metadata(source: &str, scope: &str, origin: &str, base_dir: Option<&Path>) -> SourceInfo {
    SourceInfo {
        path: String::new(),
        source: source.to_owned(),
        scope: scope.to_owned(),
        origin: origin.to_owned(),
        base_dir: base_dir.map(|dir| dir.to_string_lossy().into_owned()),
    }
}

/// pi's `collectPackageResources`: whether the package provided anything.
fn collect_package_resources(
    root: &Path,
    acc: &mut ResolvedPaths,
    filter: Option<&FilteredPackage>,
    meta: &SourceInfo,
) -> bool {
    let (manifest, problem) = Manifest::read(root);
    if let Some(err) = problem {
        let folder = root.to_string_lossy().into_owned();
        acc.problems.push((folder, err.to_string()));
    }
    if let Some(filter) = filter {
        for kind in ResourceType::ALL {
            let patterns = match kind {
                ResourceType::Extensions => &filter.extensions,
                ResourceType::Skills => &filter.skills,
                ResourceType::Prompts => &filter.prompts,
                ResourceType::Themes => &filter.themes,
            };
            if filter.autoload == Some(false) {
                let patterns = patterns.clone().unwrap_or_default();
                if patterns.is_empty() {
                    continue;
                }
                let all = package_files(root, manifest.as_ref(), kind);
                for (file, enabled) in apply_autoload_disabled_patterns(&all, &patterns, root) {
                    acc.add(kind, &file, meta, enabled);
                }
            } else if let Some(patterns) = patterns {
                let all = package_files(root, manifest.as_ref(), kind);
                let enabled = if patterns.is_empty() {
                    HashSet::new()
                } else {
                    apply_patterns(&all, patterns, root)
                };
                for file in &all {
                    acc.add(kind, file, meta, enabled.contains(file));
                }
            } else {
                default_resources(root, manifest.as_ref(), kind, acc, meta);
            }
        }
        return true;
    }
    if let Some(manifest) = &manifest {
        for kind in ResourceType::ALL {
            if let Some(entries) = manifest.get(kind) {
                manifest_entries(entries, root, kind, acc, meta);
            }
        }
        return true;
    }
    let mut any = false;
    for kind in ResourceType::ALL {
        let dir = root.join(kind.key());
        if dir.exists() {
            for file in collect_resource_files(&dir, kind) {
                acc.add(kind, &file, meta, true);
            }
            any = true;
        }
    }
    any
}

/// pi's `collectDefaultResources`.
fn default_resources(
    root: &Path,
    manifest: Option<&Manifest>,
    kind: ResourceType,
    acc: &mut ResolvedPaths,
    meta: &SourceInfo,
) {
    if let Some(entries) = manifest.and_then(|manifest| manifest.get(kind)) {
        manifest_entries(entries, root, kind, acc, meta);
        return;
    }
    let dir = root.join(kind.key());
    if dir.exists() {
        for file in collect_resource_files(&dir, kind) {
            acc.add(kind, &file, meta, true);
        }
    }
}

/// pi's `collectManifestFiles`: the files the manifest's entries select,
/// or the conventional directory's.
fn package_files(root: &Path, manifest: Option<&Manifest>, kind: ResourceType) -> Vec<PathBuf> {
    let entries = manifest.and_then(|manifest| manifest.get(kind));
    selected_files(root, entries.map(Vec::as_slice), kind.key(), kind)
}

/// The files of `kind` that the package at `root` provides: those its
/// manifest `entries` select, with their globs and `!` patterns, else
/// those in its folder `folder`.
pub(crate) fn selected_files(
    root: &Path,
    entries: Option<&[String]>,
    folder: &str,
    kind: ResourceType,
) -> Vec<PathBuf> {
    if let Some(entries) = entries.filter(|entries| !entries.is_empty()) {
        let all = manifest_files(entries, root, kind);
        let patterns: Vec<String> = entries
            .iter()
            .filter(|entry| is_override(entry))
            .cloned()
            .collect();
        if patterns.is_empty() {
            return all;
        }
        let enabled = apply_patterns(&all, &patterns, root);
        return all
            .into_iter()
            .filter(|file| enabled.contains(file))
            .collect();
    }
    let dir = root.join(folder);
    if dir.exists() {
        collect_resource_files(&dir, kind)
    } else {
        Vec::new()
    }
}

/// pi's `addManifestEntries`: the enabled files only.
fn manifest_entries(
    entries: &[String],
    root: &Path,
    kind: ResourceType,
    acc: &mut ResolvedPaths,
    meta: &SourceInfo,
) {
    let all = manifest_files(entries, root, kind);
    let patterns: Vec<String> = entries
        .iter()
        .filter(|entry| is_override(entry))
        .cloned()
        .collect();
    let enabled = apply_patterns(&all, &patterns, root);
    for file in &all {
        if enabled.contains(file) {
            acc.add(kind, file, meta, true);
        }
    }
}

/// pi's `resolveLocalEntries`: settings entries as paths, with their
/// patterns deciding which files are on.
fn local_entries(
    entries: &[String],
    kind: ResourceType,
    acc: &mut ResolvedPaths,
    meta: &SourceInfo,
    base: &Path,
) {
    if entries.is_empty() {
        return;
    }
    let (patterns, plain): (Vec<String>, Vec<String>) =
        entries.iter().cloned().partition(|entry| is_pattern(entry));
    let resolved: Vec<PathBuf> = plain
        .iter()
        .map(|entry| resolve_lexically(base, Path::new(&crate::tools::path::expand(entry.trim()))))
        .collect();
    let all = collect_files_from_paths(&resolved, kind);
    let enabled = apply_patterns(&all, &patterns, base);
    for file in &all {
        acc.add(kind, file, meta, enabled.contains(file));
    }
}

/// pi's `collectAncestorAgentsSkillDirs`: `.agents/skills` in `start` and
/// each parent up to the repository root, or the filesystem root.
fn ancestor_agents_skill_dirs(start: &Path) -> Vec<PathBuf> {
    let repo = start
        .ancestors()
        .find(|dir| dir.join(".git").exists())
        .map(Path::to_path_buf);
    let mut dirs = Vec::new();
    for dir in start.ancestors() {
        dirs.push(dir.join(".agents").join("skills"));
        if repo.as_deref() == Some(dir) {
            break;
        }
    }
    dirs
}

/// pi's `addAutoDiscoveredResources`: the project's resources when it is
/// trusted, then the user's, each scope with its extensions, skills,
/// `.agents` skills, prompts and themes.
fn auto_discovered(input: &ResolveInput<'_>, acc: &mut ResolvedPaths) {
    let user_agents = input.home.join(".agents").join("skills");
    let project_agents: Vec<PathBuf> = if input.project_trusted {
        ancestor_agents_skill_dirs(&input.cwd)
            .into_iter()
            .filter(|dir| *dir != user_agents)
            .collect()
    } else {
        Vec::new()
    };
    let scopes = [
        (
            "project",
            &input.project_dir,
            input.project,
            input.project_trusted,
            project_agents,
        ),
        (
            "user",
            &input.agent_dir,
            input.user,
            true,
            vec![user_agents],
        ),
    ];
    for (scope, base, overrides, own, agents) in scopes {
        let mut add = |kind: ResourceType, paths: Vec<PathBuf>, base: &Path| {
            let meta = metadata("auto", scope, "top-level", Some(base));
            for path in paths {
                let enabled = is_enabled_by_overrides(&path, overrides[kind as usize], base);
                acc.add(kind, &path, &meta, enabled);
            }
        };
        for kind in ResourceType::ALL {
            let dir = base.join(kind.key());
            if own {
                let paths = match kind {
                    ResourceType::Extensions => collect_auto_extension_entries(&dir),
                    ResourceType::Skills => {
                        collect_skill_entries(&dir, SkillMode::Pi, &mut Ignore::default(), &dir)
                    }
                    _ => collect_top_files(&dir, kind),
                };
                add(kind, paths, base);
            }
            if kind == ResourceType::Skills {
                for dir in &agents {
                    let paths =
                        collect_skill_entries(dir, SkillMode::Agents, &mut Ignore::default(), dir);
                    add(kind, paths, dir.parent().unwrap_or(dir));
                }
            }
        }
    }
}

/// pi's `resourcePrecedenceRank`, with chest's entries ranked as their
/// scope's discovered folders, which hold their placed skills: collected
/// first, they win the names they share there.
fn precedence(info: &SourceInfo) -> u8 {
    if info.source == "builtin" {
        return 5;
    }
    if info.origin == "package" && !info.source.starts_with("chest:") {
        return 4;
    }
    let scope = if info.scope == "project" { 0 } else { 2 };
    scope + u8::from(info.source != "local")
}

/// One package's resources, installed at `root`: a file is one extension,
/// and a folder gives what its manifest or resource folders list. pi takes a
/// folder with neither as one extension only when it is a `local` path.
fn collect_package(
    acc: &mut ResolvedPaths,
    root: &Path,
    filter: Option<&FilteredPackage>,
    local: bool,
    mut meta: SourceInfo,
) {
    if root.is_file() {
        meta.base_dir = root.parent().map(|dir| dir.to_string_lossy().into_owned());
        acc.add(ResourceType::Extensions, root, &meta, true);
        return;
    }
    if !root.is_dir() {
        return;
    }
    meta.base_dir = Some(root.to_string_lossy().into_owned());
    if !collect_package_resources(root, acc, filter, &meta) && local {
        for entry in crate::extensions::discovery::entries(root).unwrap_or_default() {
            acc.add(ResourceType::Extensions, &entry, &meta, true);
        }
    }
}

/// The resources of the package installed at `root`, as [`resolve`] finds
/// them for a settings entry with `filter`, each enabled or not. `local`
/// says whether its source is a local path.
pub fn package_resources(
    root: &Path,
    filter: Option<&FilteredPackage>,
    local: bool,
) -> ResolvedPaths {
    let mut acc = ResolvedPaths::default();
    collect_package(
        &mut acc,
        root,
        filter,
        local,
        metadata("local", "user", "package", None),
    );
    acc
}

/// pi's `resolve`: packages, then settings entries, then discovered files,
/// then built-in extensions, ordered by precedence without repeats.
pub fn resolve(input: &ResolveInput<'_>) -> ResolvedPaths {
    let mut acc = ResolvedPaths {
        keep: input.project_only.clone().map(|only| Keep {
            only,
            agent_dir: input.agent_dir.clone(),
            home: input.home.clone(),
        }),
        ..ResolvedPaths::default()
    };
    // The project's packages and skills come before the user's, whichever
    // manager installed them. Settings list the project's first already.
    for project in [true, false] {
        let ours = |input: &&PackageInput| (input.scope == "project") == project;
        for package in input.packages.iter().filter(ours) {
            collect_package(
                &mut acc,
                &package.root,
                package.filter.as_ref(),
                super::source::is_local(&package.source),
                metadata(&package.source, &package.scope, "package", None),
            );
        }
        for skill in input.skills.iter().filter(ours) {
            let meta = metadata(&skill.source, &skill.scope, "package", None);
            // By its file, as discovery names a skill folder.
            let file = skill.root.join("SKILL.md");
            let path = if file.is_file() { &file } else { &skill.root };
            acc.add(ResourceType::Skills, path, &meta, true);
        }
    }
    for (index, kind) in ResourceType::ALL.into_iter().enumerate() {
        let project_meta = metadata("local", "project", "top-level", None);
        let user_meta = metadata("local", "user", "top-level", None);
        local_entries(
            input.project[index],
            kind,
            &mut acc,
            &project_meta,
            &input.project_dir,
        );
        local_entries(
            input.user[index],
            kind,
            &mut acc,
            &user_meta,
            &input.agent_dir,
        );
    }
    auto_discovered(input, &mut acc);
    let [user_ext, ..] = input.user;
    let [project_ext, ..] = input.project;
    for name in input.builtins {
        let path = PathBuf::from(format!("{BUILTIN_PREFIX}{name}"));
        let overrides: Vec<String> = project_ext
            .iter()
            .filter(|entry| is_override(entry))
            .cloned()
            .collect();
        let project = apply_autoload_disabled_patterns(
            std::slice::from_ref(&path),
            &overrides,
            &input.project_dir,
        )
        .into_iter()
        .next()
        .map(|(_, enabled)| enabled);
        let meta = metadata(
            "builtin",
            if project.is_some() { "project" } else { "user" },
            "top-level",
            None,
        );
        let enabled =
            project.unwrap_or_else(|| is_enabled_by_overrides(&path, user_ext, &input.agent_dir));
        acc.add(ResourceType::Extensions, &path, &meta, enabled);
    }
    let mut shadowed = Vec::new();
    for kind in ResourceType::ALL {
        let list = acc.of_mut(kind);
        list.sort_by_key(|resource| precedence(&resource.info));
        let mut seen = HashSet::new();
        list.retain(|resource| {
            let canonical = std::fs::canonicalize(&resource.info.path)
                .unwrap_or_else(|_| PathBuf::from(&resource.info.path));
            let first = seen.insert(canonical);
            if !first && kind == ResourceType::Extensions {
                shadowed.push(resource.info.clone());
            }
            first
        });
    }
    acc.shadowed.extend(shadowed);
    acc.keep = None;
    acc.chest_files.clear();
    acc
}

/// The global items a run under `--project-only` still loads: the
/// `projectOnly` setting of the user's settings.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ProjectOnly {
    /// Global packages kept whole, by source, `chest:<name>` or `*`.
    pub packages: Vec<String>,
    /// Patterns of global resources kept, by kind, in [`ResourceType::ALL`]
    /// order.
    pub kinds: [Vec<String>; 4],
    /// Global MCP servers kept, by name pattern.
    pub mcp_servers: Vec<String>,
}

impl ProjectOnly {
    /// The `projectOnly` object of the user's settings `document`.
    pub fn from_settings(document: &serde_json::Map<String, serde_json::Value>) -> ProjectOnly {
        let empty = serde_json::Map::new();
        let object = document
            .get("projectOnly")
            .and_then(serde_json::Value::as_object)
            .unwrap_or(&empty);
        let list = |key: &str| string_list(object, key);
        // A folder written with a trailing `/` names the folder.
        let patterns = |kind: ResourceType| {
            let list = list(kind.key()).into_iter();
            list.map(|pattern| pattern.trim_end_matches('/').to_owned())
                .collect()
        };
        ProjectOnly {
            packages: list("packages"),
            kinds: ResourceType::ALL.map(patterns),
            mcp_servers: list("mcpServers"),
        }
    }

    /// Whether a run keeps the global resource `info` of `kind`: its package
    /// is kept, or its kind's patterns match its path, with `~` as `home`
    /// and other paths relative to `agent_dir`.
    pub fn keeps(
        &self,
        info: &SourceInfo,
        kind: ResourceType,
        agent_dir: &Path,
        home: &Path,
    ) -> bool {
        let package = info.origin == "package" && self.keeps_package(&info.source, agent_dir);
        package || self.keeps_path(Path::new(&info.path), kind, agent_dir, home)
    }

    /// Whether `kind`'s patterns match the global file `path`, as for
    /// [`keeps`](Self::keeps).
    fn keeps_path(&self, path: &Path, kind: ResourceType, agent_dir: &Path, home: &Path) -> bool {
        let patterns: Vec<String> = self.kinds[kind as usize]
            .iter()
            .map(|pattern| match pattern.strip_prefix("~/") {
                Some(rest) => home.join(rest).to_string_lossy().into_owned(),
                None if pattern == "~" => home.to_string_lossy().into_owned(),
                None => pattern.clone(),
            })
            .collect();
        matches_any_pattern(path, &patterns, agent_dir)
    }

    /// Whether a kind list keeps a resource that the user's package `input`
    /// loads, as [`resolve`] lists them, with paths as for
    /// [`keeps`](Self::keeps).
    pub fn keeps_part(&self, input: &PackageInput, agent_dir: &Path, home: &Path) -> bool {
        let local = super::source::is_local(&input.source);
        let resources = package_resources(&input.root, input.filter.as_ref(), local);
        ResourceType::ALL.into_iter().any(|kind| {
            let mut files = resources.enabled(kind);
            files.any(|info| self.keeps_path(Path::new(&info.path), kind, agent_dir, home))
        })
    }

    /// Whether a project-only run needs the user's package `source` on
    /// disk: `packages` keeps it, or a kind list could match a file inside
    /// it. chest's entries are `chest:<name>`.
    pub fn needs_package(&self, source: &str, agent_dir: &Path) -> bool {
        self.kinds.iter().any(|list| !list.is_empty()) || self.keeps_package(source, agent_dir)
    }

    /// Whether `packages` keeps the user's package `source` whole.
    pub fn keeps_package(&self, source: &str, agent_dir: &Path) -> bool {
        self.packages
            .iter()
            .any(|entry| entry == "*" || same_package(entry, source, agent_dir))
    }

    /// Whether a project-only run needs the user's chest manifest: a kind
    /// list could match a file of its entries, or `packages` names one.
    pub fn needs_chest(&self) -> bool {
        self.kinds.iter().any(|list| !list.is_empty())
            || self
                .packages
                .iter()
                .any(|entry| entry == "*" || entry.starts_with("chest:"))
    }
}

/// Whether `entry` of `projectOnly.packages` names the package of `source`,
/// as a project entry overrides a user's: by identity, so versions and refs
/// don't count. chest's sources compare by name.
fn same_package(entry: &str, source: &str, agent_dir: &Path) -> bool {
    use super::source::parse;
    match (entry.strip_prefix("chest:"), source.strip_prefix("chest:")) {
        (Some(entry), Some(source)) => entry == source,
        (None, None) => parse(entry).identity(agent_dir) == parse(source).identity(agent_dir),
        _ => false,
    }
}

/// The `extensions`, `skills`, `prompts` and `themes` lists of a settings
/// document.
pub fn settings_lists(document: &serde_json::Map<String, serde_json::Value>) -> [Vec<String>; 4] {
    ResourceType::ALL.map(|kind| string_list(document, kind.key()))
}

/// The strings in list `key` of a settings document or package entry,
/// skipping entries of other types.
pub fn string_list(
    document: &serde_json::Map<String, serde_json::Value>,
    key: &str,
) -> Vec<String> {
    document
        .get(key)
        .and_then(serde_json::Value::as_array)
        .into_iter()
        .flatten()
        .filter_map(|entry| entry.as_str().map(str::to_owned))
        .collect()
}

/// pi's `dedupePackages`: the `packages` entries of the project, then the
/// user, with their scopes, `project` or `user`. A project entry wins over
/// the user's for the same package, as `identity` names it for a source and
/// scope, unless it sets `autoload: false`: then both stay.
pub fn dedupe_packages(
    project: &[serde_json::Value],
    user: &[serde_json::Value],
    identity: impl Fn(&str, &str) -> String,
) -> Vec<(serde_json::Value, &'static str)> {
    let mut result: Vec<(serde_json::Value, &'static str)> = Vec::new();
    let mut seen: Vec<(String, usize)> = Vec::new();
    let entries = project
        .iter()
        .map(|entry| (entry, "project"))
        .chain(user.iter().map(|entry| (entry, "user")));
    for (entry, scope) in entries {
        let Some(source) = super::entry_source(entry) else {
            continue;
        };
        let id = identity(source, scope);
        match seen
            .iter()
            .find(|(seen_id, _)| *seen_id == id)
            .map(|(_, index)| *index)
        {
            None => {
                seen.push((id, result.len()));
                result.push((entry.clone(), scope));
            }
            Some(index) => {
                let (existing, existing_scope) = &result[index];
                if *existing_scope == "project" && scope == "user" {
                    if is_delta(existing) {
                        result.push((entry.clone(), scope));
                    }
                } else if scope == "project" {
                    result[index] = (entry.clone(), scope);
                }
            }
        }
    }
    result
}

/// Whether a project's `packages` entry only adjusts the user's entry for
/// the same package: it sets `autoload: false`.
fn is_delta(entry: &serde_json::Value) -> bool {
    entry.is_object() && entry["autoload"] == serde_json::Value::Bool(false)
}

/// pi's `dedupePackages` with `findAutoloadDeltaBase`: each entry that
/// [`dedupe_packages`] keeps, with its scope, then the source and scope its
/// package is installed under, pi's `resolvedSource` and `resolvedScope`. A
/// project entry with `autoload: false` takes the user's entry for the same
/// package, when there is one.
pub fn locate_packages(
    project: &[serde_json::Value],
    user: &[serde_json::Value],
    identity: impl Fn(&str, &str) -> String,
) -> Vec<(serde_json::Value, &'static str, String, &'static str)> {
    let packages = dedupe_packages(project, user, &identity);
    packages
        .iter()
        .map(|(entry, scope)| {
            // `dedupe_packages` keeps only entries with a source.
            let source = super::entry_source(entry).unwrap_or_default();
            let base = (*scope == "project" && is_delta(entry))
                .then(|| {
                    let id = identity(source, scope);
                    packages
                        .iter()
                        .filter(|(_, other)| *other == "user")
                        .filter_map(|(other, _)| super::entry_source(other))
                        .find(|other| identity(other, "user") == id)
                })
                .flatten();
            let (located, located_scope) = base.map_or((source, *scope), |base| (base, "user"));
            (entry.clone(), *scope, located.to_owned(), located_scope)
        })
        .collect()
}

/// The packages of [`locate_packages`] that are installed, as `install_path`
/// places a source written in a scope's settings. A project entry with
/// `autoload: false` only overrides the resources it names, on top of the
/// user's entry.
pub fn package_inputs(
    project: &[serde_json::Value],
    user: &[serde_json::Value],
    base: impl Fn(&str) -> PathBuf,
    install_path: impl Fn(&super::source::Source, &str) -> PathBuf,
) -> Vec<PackageInput> {
    use super::source::parse;
    let identity = |source: &str, scope: &str| parse(source).identity(&base(scope));
    let mut inputs = Vec::new();
    for (entry, scope, located, located_scope) in locate_packages(project, user, identity) {
        let Some(source) = super::entry_source(&entry) else {
            continue;
        };
        // Only chest names its packages `chest:`, so no settings entry
        // passes for one.
        if source.starts_with("chest:") {
            continue;
        }
        let filter: Option<FilteredPackage> = entry
            .is_object()
            .then(|| serde_json::from_value(entry.clone()).ok())
            .flatten();
        let root = install_path(&parse(&located), located_scope);
        if root.exists() {
            inputs.push(PackageInput {
                source: source.to_owned(),
                scope: scope.to_owned(),
                root,
                filter,
            });
        }
    }
    inputs
}