runner-run 0.19.1

Universal project task runner
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
//! `runner.toml` — project-level configuration.
//!
//! The file lives at the project root. The resolver reads it as step 4 of
//! the precedence chain (after CLI flags and environment variables, before
//! manifest declarations).
//!
//! Schema:
//!
//! ```toml
//! [pm]
//! node   = "pnpm"      # one of npm|pnpm|yarn|bun|deno
//! python = "uv"        # one of uv|poetry|pipenv
//!
//! [task_runner]
//! prefer = ["just", "turbo"]
//!
//! [resolution]
//! fallback     = "probe"   # probe|npm|error
//! on_mismatch  = "warn"    # warn|error|ignore
//! ```
//!
//! Parsing is **forward-compatible**: an unknown section or field (a typo,
//! or a key a newer `runner` added) is ignored rather than fatal, so a
//! config written by one version never bricks task dispatch under another.
//! Unknown keys are still surfaced as warnings (see [`collect_unknown_keys`])
//! so genuine typos stay visible. The JSON Schema keeps
//! `additionalProperties: false` (via `schemars(deny_unknown_fields)`), so
//! editors flag typos inline even though the runtime tolerates them.
//!
//! Adding a new knob is two changes: a field on the matching section plus a
//! consumer in `crate::resolver`. Keep [`KNOWN_SCHEMA`] in sync so the new
//! key isn't mis-reported as unknown.

use std::collections::BTreeMap;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};

use anyhow::{Context as _, Result, anyhow};
use serde::{Deserialize, Serialize};

use crate::types::{DetectionWarning, Ecosystem, PackageManager};

/// Canonical config filename, written by `runner config init`. Its dotfile form
/// (`.` + this) is the hidden variant; both are accepted during discovery.
pub(crate) const CONFIG_FILENAME: &str = "runner.toml";

/// Directories searched for a config, relative to the loaded directory, highest
/// precedence first: the directory itself (`""`) and its `.config/` subdir.
pub(crate) const CONFIG_DIRS: [&str; 2] = ["", ".config"];

/// Starter `runner.toml` scaffolded by `runner config init`. Generated from
/// [`RunnerConfig`]'s schemars metadata (section/field doc comments) plus a
/// small hand-picked value/hint table — see
/// `cmd::schema::render_init_template` — so a field can't silently ship
/// without scaffold coverage. Regenerate with `just gen-schema` after
/// changing a section struct; a drift-guard test enforces this file stays
/// in sync.
pub(crate) const INIT_TEMPLATE: &str = include_str!("../schemas/runner.init.toml");

/// Parsed `runner.toml` content plus the absolute path it was loaded from.
#[derive(Debug, Clone)]
pub(crate) struct LoadedConfig {
    /// Absolute path the config was read from. Echoed back in resolver
    /// traces and the `runner doctor` output (Phase 6).
    pub path: PathBuf,
    /// Parsed config sections.
    pub config: RunnerConfig,
    /// Unknown sections/fields the parse tolerated (forward compat). Carried
    /// so the dispatcher can fold them into `ctx.warnings` and `config
    /// validate` can report them, instead of silently dropping them.
    pub warnings: Vec<DetectionWarning>,
}

/// Top-level schema for `runner.toml`.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[cfg_attr(
    feature = "schema",
    derive(schemars::JsonSchema),
    schemars(deny_unknown_fields)
)]
pub(crate) struct RunnerConfig {
    /// `[pm]` — per-ecosystem package-manager overrides.
    #[serde(default)]
    pub pm: PmSection,
    /// `[tasks]` — persistent task-source preference (global order + per-task pins).
    #[serde(default)]
    pub tasks: TasksSection,
    /// `[task_runner]` — task-runner preferences. Deprecated; superseded
    /// by [`Self::tasks`].
    #[serde(default, rename = "task_runner")]
    pub task_runner: TaskRunnerSection,
    /// `[install]` — restrict which detected PMs `runner install` runs.
    #[serde(default)]
    pub install: InstallSection,
    /// `[resolution]` — resolver-policy knobs.
    #[serde(default)]
    pub resolution: ResolutionSection,
    /// `[chain]` — failure policy for multi-task chains.
    #[serde(default)]
    pub chain: ChainSection,
    /// `[github]` — GitHub Actions integration (output grouping).
    #[serde(default)]
    pub github: GitHubSection,
    /// `[parallel]` — presentation of parallel (`-p`) chain output.
    #[serde(default)]
    pub parallel: ParallelSection,
}

/// `[install]` section — restrict which detected package managers
/// `runner install` runs with. Absent or empty installs every detected
/// PM (the default). Overridden by `RUNNER_INSTALL_PMS`.
///
/// Unlike `[pm]` (which scopes *script dispatch* per ecosystem), this
/// scopes the *install fan-out*: in a polyglot repo where both `bun` and
/// `deno` would write `node_modules`, `pms = ["bun"]` keeps install to bun.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[cfg_attr(
    feature = "schema",
    derive(schemars::JsonSchema),
    schemars(deny_unknown_fields)
)]
pub(crate) struct InstallSection {
    /// Allowlist of package-manager labels to install with, e.g.
    /// `["bun"]`. Each must be a detected PM or `runner install` errors.
    /// Empty = install with every detected PM.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub pms: Vec<String>,

    /// Lifecycle-script policy for the install. `"deny"` skips lifecycle
    /// scripts wherever the package manager exposes a skip mechanism
    /// (npm/yarn/pnpm/bun `--ignore-scripts`, composer `--no-scripts`,
    /// yarn-berry `YARN_ENABLE_SCRIPTS=false`; deno already denies by
    /// default), warning for the managers that cannot. `"allow"` forces
    /// scripts on wherever a manager can express it (npm `--no-ignore-scripts`,
    /// yarn-berry `YARN_ENABLE_SCRIPTS=true`, deno `--allow-scripts`); managers
    /// that already run scripts by default are satisfied without a flag, while
    /// bun and pnpm (>=10) warn because re-enabling their dependency build
    /// scripts needs a manifest allowlist (`trustedDependencies` /
    /// `onlyBuiltDependencies`) runner won't write. Absent leaves every manager
    /// at its default. Overridden by `RUNNER_INSTALL_SCRIPTS`, then the
    /// `--no-scripts` / `--scripts` flags.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(
        feature = "schema",
        schemars(extend("enum" = ["deny", "allow", null]))
    )]
    pub scripts: Option<String>,
}

/// `[chain]` section — failure policy for `run -s/-p` chains and
/// `runner install <tasks>`.
// Fields are `Option<bool>` rather than `bool` so the resolver can
// distinguish "user explicitly set false" from "user didn't say":
// env-overrides-config layering means `[chain].keep_going = false` plus
// `RUNNER_KEEP_GOING=1` resolves to `true`.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[cfg_attr(
    feature = "schema",
    derive(schemars::JsonSchema),
    schemars(deny_unknown_fields)
)]
#[cfg_attr(
    feature = "schema",
    schemars(extend("not" = {
        "required": ["keep_going", "kill_on_fail"],
        "properties": {
            "keep_going": { "const": true },
            "kill_on_fail": { "const": true }
        }
    }))
)]
pub(crate) struct ChainSection {
    /// Run every task in the chain to completion regardless of failures.
    /// Mutually exclusive with `kill_on_fail`. Equivalent to `-k` /
    /// `RUNNER_KEEP_GOING`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub keep_going: Option<bool>,

    /// Parallel only: terminate sibling tasks immediately on first
    /// failure (forcible kill, not graceful shutdown — uncatchable on
    /// Unix). Mutually exclusive with `keep_going`. Equivalent to
    /// `--kill-on-fail` / `RUNNER_KILL_ON_FAIL`. Ignored in sequential
    /// contexts.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kill_on_fail: Option<bool>,
}

/// `[github]` section — GitHub Actions integration. Both knobs only take
/// effect under GitHub Actions (gated at the call site by
/// `actions_rs::env::is_github_actions`); in a normal terminal nothing here
/// changes behavior.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[cfg_attr(
    feature = "schema",
    derive(schemars::JsonSchema),
    schemars(deny_unknown_fields)
)]
pub(crate) struct GitHubSection {
    /// Wrap task output in `runner: <task>` groups under GitHub Actions.
    /// Defaults to `true`; set `false` to restore the old ungrouped output,
    /// including the live `[task]`-prefixed muxer for parallel runs.
    #[serde(default = "default_group_output")]
    pub group_output: bool,

    /// Under GitHub Actions, group parallel (`-p`) output: buffer each task
    /// and print it as one block on completion instead of interleaving lines
    /// live. Defaults to `true` (CI logs read better grouped), but only when
    /// [`Self::group_output`] is also true. The non-CI equivalent is
    /// `[parallel].grouped` (default `false`), so CI and local diverge unless
    /// you set them to match.
    #[serde(default = "default_github_group_parallel")]
    pub group_parallel: bool,
}

impl Default for GitHubSection {
    fn default() -> Self {
        Self {
            group_output: default_group_output(),
            group_parallel: default_github_group_parallel(),
        }
    }
}

/// Default for [`GitHubSection::group_output`]: grouping is on unless the
/// user opts out, so the CI-readability win is automatic.
const fn default_group_output() -> bool {
    true
}

/// Default for [`GitHubSection::group_parallel`]: under GitHub Actions,
/// parallel output is grouped by default for readable CI logs.
const fn default_github_group_parallel() -> bool {
    true
}

/// `[parallel]` section — how parallel (`-p`) chains present their output
/// **outside** GitHub Actions. (Under GitHub Actions, see
/// `[github].group_parallel` instead.)
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[cfg_attr(
    feature = "schema",
    derive(schemars::JsonSchema),
    schemars(deny_unknown_fields)
)]
pub(crate) struct ParallelSection {
    /// Buffer each parallel task's output and print it as one contiguous
    /// block the moment that task finishes (completion order — first done,
    /// first shown), instead of interleaving prefixed lines live. Defaults to
    /// `false` (the live `[task]`-prefixed muxer); set `true` to group even in
    /// a plain terminal, where a colored header delimits each block.
    #[serde(default)]
    pub grouped: bool,
}

/// `[pm]` section — per-ecosystem package manager overrides.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[cfg_attr(
    feature = "schema",
    derive(schemars::JsonSchema),
    schemars(deny_unknown_fields)
)]
pub(crate) struct PmSection {
    /// Package manager used to dispatch Node `package.json` scripts.
    /// Valid values: `npm`, `pnpm`, `yarn`, `bun`, `deno`.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(
        feature = "schema",
        schemars(extend("enum" = ["npm", "pnpm", "yarn", "bun", "deno", null]))
    )]
    pub node: Option<String>,
    /// Package manager used for Python ecosystems.
    /// Valid values: `uv`, `poetry`, `pipenv`.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(
        feature = "schema",
        schemars(extend("enum" = ["uv", "poetry", "pipenv", null]))
    )]
    pub python: Option<String>,
}

/// `[task_runner]` section — **deprecated**. Use `[tasks]` instead.
///
/// Kept for backward compatibility: existing `[task_runner].prefer` files
/// keep working (and emit a deprecation warning), but `[tasks].prefer` is the
/// supported successor — rank-only and able to name package managers, not just
/// task runners.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[cfg_attr(
    feature = "schema",
    derive(schemars::JsonSchema),
    schemars(deny_unknown_fields, extend("deprecated" = true))
)]
pub(crate) struct TaskRunnerSection {
    /// **Deprecated — use `[tasks].prefer` instead** (rank-only, and accepts
    /// package managers like `bun`, not just task runners). Migration:
    /// `[task_runner].prefer = ["turbo"]` → `[tasks].prefer = ["turbo"]`.
    ///
    /// Legacy behavior, still honored: a ranked preference list that
    /// *restricts* candidates to runners in the list (in listed order); a
    /// same-named task under a runner not in the list is hard-rejected.
    /// Valid values: `turbo`, `nx`, `make`, `just`, `task`, `mise`, `bacon`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[cfg_attr(feature = "schema", schemars(extend("deprecated" = true)))]
    pub prefer: Vec<String>,
}

/// `[tasks]` section — persistent task-source preference for ambiguous task
/// names (a name that exists under more than one source, e.g. a `package.json`
/// script *and* a `turbo` task).
///
/// Both knobs speak the same label vocabulary: a label is a task runner
/// (`turbo`, `make`, …), a package manager (`bun`, `npm`, `pnpm`, `yarn`,
/// `deno`, …), or a source name (`package.json`, `deno`, …). Package-manager
/// labels map to the script source they run (`bun` → `package.json`).
/// Selection here is **rank-only**: it never hard-rejects an unlisted source,
/// it only reorders. An explicit CLI qualifier (`package.json:test`),
/// `--runner`, or `--pm`/`RUNNER_PM` still outranks these file settings.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[cfg_attr(
    feature = "schema",
    derive(schemars::JsonSchema),
    schemars(deny_unknown_fields)
)]
pub(crate) struct TasksSection {
    /// Global tie-break order for ambiguous task names, highest priority
    /// first. Listed sources win over unlisted ones (which still run as
    /// lower-priority fallbacks). E.g. `prefer = ["turbo", "bun"]` makes a
    /// `turbo` task win, then a `package.json` script, then everything else.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub prefer: Vec<String>,
    /// Per-task pins that override [`Self::prefer`] for specific names:
    /// `overrides = { dev = "bun", build = "turbo" }`. A pin to a source the
    /// task doesn't have falls through to the normal ranking (no hard error).
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub overrides: BTreeMap<String, String>,
}

/// `[resolution]` section — resolver policy knobs.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[cfg_attr(
    feature = "schema",
    derive(schemars::JsonSchema),
    schemars(deny_unknown_fields)
)]
pub(crate) struct ResolutionSection {
    /// `probe` (default) — PATH probe in canonical order when no signals
    /// match; `npm` — legacy silent fallback; `error` — refuse to proceed.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(
        feature = "schema",
        schemars(extend("enum" = ["probe", "npm", "error", null]))
    )]
    pub fallback: Option<String>,
    /// `warn` (default), `error`, `ignore` — how to react when declaration
    /// (manifest field) disagrees with detection (lockfile).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(
        feature = "schema",
        schemars(extend("enum" = ["warn", "error", "ignore", null]))
    )]
    pub on_mismatch: Option<String>,
}

/// Recognized sections and their fields, mirroring the section structs and
/// [`INIT_TEMPLATE`]. A key absent from this table is reported as an
/// [`DetectionWarning::UnknownConfigKey`] rather than aborting the load, so a
/// config written by a newer `runner` never bricks an older binary (and vice
/// versa). Keep in sync when adding a section or field — the
/// `known_schema_covers_every_section` test guards section-level drift.
const KNOWN_SCHEMA: &[(&str, &[&str])] = &[
    ("pm", &["node", "python"]),
    ("task_runner", &["prefer"]),
    ("tasks", &["prefer", "overrides"]),
    ("install", &["pms", "scripts"]),
    ("resolution", &["fallback", "on_mismatch"]),
    ("chain", &["keep_going", "kill_on_fail"]),
    ("github", &["group_output", "group_parallel"]),
    ("parallel", &["grouped"]),
];

/// Collect forward-compat warnings for sections/fields this build doesn't
/// recognize. Walks the raw parsed table against [`KNOWN_SCHEMA`]; a
/// non-table where a section is expected is left for the typed deserialize to
/// reject (a genuine type error, not version skew).
pub(crate) fn collect_unknown_keys(value: &toml::Value) -> Vec<DetectionWarning> {
    let Some(table) = value.as_table() else {
        return Vec::new();
    };
    let mut warnings = Vec::new();
    for (section, body) in table {
        let Some((_, known_fields)) = KNOWN_SCHEMA.iter().find(|(name, _)| name == section) else {
            warnings.push(DetectionWarning::UnknownConfigKey {
                path: section.clone(),
            });
            continue;
        };
        if let Some(body) = body.as_table() {
            for field in body.keys() {
                if !known_fields.contains(&field.as_str()) {
                    warnings.push(DetectionWarning::UnknownConfigKey {
                        path: format!("{section}.{field}"),
                    });
                }
            }
        }
    }
    warnings
}

/// Load the project config, searching [`CONFIG_DIRS`] × plain/dotted
/// [`CONFIG_FILENAME`] in precedence order.
///
/// Returns `Ok(None)` when no candidate exists; `Ok(Some(_))` otherwise, with
/// `LoadedConfig::path` set to the file actually loaded. The parse is
/// forward-compatible: unknown sections/fields are tolerated (and returned as
/// `warnings`) so version skew never aborts the load. Genuine failures —
/// unreadable file, malformed TOML, or a wrong-typed *known* field — still
/// propagate as errors.
///
/// # Errors
///
/// Returns an error if a candidate file exists but cannot be read, isn't valid
/// TOML, or assigns the wrong type to a recognized field.
pub(crate) fn load(dir: &Path) -> Result<Option<LoadedConfig>> {
    let Some((path, content)) = read_first_candidate(dir)? else {
        return Ok(None);
    };

    // Parse once into a generic value: it lets us surface unknown keys as
    // warnings (forward compat) while still letting a wrong-typed known field
    // fail the typed conversion below.
    let value: toml::Value =
        toml::from_str(&content).with_context(|| format!("failed to parse {}", path.display()))?;
    let mut warnings = collect_unknown_keys(&value);
    let config: RunnerConfig = value
        .try_into()
        .with_context(|| format!("failed to parse {}", path.display()))?;
    warnings.extend(deprecation_warnings(&config));

    Ok(Some(LoadedConfig {
        path,
        config,
        warnings,
    }))
}

/// Read the first config file that exists, searching each [`CONFIG_DIRS`]
/// directory for the plain then dotted [`CONFIG_FILENAME`]. Directory precedence
/// is outer, so a config in the directory itself beats one in its `.config/`.
/// Returns the path and contents; `Ok(None)` when none exist.
///
/// # Errors
///
/// Propagates any read error other than "not found" (e.g. a permission error),
/// so a present-but-unreadable config never masquerades as absent.
fn read_first_candidate(dir: &Path) -> Result<Option<(PathBuf, String)>> {
    let dotted = format!(".{CONFIG_FILENAME}");
    let filenames = [CONFIG_FILENAME, dotted.as_str()];
    for subdir in CONFIG_DIRS {
        let base = if subdir.is_empty() {
            dir.to_path_buf()
        } else {
            dir.join(subdir)
        };
        for filename in filenames {
            let path = base.join(filename);
            match fs::read_to_string(&path) {
                Ok(content) => return Ok(Some((path, content))),
                Err(e) if e.kind() == io::ErrorKind::NotFound => {}
                Err(e) => {
                    return Err(e).with_context(|| format!("failed to read {}", path.display()));
                }
            }
        }
    }
    Ok(None)
}

/// Migration warnings for config keys that still work but have a supported
/// successor. Shared by [`load`] and the editor language server so both surface
/// the same nudge.
///
/// `[task_runner].prefer` is superseded by `[tasks]`: the warning flags whether
/// `[tasks]` overrides it this run so the message tells the truth either way.
pub(crate) fn deprecation_warnings(config: &RunnerConfig) -> Vec<DetectionWarning> {
    let mut out = Vec::new();
    if !config.task_runner.prefer.is_empty() {
        let prefer_set = !config.tasks.prefer.is_empty();
        let overrides_set = !config.tasks.overrides.is_empty();
        // Name whichever `[tasks]` knob actually superseded this run, so the
        // message never claims `tasks.prefer` is set when only `overrides` is.
        let replacement = if overrides_set && !prefer_set {
            "tasks.overrides"
        } else {
            "tasks.prefer"
        };
        out.push(DetectionWarning::DeprecatedConfigKey {
            path: "task_runner.prefer".to_string(),
            replacement,
            superseded: prefer_set || overrides_set,
        });
    }
    out
}

/// Validate `[pm].node` against the set of script-dispatching PMs.
///
/// # Errors
///
/// Returns an error if `raw` does not name a known PM, or if it names a PM
/// that cannot run `package.json` scripts (e.g. `cargo`).
pub(crate) fn parse_node_pm(raw: &str) -> Result<PackageManager> {
    let pm = PackageManager::from_label(raw)
        .ok_or_else(|| anyhow!("[pm].node: unknown package manager {raw:?}"))?;
    let eco = pm.ecosystem();
    if !matches!(eco, Ecosystem::Node | Ecosystem::Deno) {
        return Err(anyhow!(
            "[pm].node: {} cannot dispatch package.json scripts (it belongs to ecosystem {:?})",
            pm.label(),
            eco,
        ));
    }
    Ok(pm)
}

/// Validate `[pm].python` against the Python ecosystem.
///
/// # Errors
///
/// Returns an error if `raw` does not name a known PM or if the named PM
/// is not part of the Python ecosystem.
pub(crate) fn parse_python_pm(raw: &str) -> Result<PackageManager> {
    let pm = PackageManager::from_label(raw)
        .ok_or_else(|| anyhow!("[pm].python: unknown package manager {raw:?}"))?;
    if pm.ecosystem() != Ecosystem::Python {
        return Err(anyhow!(
            "[pm].python: {} is not a Python package manager",
            pm.label(),
        ));
    }
    Ok(pm)
}

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

    use super::{
        CONFIG_FILENAME, INIT_TEMPLATE, KNOWN_SCHEMA, LoadedConfig, RunnerConfig, load,
        parse_node_pm, parse_python_pm,
    };
    use crate::tool::test_support::TempDir;
    use crate::types::{DetectionWarning, PackageManager};

    /// Dotted paths of the unknown-key warnings a load produced.
    fn unknown_paths(loaded: &LoadedConfig) -> Vec<String> {
        loaded
            .warnings
            .iter()
            .filter_map(|w| match w {
                DetectionWarning::UnknownConfigKey { path } => Some(path.clone()),
                _ => None,
            })
            .collect()
    }

    #[test]
    fn load_returns_none_when_file_absent() {
        let dir = TempDir::new("config-absent");
        let result = load(dir.path()).expect("absent file should be Ok(None)");

        assert!(result.is_none());
    }

    #[test]
    fn load_discovers_hidden_dotfile() {
        let dir = TempDir::new("config-hidden");
        fs::write(dir.path().join(".runner.toml"), "[pm]\nnode = \"npm\"\n")
            .expect("seed hidden config");

        let loaded = load(dir.path())
            .expect("config should parse")
            .expect(".runner.toml should be discovered");

        assert!(loaded.path.ends_with(".runner.toml"));
    }

    #[test]
    fn load_discovers_config_dir_variant() {
        let dir = TempDir::new("config-dot-config-dir");
        fs::create_dir_all(dir.path().join(".config")).expect("mk .config");
        fs::write(
            dir.path().join(".config/runner.toml"),
            "[pm]\nnode = \"npm\"\n",
        )
        .expect("seed .config config");

        let loaded = load(dir.path())
            .expect("config should parse")
            .expect(".config/runner.toml should be discovered");

        assert!(loaded.path.ends_with("runner.toml"));
        assert!(loaded.path.to_string_lossy().contains(".config"));
    }

    #[test]
    fn load_prefers_canonical_over_fallbacks() {
        let dir = TempDir::new("config-precedence");
        fs::write(dir.path().join(CONFIG_FILENAME), "[pm]\nnode = \"npm\"\n")
            .expect("seed canonical");
        fs::write(dir.path().join(".runner.toml"), "[pm]\nnode = \"bun\"\n").expect("seed hidden");

        let loaded = load(dir.path())
            .expect("config should parse")
            .expect("config should be present");

        assert!(loaded.path.ends_with(CONFIG_FILENAME));
        assert_eq!(loaded.config.pm.node.as_deref(), Some("npm"));
    }

    #[test]
    fn load_prefers_root_over_config_dir() {
        let dir = TempDir::new("config-dir-precedence");
        fs::write(dir.path().join(CONFIG_FILENAME), "[pm]\nnode = \"npm\"\n")
            .expect("seed root config");
        fs::create_dir_all(dir.path().join(".config")).expect("mk .config");
        fs::write(
            dir.path().join(".config/runner.toml"),
            "[pm]\nnode = \"bun\"\n",
        )
        .expect("seed .config config");

        let loaded = load(dir.path())
            .expect("config should parse")
            .expect("config should be present");

        assert!(!loaded.path.to_string_lossy().contains(".config"));
        assert_eq!(loaded.config.pm.node.as_deref(), Some("npm"));
    }

    #[test]
    fn legacy_task_runner_prefer_warns_deprecated() {
        let dir = TempDir::new("config-deprecated-task-runner");
        fs::write(
            dir.path().join(CONFIG_FILENAME),
            "[task_runner]\nprefer = [\"turbo\"]\n",
        )
        .expect("seed config");

        let loaded = load(dir.path())
            .expect("config should parse")
            .expect("config should be present");

        assert!(
            loaded.warnings.iter().any(|w| matches!(
                w,
                DetectionWarning::DeprecatedConfigKey {
                    superseded: false,
                    ..
                }
            )),
            "expected a non-superseded deprecation warning, got: {:?}",
            loaded.warnings,
        );
    }

    #[test]
    fn tasks_section_marks_legacy_prefer_superseded() {
        let dir = TempDir::new("config-deprecated-superseded");
        fs::write(
            dir.path().join(CONFIG_FILENAME),
            "[task_runner]\nprefer = [\"turbo\"]\n\n[tasks]\nprefer = [\"bun\"]\n",
        )
        .expect("seed config");

        let loaded = load(dir.path())
            .expect("config should parse")
            .expect("config should be present");

        assert!(
            loaded.warnings.iter().any(|w| matches!(
                w,
                DetectionWarning::DeprecatedConfigKey {
                    superseded: true,
                    ..
                }
            )),
            "expected a superseded deprecation warning, got: {:?}",
            loaded.warnings,
        );
    }

    #[test]
    fn tasks_overrides_alone_names_itself_as_the_replacement() {
        let dir = TempDir::new("config-deprecated-overrides-only");
        fs::write(
            dir.path().join(CONFIG_FILENAME),
            "[task_runner]\nprefer = [\"turbo\"]\n\n[tasks.overrides]\nbuild = \"bun\"\n",
        )
        .expect("seed config");

        let loaded = load(dir.path())
            .expect("config should parse")
            .expect("config should be present");

        assert!(
            loaded.warnings.iter().any(|w| matches!(
                w,
                DetectionWarning::DeprecatedConfigKey {
                    superseded: true,
                    replacement: "tasks.overrides",
                    ..
                }
            )),
            "expected the warning to name tasks.overrides, got: {:?}",
            loaded.warnings,
        );
    }

    #[test]
    fn tasks_section_validates() {
        // `[tasks]` with a PM label and a per-task pin is a valid config —
        // the same check `runner config validate` runs.
        let dir = TempDir::new("config-tasks-valid");
        fs::write(
            dir.path().join(CONFIG_FILENAME),
            "[tasks]\nprefer = [\"turbo\", \"bun\"]\n\n[tasks.overrides]\nbuild = \"turbo\"\n",
        )
        .expect("seed config");

        let loaded = load(dir.path())
            .expect("config should parse")
            .expect("config should be present");
        crate::resolver::validate_config(&loaded).expect("a well-formed [tasks] section validates");
    }

    #[test]
    fn load_parses_pm_section() {
        let dir = TempDir::new("config-pm");
        fs::write(
            dir.path().join(CONFIG_FILENAME),
            "[pm]\nnode = \"pnpm\"\npython = \"uv\"\n",
        )
        .expect("config should be written");

        let loaded = load(dir.path())
            .expect("config should parse")
            .expect("config should be present");

        assert!(loaded.path.ends_with(CONFIG_FILENAME));
        assert_eq!(loaded.config.pm.node.as_deref(), Some("pnpm"));
        assert_eq!(loaded.config.pm.python.as_deref(), Some("uv"));
    }

    #[test]
    fn load_warns_on_unknown_section_without_failing() {
        // Forward compat: a section this build doesn't know (a typo, or one a
        // newer runner added) must not abort the load — it warns and the rest
        // of the config still applies.
        let dir = TempDir::new("config-unknown-key");
        fs::write(
            dir.path().join(CONFIG_FILENAME),
            "[pm]\nnode = \"bun\"\n[zoot]\nfoo = 1\n",
        )
        .expect("config should be written");

        let loaded = load(dir.path())
            .expect("unknown section must be tolerated, not fatal")
            .expect("config should be present");

        assert_eq!(unknown_paths(&loaded), vec!["zoot".to_string()]);
        // Known config beside the unknown section is still honored.
        assert_eq!(loaded.config.pm.node.as_deref(), Some("bun"));
    }

    #[test]
    fn load_warns_on_unknown_field_within_known_section() {
        let dir = TempDir::new("config-unknown-pm-key");
        fs::write(dir.path().join(CONFIG_FILENAME), "[pm]\nrust = \"cargo\"\n")
            .expect("config should be written");

        let loaded = load(dir.path())
            .expect("unknown field must be tolerated, not fatal")
            .expect("config should be present");

        assert_eq!(unknown_paths(&loaded), vec!["pm.rust".to_string()]);
    }

    #[test]
    fn load_still_rejects_wrong_type_on_known_field() {
        // Forward compat tolerates *unknown* keys, not garbage in *known*
        // ones: a wrong-typed known field is a genuine error, still fatal.
        let dir = TempDir::new("config-wrong-type");
        fs::write(
            dir.path().join(CONFIG_FILENAME),
            "[github]\ngroup_output = \"yes\"\n",
        )
        .expect("config should be written");

        let err = load(dir.path()).expect_err("wrong type on a known field must stay fatal");
        assert!(format!("{err:#}").contains("failed to parse"));
    }

    #[test]
    fn known_schema_matches_init_template_sections_and_fields() {
        // Guard KNOWN_SCHEMA against drift in both directions, at section AND
        // field granularity. The scaffold ships every non-deprecated knob
        // (commented out), so its sections/fields are the canonical set
        // modulo deprecated sections (see DEPRECATED_SECTIONS below), which
        // `render_init_template` deliberately omits so new users never get
        // handed one; a field missing from KNOWN_SCHEMA makes `config init`
        // write a file that warns about its own keys, while a stale
        // KNOWN_SCHEMA entry lists a field nobody can set. Equality catches
        // either, so adding a struct field forces the template and
        // KNOWN_SCHEMA to be updated alongside it.
        use std::collections::{BTreeMap, BTreeSet};

        // Sections KNOWN_SCHEMA recognizes (for backward-compat parsing) but
        // that `render_init_template` intentionally leaves out of the
        // scaffold because they're deprecated.
        const DEPRECATED_SECTIONS: &[&str] = &["task_runner"];

        // Walk the template into section -> {field names it emits}.
        let mut template: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
        let mut section: Option<String> = None;
        for line in INIT_TEMPLATE.lines() {
            let trimmed = line.trim();
            if let Some(rest) = trimmed.strip_prefix('[') {
                section = Some(rest.trim_end_matches(']').to_string());
                template
                    .entry(section.clone().expect("just set"))
                    .or_default();
                continue;
            }
            // Field lines are `key = ...`, shipped commented-out. Strip one
            // leading `#`, then keep only a bare-identifier left of `=` — that
            // shape excludes the prose comments, which carry no `key =`.
            let body = trimmed.strip_prefix('#').map_or(trimmed, str::trim);
            let Some((lhs, _)) = body.split_once('=') else {
                continue;
            };
            let key = lhs.trim();
            if !key.is_empty()
                && key.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
                && let Some(sec) = &section
            {
                template
                    .get_mut(sec)
                    .expect("section recorded above")
                    .insert(key.to_string());
            }
        }

        let mut known: BTreeMap<String, BTreeSet<String>> = KNOWN_SCHEMA
            .iter()
            .map(|(name, fields)| {
                (
                    (*name).to_string(),
                    fields.iter().map(|f| (*f).to_string()).collect(),
                )
            })
            .collect();
        for section in DEPRECATED_SECTIONS {
            known.remove(*section);
        }

        assert_eq!(
            template, known,
            "INIT_TEMPLATE sections/fields must match KNOWN_SCHEMA (minus DEPRECATED_SECTIONS) \
             exactly — keep the section structs, the scaffold template, and KNOWN_SCHEMA in sync \
             when adding a knob"
        );
    }

    #[cfg(feature = "schema")]
    #[test]
    fn known_schema_matches_generated_runner_config_schema() {
        // known_schema_matches_init_template_sections_and_fields only
        // catches INIT_TEMPLATE drifting from KNOWN_SCHEMA — a struct field
        // added to a section without updating either the scaffold or
        // KNOWN_SCHEMA passes that guard invisibly (template and KNOWN_SCHEMA
        // still agree with each other, just not with the real type; the
        // typed deserializer would accept the field while
        // `collect_unknown_keys` spuriously flags it as unknown). Compare
        // KNOWN_SCHEMA directly against the schemars-derived shape of
        // RunnerConfig, independent of the scaffold.
        use std::collections::{BTreeMap, BTreeSet};

        let schema = serde_json::to_value(schemars::schema_for!(RunnerConfig))
            .expect("RunnerConfig schema should serialize");

        let top_properties = schema["properties"]
            .as_object()
            .expect("RunnerConfig schema must have top-level properties");
        let defs = schema["$defs"]
            .as_object()
            .expect("RunnerConfig schema must have $defs");

        let generated: BTreeMap<String, BTreeSet<String>> = top_properties
            .iter()
            .map(|(section, section_schema)| {
                let def_name = section_schema["$ref"]
                    .as_str()
                    .and_then(|r| r.strip_prefix("#/$defs/"))
                    .unwrap_or_else(|| {
                        panic!(
                            "{section}: expected a $defs $ref in the generated schema, got \
                             {section_schema:?}"
                        )
                    });
                let fields = defs[def_name]["properties"]
                    .as_object()
                    .unwrap_or_else(|| {
                        panic!("{def_name}: expected a properties object in the generated schema")
                    })
                    .keys()
                    .cloned()
                    .collect();
                (section.clone(), fields)
            })
            .collect();

        let known: BTreeMap<String, BTreeSet<String>> = KNOWN_SCHEMA
            .iter()
            .map(|(name, fields)| {
                (
                    (*name).to_string(),
                    fields.iter().map(|f| (*f).to_string()).collect(),
                )
            })
            .collect();

        assert_eq!(
            generated, known,
            "KNOWN_SCHEMA must match RunnerConfig's real (schemars-derived) shape exactly — a \
             struct field with no KNOWN_SCHEMA entry is silently treated as unknown by \
             collect_unknown_keys even though the typed deserializer accepts it"
        );
    }

    #[test]
    fn parse_node_pm_accepts_node_and_deno() {
        assert_eq!(parse_node_pm("pnpm").unwrap(), PackageManager::Pnpm);
        assert_eq!(parse_node_pm("bun").unwrap(), PackageManager::Bun);
        assert_eq!(parse_node_pm("deno").unwrap(), PackageManager::Deno);
    }

    #[test]
    fn parse_node_pm_rejects_cross_ecosystem() {
        let err = parse_node_pm("cargo").expect_err("cargo should not be a Node PM");
        assert!(format!("{err}").contains("cannot dispatch package.json scripts"));
    }

    #[test]
    fn parse_python_pm_accepts_uv_poetry_pipenv() {
        assert_eq!(parse_python_pm("uv").unwrap(), PackageManager::Uv);
        assert_eq!(parse_python_pm("poetry").unwrap(), PackageManager::Poetry);
        assert_eq!(parse_python_pm("pipenv").unwrap(), PackageManager::Pipenv);
    }

    #[test]
    fn parse_python_pm_rejects_node_pm() {
        let err = parse_python_pm("pnpm").expect_err("pnpm should not be Python");
        assert!(format!("{err}").contains("not a Python package manager"));
    }

    #[test]
    fn load_parses_install_section() {
        let dir = TempDir::new("config-install");
        fs::write(
            dir.path().join(CONFIG_FILENAME),
            "[install]\npms = [\"bun\", \"cargo\"]\n",
        )
        .expect("config should be written");

        let loaded = load(dir.path())
            .expect("config should parse")
            .expect("config should be present");

        assert_eq!(loaded.config.install.pms, vec!["bun", "cargo"]);
    }

    #[test]
    fn load_parses_install_scripts() {
        let dir = TempDir::new("config-install-scripts");
        fs::write(
            dir.path().join(CONFIG_FILENAME),
            "[install]\nscripts = \"deny\"\n",
        )
        .expect("config should be written");

        let loaded = load(dir.path())
            .expect("config should parse")
            .expect("config should be present");

        assert_eq!(loaded.config.install.scripts.as_deref(), Some("deny"));
    }

    #[test]
    fn load_warns_on_unknown_install_key() {
        let dir = TempDir::new("config-unknown-install-key");
        fs::write(dir.path().join(CONFIG_FILENAME), "[install]\nfoo = true\n")
            .expect("config should be written");

        let loaded = load(dir.path())
            .expect("unknown [install] key tolerated")
            .expect("config present");
        assert_eq!(unknown_paths(&loaded), vec!["install.foo".to_string()]);
    }

    #[test]
    fn load_parses_chain_section() {
        let dir = TempDir::new("config-chain");
        fs::write(
            dir.path().join(CONFIG_FILENAME),
            "[chain]\nkeep_going = true\nkill_on_fail = false\n",
        )
        .expect("config should be written");

        let loaded = load(dir.path())
            .expect("config should parse")
            .expect("config should be present");

        assert_eq!(loaded.config.chain.keep_going, Some(true));
        assert_eq!(loaded.config.chain.kill_on_fail, Some(false));
    }

    #[test]
    fn load_warns_on_unknown_chain_key() {
        let dir = TempDir::new("config-unknown-chain-key");
        fs::write(dir.path().join(CONFIG_FILENAME), "[chain]\nfast = true\n")
            .expect("config should be written");

        let loaded = load(dir.path())
            .expect("unknown [chain] key tolerated")
            .expect("config present");
        assert_eq!(unknown_paths(&loaded), vec!["chain.fast".to_string()]);
    }

    #[test]
    fn load_parses_github_section() {
        let dir = TempDir::new("config-github");
        fs::write(
            dir.path().join(CONFIG_FILENAME),
            "[github]\ngroup_output = false\n",
        )
        .expect("config should be written");

        let loaded = load(dir.path())
            .expect("config should parse")
            .expect("config should be present");

        assert!(!loaded.config.github.group_output);
    }

    #[test]
    fn github_group_output_defaults_true_when_key_omitted() {
        let dir = TempDir::new("config-github-default");
        fs::write(dir.path().join(CONFIG_FILENAME), "[github]\n")
            .expect("config should be written");

        let loaded = load(dir.path())
            .expect("config should parse")
            .expect("config should be present");

        assert!(loaded.config.github.group_output);
    }

    #[test]
    fn github_group_output_defaults_true_when_section_absent() {
        let dir = TempDir::new("config-github-absent");
        fs::write(dir.path().join(CONFIG_FILENAME), "[pm]\nnode = \"npm\"\n")
            .expect("config should be written");

        let loaded = load(dir.path())
            .expect("config should parse")
            .expect("config should be present");

        assert!(loaded.config.github.group_output);
    }

    #[test]
    fn load_warns_on_unknown_github_key() {
        let dir = TempDir::new("config-unknown-github-key");
        fs::write(dir.path().join(CONFIG_FILENAME), "[github]\nfoo = true\n")
            .expect("config should be written");

        let loaded = load(dir.path())
            .expect("unknown [github] key tolerated")
            .expect("config present");
        assert_eq!(unknown_paths(&loaded), vec!["github.foo".to_string()]);
    }

    #[test]
    fn load_parses_parallel_grouped() {
        let dir = TempDir::new("config-parallel-grouped");
        fs::write(
            dir.path().join(CONFIG_FILENAME),
            "[parallel]\ngrouped = true\n",
        )
        .expect("config should be written");

        let loaded = load(dir.path())
            .expect("config should parse")
            .expect("config should be present");

        assert!(loaded.config.parallel.grouped);
    }

    #[test]
    fn parallel_grouped_defaults_false_when_section_absent() {
        let dir = TempDir::new("config-parallel-default");
        fs::write(dir.path().join(CONFIG_FILENAME), "[pm]\nnode = \"npm\"\n")
            .expect("config should be written");

        let loaded = load(dir.path())
            .expect("config should parse")
            .expect("config should be present");

        // Off by default outside GitHub Actions.
        assert!(!loaded.config.parallel.grouped);
    }

    #[test]
    fn load_warns_on_unknown_parallel_key() {
        let dir = TempDir::new("config-unknown-parallel-key");
        fs::write(dir.path().join(CONFIG_FILENAME), "[parallel]\nfoo = true\n")
            .expect("config should be written");

        let loaded = load(dir.path())
            .expect("unknown [parallel] key tolerated")
            .expect("config present");
        assert_eq!(unknown_paths(&loaded), vec!["parallel.foo".to_string()]);
    }

    #[test]
    fn load_parses_github_group_parallel() {
        let dir = TempDir::new("config-github-group-parallel");
        fs::write(
            dir.path().join(CONFIG_FILENAME),
            "[github]\ngroup_parallel = false\n",
        )
        .expect("config should be written");

        let loaded = load(dir.path())
            .expect("config should parse")
            .expect("config should be present");

        assert!(!loaded.config.github.group_parallel);
        // group_output is independent and still defaults true.
        assert!(loaded.config.github.group_output);
    }

    #[test]
    fn github_group_parallel_defaults_true() {
        let dir = TempDir::new("config-github-group-parallel-default");
        fs::write(dir.path().join(CONFIG_FILENAME), "[github]\n")
            .expect("config should be written");

        let loaded = load(dir.path())
            .expect("config should parse")
            .expect("config should be present");

        assert!(loaded.config.github.group_parallel);
    }
}