runner-run 0.11.0

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
//! Typed JSON shapes for `--json` output across `doctor`, `info`, `list`, and `why`.
//!
//! Every subcommand projects from the single source-of-truth [`Project`]
//! struct so the contract is defined in one place. Doctor emits the full
//! struct; info/list emit projections (currently the full shape with
//! empty task tables collapsed away by `#[serde(skip_serializing_if)]`).
//!
//! Version negotiation: [`Project::build_with_schema`] takes the requested
//! schema version and routes per-field label resolution through
//! [`super::labels::source_label_for`]. Today the *shape* of `Project`
//! is identical across v1 and v2 — only label *values* differ. If a
//! future version diverges in shape, split this struct per-version and
//! keep the builder switch in here.

use std::collections::BTreeMap;

use serde::Serialize;

use super::labels::source_label_for;
use crate::resolver::{
    FallbackPolicy, MismatchPolicy, OverrideOrigin, ResolutionOverrides, Resolver,
};
use crate::tool::node::{ManifestSource, detect_pm_from_manifest};
use crate::types::{DetectionWarning, PackageManager, ProjectContext, TaskSource};

/// The canonical machine-readable view of a project, used by every
/// `--json` surface. Field order is preserved by `serde_json` so
/// consumers can hand-write `jq` queries without sort surprises.
#[derive(Debug, Serialize)]
pub(crate) struct Project<'a> {
    /// Increments on any breaking change to this schema. Consumers
    /// should reject anything they weren't built for.
    pub schema_version: u32,
    /// Absolute path of the project root the report describes.
    pub root: String,
    /// Detected ecosystems, in the order their package managers were
    /// found by [`crate::detect`].
    pub ecosystems: Vec<&'static str>,
    /// Raw, type-deduplicated detection results: PMs, runners, Node
    /// version, monorepo flag. Stable across resolver behavior tweaks.
    pub detected: Detected<'a>,
    /// Effective override stack — CLI, env, and config bundled.
    pub overrides: OverridesView,
    /// Per-ecosystem detection signals: lockfile pick, manifest
    /// declaration, PATH probe results.
    pub signals: Signals,
    /// Resolver verdict (or first-class error if the chain bailed).
    pub decisions: Decisions,
    /// Full task list. Subcommands that don't care omit this via
    /// projection.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub tasks: Vec<TaskInfo<'a>>,
    /// Diagnostic warnings from both detection (`ctx.warnings`) and
    /// the resolver (`ResolvedPm.warnings`), flattened.
    pub warnings: Vec<WarningInfo>,
}

impl<'a> Project<'a> {
    /// Build the full report at the latest [`super::CURRENT_VERSION`].
    /// Test-only convenience — production callers go through the
    /// dispatcher, which validates `--schema-version` and always
    /// passes a concrete version to [`Self::build_with_schema`].
    #[cfg(test)]
    pub(crate) fn build(ctx: &'a ProjectContext, overrides: &ResolutionOverrides) -> Self {
        Self::build_with_schema(ctx, overrides, super::CURRENT_VERSION)
    }

    /// Build the report against a specific schema version. `schema_version`
    /// must be a value [`super::validate_schema_version`] would accept;
    /// callers validate before calling so the CLI surfaces a useful error.
    ///
    /// Per-field versioning: source labels route through
    /// [`super::labels::source_label_for`]. PM and `TaskRunner` labels
    /// are unchanged across versions.
    pub(crate) fn build_with_schema(
        ctx: &'a ProjectContext,
        overrides: &ResolutionOverrides,
        schema_version: u32,
    ) -> Self {
        let manifest_decl = detect_pm_from_manifest(&ctx.root);
        let manifest_pm = manifest_decl.as_ref().map(|d| ManifestPm {
            pm: d.pm.label(),
            source: match d.source {
                ManifestSource::PackageManager => "packageManager",
                ManifestSource::DevEngines => "devEngines.packageManager",
            },
            version: d.version.clone(),
            on_fail: d.on_fail.label(),
        });

        let (decisions, resolver_warnings) = decisions_for(ctx, overrides);

        let warnings = ctx
            .warnings
            .iter()
            .chain(resolver_warnings.iter())
            .map(WarningInfo::from_warning)
            .collect();

        let tasks = ctx
            .tasks
            .iter()
            .map(|t| TaskInfo {
                name: &t.name,
                source: source_label_for(t.source, schema_version),
                description: t.description.as_deref(),
                alias_of: t.alias_of.as_deref(),
                passthrough_to: t.passthrough_to.map(crate::types::TaskRunner::label),
            })
            .collect();

        Self {
            schema_version,
            root: ctx.root.display().to_string(),
            ecosystems: ctx
                .package_managers
                .iter()
                .map(|pm| pm.ecosystem().label())
                .collect(),
            detected: Detected::from_ctx(ctx),
            overrides: OverridesView::from_resolution_overrides(overrides),
            signals: Signals {
                node: NodeSignals {
                    lockfile_pm: ctx.primary_node_pm().map(PackageManager::label),
                    manifest_pm,
                    path_probe: path_probe_map(),
                },
            },
            decisions,
            tasks,
            warnings,
        }
    }

    /// Project the full report to an `info`-shaped view: same shape
    /// minus the per-task detail (which `info` doesn't need; `list` is
    /// the dedicated task surface).
    pub(crate) fn into_info_view(mut self) -> Self {
        self.tasks.clear();
        self
    }

    /// Project the full report to a `list`-shaped view: just the
    /// tasks (filtered by `source` when set) plus the schema version
    /// and root. Drops resolver state — `list` is purely a directory
    /// listing for tasks.
    pub(crate) fn into_list_view(self, source: Option<TaskSource>) -> TaskListView<'a> {
        // The filter compares against whichever label flavor the report
        // was built with — v1 emits filename-style strings (`"justfile"`),
        // v2 emits tool names (`"just"`). Using `t.source` (already
        // version-resolved at build time) keeps the comparison correct
        // no matter which schema the caller asked for.
        let target = source.map(|s| source_label_for(s, self.schema_version));
        let tasks = self
            .tasks
            .into_iter()
            .filter(|t| target.is_none_or(|expected| expected == t.source))
            .collect();
        TaskListView {
            schema_version: self.schema_version,
            root: self.root,
            tasks,
        }
    }
}

/// `list --json` projection. Same `schema_version` as [`Project`] so
/// consumers can branch on it.
#[derive(Debug, Serialize)]
pub(crate) struct TaskListView<'a> {
    /// Identical to [`Project::schema_version`]; consumers can assume
    /// `1` here means a v1-shaped `tasks` array.
    pub schema_version: u32,
    /// Project root.
    pub root: String,
    /// Tasks, optionally filtered by source.
    pub tasks: Vec<TaskInfo<'a>>,
}

/// Detection results — what the file scan found, before any resolver
/// policy was applied.
#[derive(Debug, Serialize)]
pub(crate) struct Detected<'a> {
    /// Detected package managers, in detection-priority order.
    pub package_managers: Vec<&'static str>,
    /// Detected task runners.
    pub task_runners: Vec<&'static str>,
    /// `.nvmrc` / `.node-version` / `engines.node` declaration.
    pub node_version: Option<NodeVersionInfo<'a>>,
    /// `node --version` output, when the binary is on PATH.
    pub current_node: Option<&'a str>,
    /// Whether the project looks like a monorepo (workspace globs).
    pub monorepo: bool,
}

impl<'a> Detected<'a> {
    fn from_ctx(ctx: &'a ProjectContext) -> Self {
        Self {
            package_managers: ctx.package_managers.iter().map(|pm| pm.label()).collect(),
            task_runners: ctx.task_runners.iter().map(|tr| tr.label()).collect(),
            node_version: ctx.node_version.as_ref().map(|nv| NodeVersionInfo {
                expected: &nv.expected,
                source: nv.source,
            }),
            current_node: ctx.current_node.as_deref(),
            monorepo: ctx.is_monorepo,
        }
    }
}

/// Node version declaration plus the file it came from.
#[derive(Debug, Serialize)]
pub(crate) struct NodeVersionInfo<'a> {
    /// Version string as written (e.g. `"20.11.0"`, `">=18"`).
    pub expected: &'a str,
    /// Source file that declared the version (e.g. `".nvmrc"`).
    pub source: &'static str,
}

/// Materialised override stack — the inputs that fed into resolver
/// decisions.
#[derive(Debug, Serialize)]
pub(crate) struct OverridesView {
    /// Cross-ecosystem PM override from `--pm` / `RUNNER_PM`.
    pub pm: Option<PmOverrideInfo>,
    /// Per-ecosystem PM overrides from `runner.toml [pm].<eco>`.
    pub pm_by_ecosystem: BTreeMap<String, PmOverrideInfo>,
    /// `--runner` / `RUNNER_RUNNER` override.
    pub runner: Option<RunnerOverrideInfo>,
    /// Ranked preference list from `[task_runner].prefer`.
    pub prefer_runners: Vec<&'static str>,
    /// Active `FallbackPolicy` label.
    pub fallback: &'static str,
    /// Active `MismatchPolicy` label.
    pub on_mismatch: &'static str,
    /// Whether the explain trace is on.
    pub explain: bool,
    /// Whether warnings are suppressed.
    pub no_warnings: bool,
}

impl OverridesView {
    fn from_resolution_overrides(overrides: &ResolutionOverrides) -> Self {
        let mut pm_by_eco = BTreeMap::new();
        for (eco, pm_override) in &overrides.pm_by_ecosystem {
            pm_by_eco.insert(
                eco.label().to_string(),
                PmOverrideInfo {
                    pm: pm_override.pm.label(),
                    origin: origin_label(&pm_override.origin),
                },
            );
        }
        Self {
            pm: overrides.pm.as_ref().map(|o| PmOverrideInfo {
                pm: o.pm.label(),
                origin: origin_label(&o.origin),
            }),
            pm_by_ecosystem: pm_by_eco,
            runner: overrides.runner.as_ref().map(|o| RunnerOverrideInfo {
                runner: o.runner.label(),
                origin: origin_label(&o.origin),
            }),
            prefer_runners: overrides.prefer_runners.iter().map(|r| r.label()).collect(),
            fallback: fallback_label(overrides.fallback),
            on_mismatch: mismatch_label(overrides.on_mismatch),
            explain: overrides.explain,
            no_warnings: overrides.no_warnings,
        }
    }
}

/// PM override + provenance.
#[derive(Debug, Serialize)]
pub(crate) struct PmOverrideInfo {
    /// The chosen PM label.
    pub pm: &'static str,
    /// `"cli"`, `"env"`, or `"config:/abs/path"`.
    pub origin: String,
}

/// Task-runner override + provenance.
#[derive(Debug, Serialize)]
pub(crate) struct RunnerOverrideInfo {
    /// The chosen runner label.
    pub runner: &'static str,
    /// `"cli"`, `"env"`, or `"config:/abs/path"`.
    pub origin: String,
}

/// Per-ecosystem signals — what the resolver had to work with.
#[derive(Debug, Serialize)]
pub(crate) struct Signals {
    /// Node-ecosystem signals. The schema is intentionally
    /// node-flat today; other ecosystems get peer fields as their
    /// resolver paths land.
    pub node: NodeSignals,
}

/// Node-ecosystem detection signals: lockfile, manifest, PATH probe.
#[derive(Debug, Serialize)]
pub(crate) struct NodeSignals {
    /// PM inferred from the highest-priority lockfile, if any.
    pub lockfile_pm: Option<&'static str>,
    /// Manifest declaration (legacy `packageManager` or `devEngines`).
    pub manifest_pm: Option<ManifestPm>,
    /// `bun`/`pnpm`/`yarn`/`npm` -> absolute path on `$PATH` (or null).
    pub path_probe: BTreeMap<&'static str, Option<String>>,
}

/// Manifest-level PM declaration plus the field it came from.
#[derive(Debug, Serialize)]
pub(crate) struct ManifestPm {
    /// Declared PM label.
    pub pm: &'static str,
    /// Either `"packageManager"` or `"devEngines.packageManager"`.
    pub source: &'static str,
    /// Version constraint as written, if present.
    pub version: Option<String>,
    /// Effective `onFail` policy (`"ignore"`, `"warn"`, `"error"`).
    pub on_fail: &'static str,
}

/// Resolver verdict surface. Mirrors the resolver's `Result` so
/// consumers can branch on the variant before reading the inner shape.
#[derive(Debug, Serialize)]
pub(crate) struct Decisions {
    /// Node script-dispatch PM decision, or an error message when the
    /// resolver bailed.
    pub node_pm: NodePmDecision,
}

/// Either a resolved Node PM or the diagnostic string for the failure
/// that prevented one. Untagged so consumers can probe via "is the
/// `pm` field present?".
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub(crate) enum NodePmDecision {
    /// Successful resolution.
    Resolved {
        /// The chosen PM label.
        pm: &'static str,
        /// Human-readable `via` line — the same string `--explain` prints.
        via: String,
    },
    /// Resolver bailed; carries the rendered error message.
    Error {
        /// One-line error description from `ResolveError::Display`.
        error: String,
    },
}

/// Task entry projected into the JSON shape.
#[derive(Debug, Serialize)]
pub(crate) struct TaskInfo<'a> {
    /// Task name as it appears in the config.
    pub name: &'a str,
    /// Source label — version-resolved at build time via
    /// [`super::labels::source_label_for`].
    pub source: &'static str,
    /// Human-readable description, if any.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<&'a str>,
    /// When the task is an alias, the target it resolves to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alias_of: Option<&'a str>,
    /// When the task's body is a thin wrapper for another runner.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub passthrough_to: Option<&'static str>,
}

/// Warning projected into the JSON shape. The `source`/`detail` split
/// is kept stable from the pre-A4 flat-struct days so existing
/// consumers (the `doctor` test suite, ad-hoc `jq` queries) keep
/// working.
#[derive(Debug, Serialize)]
pub(crate) struct WarningInfo {
    /// Subsystem the warning came from (e.g. `"package.json"`).
    pub source: &'static str,
    /// Human-readable detail.
    pub detail: String,
}

impl WarningInfo {
    fn from_warning(warning: &DetectionWarning) -> Self {
        Self {
            source: warning.source(),
            detail: warning.detail(),
        }
    }
}

fn decisions_for(
    ctx: &ProjectContext,
    overrides: &ResolutionOverrides,
) -> (Decisions, Vec<DetectionWarning>) {
    match Resolver::new(ctx, overrides).resolve_node_pm() {
        Ok(decision) => {
            let warnings = decision.warnings.clone();
            (
                Decisions {
                    node_pm: NodePmDecision::Resolved {
                        pm: decision.pm.label(),
                        via: decision.describe(),
                    },
                },
                warnings,
            )
        }
        Err(err) => (
            Decisions {
                node_pm: NodePmDecision::Error {
                    error: format!("{err}"),
                },
            },
            Vec::new(),
        ),
    }
}

fn origin_label(origin: &OverrideOrigin) -> String {
    match origin {
        OverrideOrigin::CliFlag => "cli".to_string(),
        OverrideOrigin::EnvVar => "env".to_string(),
        OverrideOrigin::ConfigFile { path } => format!("config:{}", path.display()),
    }
}

const fn fallback_label(policy: FallbackPolicy) -> &'static str {
    match policy {
        FallbackPolicy::Probe => "probe",
        FallbackPolicy::Npm => "npm",
        FallbackPolicy::Error => "error",
    }
}

const fn mismatch_label(policy: MismatchPolicy) -> &'static str {
    match policy {
        MismatchPolicy::Warn => "warn",
        MismatchPolicy::Error => "error",
        MismatchPolicy::Ignore => "ignore",
    }
}

/// Probe each Node PM in canonical order and report (binary, path) pairs.
/// Used by the doctor signals section; intentionally calls the real probe
/// so the output reflects what the resolver would see.
///
/// Probes run in parallel via [`std::thread::scope`]: each `probe_path_for_doctor`
/// call walks the entire `PATH` searching for one binary, which is O(N
/// entries) of independent `stat` syscalls. Doctor isn't on the hot
/// path, but four-way fan-out is essentially free and keeps the
/// rendering snappy on `PATH`s that contain network-mounted directories.
const PATH_PROBE_PMS: [PackageManager; 4] = [
    PackageManager::Bun,
    PackageManager::Pnpm,
    PackageManager::Yarn,
    PackageManager::Npm,
];

fn path_probe_map() -> BTreeMap<&'static str, Option<String>> {
    use std::env;
    use std::thread;

    let path = env::var_os("PATH").unwrap_or_default();
    let pathext = env::var_os("PATHEXT");
    let pathext_ref = pathext.as_deref();

    thread::scope(|s| {
        // Spawn all probes first (push, don't lazy-iterate) so they
        // actually run in parallel; chaining `.map(spawn).map(join)`
        // without the eager push would serialize — `Iterator::map` is
        // lazy, so the next `spawn` wouldn't fire until the previous
        // join returned.
        let mut handles = Vec::with_capacity(PATH_PROBE_PMS.len());
        for pm in &PATH_PROBE_PMS {
            let path = &path;
            handles.push(s.spawn(move || {
                let resolved =
                    crate::resolver::probe_path_for_doctor(pm.label(), path, pathext_ref)
                        .map(|p| p.display().to_string());
                (pm.label(), resolved)
            }));
        }

        let mut map = BTreeMap::new();
        for handle in handles {
            let (label, resolved) = handle.join().expect("path probe thread panicked");
            map.insert(label, resolved);
        }
        map
    })
}

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

    use super::Project;
    use crate::resolver::ResolutionOverrides;
    use crate::types::{PackageManager, ProjectContext, Task, TaskSource};

    fn empty_context(root: &str) -> ProjectContext {
        ProjectContext {
            root: PathBuf::from(root),
            package_managers: vec![PackageManager::Pnpm],
            task_runners: Vec::new(),
            tasks: Vec::new(),
            node_version: None,
            current_node: None,
            is_monorepo: false,
            warnings: Vec::new(),
        }
    }

    #[test]
    fn project_serializes_schema_version_field() {
        let ctx = empty_context("/tmp/test");
        let overrides = ResolutionOverrides::default();
        let project = Project::build(&ctx, &overrides);
        let value = serde_json::to_value(&project).expect("Project should serialize to JSON");

        assert_eq!(value["schema_version"], 2);
        assert_eq!(value["root"], "/tmp/test");
        assert!(
            value["ecosystems"]
                .as_array()
                .is_some_and(|a| !a.is_empty())
        );
    }

    #[test]
    fn info_view_drops_tasks_array() {
        let mut ctx = empty_context("/tmp/test");
        ctx.tasks.push(Task {
            name: "build".to_string(),
            source: TaskSource::PackageJson,
            run_target: None,
            description: None,
            alias_of: None,
            passthrough_to: None,
        });
        let project = Project::build(&ctx, &ResolutionOverrides::default()).into_info_view();
        let value = serde_json::to_value(&project).expect("info view should serialize");

        // `skip_serializing_if = Vec::is_empty` collapses to no field.
        assert!(value.get("tasks").is_none(), "info view should omit tasks");
    }

    #[test]
    fn list_view_filters_by_source() {
        let mut ctx = empty_context("/tmp/test");
        ctx.tasks.push(Task {
            name: "build".to_string(),
            source: TaskSource::PackageJson,
            run_target: None,
            description: None,
            alias_of: None,
            passthrough_to: None,
        });
        ctx.tasks.push(Task {
            name: "fmt".to_string(),
            source: TaskSource::Justfile,
            run_target: None,
            description: None,
            alias_of: None,
            passthrough_to: None,
        });
        let project = Project::build(&ctx, &ResolutionOverrides::default());
        let view = project.into_list_view(Some(TaskSource::Justfile));

        assert_eq!(view.tasks.len(), 1);
        assert_eq!(view.tasks[0].name, "fmt");
    }

    #[test]
    fn build_with_schema_serializes_v1_labels_for_tasks() {
        let ctx = ProjectContext {
            root: PathBuf::from("/tmp/test"),
            package_managers: Vec::new(),
            task_runners: Vec::new(),
            tasks: vec![Task {
                name: "fmt".to_string(),
                source: TaskSource::Justfile,
                run_target: None,
                description: None,
                alias_of: None,
                passthrough_to: None,
            }],
            node_version: None,
            current_node: None,
            is_monorepo: false,
            warnings: Vec::new(),
        };

        let v1 = Project::build_with_schema(&ctx, &ResolutionOverrides::default(), 1);
        let v1_json = serde_json::to_value(&v1).expect("v1 serialization");
        assert_eq!(v1_json["schema_version"], 1);
        assert_eq!(v1_json["tasks"][0]["source"], "justfile");

        let v2 = Project::build_with_schema(&ctx, &ResolutionOverrides::default(), 2);
        let v2_json = serde_json::to_value(&v2).expect("v2 serialization");
        assert_eq!(v2_json["schema_version"], 2);
        assert_eq!(v2_json["tasks"][0]["source"], "just");
    }
}