jarvy 0.5.1

Jarvy is a fast, cross-platform CLI that installs and manages developer tools across macOS and Linux.
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
//! `jarvy workspace` CLI handler (PRD-047 monorepo support).
//!
//! Surfaces three read-only subcommands over the existing `crate::workspace`
//! foundation (`find_workspace_root`, `merge_configs`):
//!
//! - `list`     — enumerate members with their resolved tool sets
//! - `show`     — pretty-print one member's resolved config + inheritance
//! - `validate` — sanity check each member (config parses, dir exists)
//!
//! Read-only by design. Workspace-aware `jarvy setup --project <name>`
//! orchestration is intentionally deferred — surfacing the workspace
//! structure first lets users debug inheritance before we add a
//! command that actually mutates the environment based on it.

use crate::cli::WorkspaceAction;
use crate::workspace;
use std::collections::BTreeMap;
use std::path::{Component, Path, PathBuf};

/// Refuse a workspace `members = [...]` entry that would escape the
/// workspace root (review item P0 #3). Returns the joined absolute
/// path on success.
///
/// We refuse:
/// - any `..` component (no parent-dir escapes — a member declared as
///   `"../../etc"` would otherwise let `validate`/`list`/`show` probe
///   arbitrary filesystem paths and read external jarvy.toml files)
/// - any absolute path (workspace members are always relative to the
///   workspace root)
/// - empty / windows-prefix components
///
/// Symlinks at the resolved member directory are NOT refused — a
/// monorepo legitimately uses symlinks for cross-language sources. The
/// containment check above prevents the link target being followed
/// outside the workspace at this layer; downstream file reads still
/// open through the symlink, which is the same posture a vanilla
/// `cargo build` takes.
fn resolve_member(root_dir: &Path, member: &str) -> Option<PathBuf> {
    let candidate = Path::new(member);
    if candidate.is_absolute() {
        return None;
    }
    for c in candidate.components() {
        match c {
            Component::Normal(_) | Component::CurDir => {}
            // ParentDir / RootDir / Prefix all refused.
            _ => return None,
        }
    }
    Some(root_dir.join(candidate))
}

pub fn run_workspace(action: &WorkspaceAction, file: &str) -> i32 {
    let project_dir = crate::paths::config_parent_dir(file);

    let ctx = match workspace::find_workspace_root(&project_dir) {
        Some(c) => c,
        None => {
            let fmt = action_format(action);
            if fmt == "json" {
                println!(
                    "{}",
                    serde_json::json!({
                        "status": "no_workspace",
                        "searched_from": project_dir.display().to_string(),
                    })
                );
            } else {
                eprintln!(
                    "No [workspace] section found walking up from {}.",
                    project_dir.display()
                );
                eprintln!(
                    "Add a `[workspace] members = [...]` block to a jarvy.toml at the repo root."
                );
            }
            return crate::error_codes::CONFIG_ERROR;
        }
    };

    match action {
        WorkspaceAction::List { output_format } => list(&ctx, output_format),
        WorkspaceAction::Show {
            name,
            output_format,
        } => show(&ctx, name, output_format),
        WorkspaceAction::Validate { output_format } => validate(&ctx, output_format),
    }
}

fn action_format(action: &WorkspaceAction) -> &str {
    match action {
        WorkspaceAction::List { output_format }
        | WorkspaceAction::Show { output_format, .. }
        | WorkspaceAction::Validate { output_format } => output_format.as_str(),
    }
}

fn list(ctx: &workspace::WorkspaceContext, output_format: &str) -> i32 {
    let root_dir = ctx.root_config.parent().unwrap_or(Path::new("."));
    let root_value = load_root_value(&ctx.root_config);
    // Expand `apps/*` globs + apply `exclude = [...]` (PRD-047 phase 2).
    let members = ctx.workspace.resolved_members(root_dir);
    let summaries: Vec<MemberSummary> = members
        .iter()
        .map(|m| collect_member_with_root(root_dir, m, ctx, &root_value))
        .collect();

    if output_format == "json" {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "workspace_root": root_dir.display().to_string(),
                "inherit": &ctx.workspace.inherit,
                "members": &summaries,
            }))
            .unwrap_or_else(|_| "{}".into())
        );
        return 0;
    }

    println!("Workspace: {}", root_dir.display());
    if !ctx.workspace.inherit.is_empty() {
        println!("Inherits: {}", ctx.workspace.inherit.join(", "));
    }
    println!("Members ({}):", summaries.len());
    for s in &summaries {
        let exists = if s.config_exists { "ok " } else { "MISS" };
        let tools = if s.tools.is_empty() {
            "(no tools)".to_string()
        } else {
            s.tools.keys().cloned().collect::<Vec<_>>().join(", ")
        };
        println!("  [{exists}] {:<22} {tools}", s.name);
    }
    0
}

fn show(ctx: &workspace::WorkspaceContext, name: &str, output_format: &str) -> i32 {
    let root_dir = ctx.root_config.parent().unwrap_or(Path::new("."));
    let resolved = ctx.workspace.resolved_members(root_dir);
    if !resolved.iter().any(|m| m == name) {
        if output_format == "json" {
            println!(
                "{}",
                serde_json::json!({"status": "unknown_member", "name": name})
            );
        } else {
            eprintln!("Member '{name}' not declared in [workspace] members.");
        }
        return crate::error_codes::CONFIG_ERROR;
    }

    let root_value = load_root_value(&ctx.root_config);
    let summary = collect_member_with_root(root_dir, name, ctx, &root_value);

    if output_format == "json" {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "workspace_root": root_dir.display().to_string(),
                "member": &summary,
            }))
            .unwrap_or_else(|_| "{}".into())
        );
        return 0;
    }

    println!("Project: {}", summary.name);
    println!("Path:    {}", summary.path);
    println!(
        "Config:  {}",
        if summary.config_exists {
            summary.config_path.clone()
        } else {
            format!("{} (missing)", summary.config_path)
        }
    );
    if !ctx.workspace.inherit.is_empty() {
        println!("Inherits sections: {}", ctx.workspace.inherit.join(", "));
    }
    println!();
    println!("Tools ({}):", summary.tools.len());
    for (name, version) in &summary.tools {
        let mark = if summary.overridden.contains(name) {
            " (overridden)"
        } else if summary.inherited.contains(name) {
            " (inherited)"
        } else {
            ""
        };
        println!("  {name} = \"{version}\"{mark}");
    }
    0
}

fn validate(ctx: &workspace::WorkspaceContext, output_format: &str) -> i32 {
    let root_dir = ctx.root_config.parent().unwrap_or(Path::new("."));
    let started = std::time::Instant::now();
    let telemetry_on = crate::observability::telemetry_gate::is_enabled();
    let mut warnings: Vec<String> = Vec::new();
    let mut errors: Vec<String> = Vec::new();
    let mut entries: Vec<serde_json::Value> = Vec::new();

    let resolved = ctx.workspace.resolved_members(root_dir);
    for member in &resolved {
        let Some(member_dir) = resolve_member(root_dir, member) else {
            // Refused at the containment check (review item P0 #3).
            // Surface as an error so validate exits CONFIG_ERROR and
            // a CI run on a hostile monorepo fails closed.
            errors.push(format!("{member}: refused — escapes workspace root"));
            if telemetry_on {
                tracing::warn!(
                    event = "workspace.member_invalid",
                    error_kind = "escapes_workspace_root",
                );
            }
            entries.push(serde_json::json!({
                "name": member,
                "refused": true,
                "reason": "escapes_workspace_root",
            }));
            continue;
        };
        let cfg_path = member_dir.join("jarvy.toml");
        let exists = member_dir.is_dir();
        let cfg_exists = cfg_path.exists();
        let parse_ok = if cfg_exists {
            std::fs::read_to_string(&cfg_path)
                .ok()
                .and_then(|s| toml::from_str::<toml::Value>(&s).ok())
                .is_some()
        } else {
            true
        };

        if !exists {
            errors.push(format!("{member}: directory missing"));
            if telemetry_on {
                tracing::warn!(
                    event = "workspace.member_invalid",
                    error_kind = "dir_missing",
                );
            }
        } else if !cfg_exists {
            warnings.push(format!(
                "{member}: no jarvy.toml (workspace defaults apply)"
            ));
        } else if !parse_ok {
            errors.push(format!("{member}: jarvy.toml failed to parse"));
            if telemetry_on {
                tracing::warn!(
                    event = "workspace.member_invalid",
                    error_kind = "toml_parse_fail",
                );
            }
        }

        entries.push(serde_json::json!({
            "name": member,
            "dir_exists": exists,
            "config_exists": cfg_exists,
            "config_parses": parse_ok,
        }));
    }

    if telemetry_on {
        let level_error = !errors.is_empty();
        let status = if level_error {
            "invalid"
        } else if !warnings.is_empty() {
            "warnings"
        } else {
            "ok"
        };
        let duration_ms = started.elapsed().as_millis() as u64;
        if level_error {
            tracing::warn!(
                event = "workspace.validate_completed",
                status = status,
                members = resolved.len(),
                errors = errors.len(),
                warnings = warnings.len(),
                duration_ms = duration_ms,
            );
        } else {
            tracing::info!(
                event = "workspace.validate_completed",
                status = status,
                members = resolved.len(),
                errors = errors.len(),
                warnings = warnings.len(),
                duration_ms = duration_ms,
            );
        }
    }

    if output_format == "json" {
        let status = if !errors.is_empty() {
            "invalid"
        } else if !warnings.is_empty() {
            "warnings"
        } else {
            "ok"
        };
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "status": status,
                "errors": errors,
                "warnings": warnings,
                "members": entries,
            }))
            .unwrap_or_else(|_| "{}".into())
        );
        return if errors.is_empty() {
            0
        } else {
            crate::error_codes::CONFIG_ERROR
        };
    }

    println!("Validating workspace at {}", root_dir.display());
    for line in &warnings {
        println!("  warn: {line}");
    }
    for line in &errors {
        println!("  err:  {line}");
    }
    if errors.is_empty() && warnings.is_empty() {
        println!("  All {} members ok.", resolved.len());
    } else {
        let total = resolved.len();
        let ok = total
            .saturating_sub(warnings.len())
            .saturating_sub(errors.len());
        println!(
            "  {ok} ok, {} warning(s), {} error(s).",
            warnings.len(),
            errors.len(),
        );
    }
    if errors.is_empty() {
        0
    } else {
        crate::error_codes::CONFIG_ERROR
    }
}

#[derive(serde::Serialize)]
struct MemberSummary {
    name: String,
    path: String,
    config_path: String,
    config_exists: bool,
    tools: BTreeMap<String, String>,
    inherited: Vec<String>,
    overridden: Vec<String>,
}

fn load_root_value(root_config: &Path) -> toml::Value {
    std::fs::read_to_string(root_config)
        .ok()
        .and_then(|s| toml::from_str(&s).ok())
        .unwrap_or_else(|| toml::Value::Table(toml::Table::new()))
}

fn collect_member_with_root(
    root_dir: &Path,
    member: &str,
    ctx: &workspace::WorkspaceContext,
    root_value: &toml::Value,
) -> MemberSummary {
    // Containment check — a hostile root config with
    // `members = ["../../etc"]` MUST NOT be allowed to probe outside
    // the workspace root via the side-channel of `is_dir()` / file
    // reads (review item P0 #3).
    let Some(member_dir) = resolve_member(root_dir, member) else {
        return MemberSummary {
            name: member.to_string(),
            path: format!("{} (refused: outside workspace)", member),
            config_path: String::new(),
            config_exists: false,
            tools: BTreeMap::new(),
            inherited: Vec::new(),
            overridden: Vec::new(),
        };
    };
    let cfg_path = member_dir.join("jarvy.toml");
    let config_exists = cfg_path.exists();

    let member_value: toml::Value = if config_exists {
        std::fs::read_to_string(&cfg_path)
            .ok()
            .and_then(|s| toml::from_str(&s).ok())
            .unwrap_or_else(|| toml::Value::Table(toml::Table::new()))
    } else {
        toml::Value::Table(toml::Table::new())
    };

    // Identical resolution to `crate::config::Config::new` workspace
    // path. Routing both through `effective_inherit` makes
    // `jarvy workspace show` and `jarvy setup` agree on which root
    // sections a member actually inherits (review item P0 #4).
    let inherit = ctx.workspace.effective_inherit();
    let merged = workspace::merge_configs(root_value, &member_value, &inherit);

    let mut tools: BTreeMap<String, String> = BTreeMap::new();
    let mut inherited: Vec<String> = Vec::new();
    let mut overridden: Vec<String> = Vec::new();

    // Just collect the KEY sets — we don't need the values (review
    // item P1 #10). Previous version cloned every `toml::Value` for
    // a containment check.
    let root_prov_keys: std::collections::HashSet<&str> = root_value
        .get("provisioner")
        .and_then(|v| v.as_table())
        .map(|t| t.keys().map(String::as_str).collect())
        .unwrap_or_default();
    let member_prov_keys: std::collections::HashSet<&str> = member_value
        .get("provisioner")
        .and_then(|v| v.as_table())
        .map(|t| t.keys().map(String::as_str).collect())
        .unwrap_or_default();

    if let Some(merged_prov) = merged.get("provisioner").and_then(|v| v.as_table()) {
        for (name, value) in merged_prov {
            tools.insert(name.clone(), value_to_string(value));
            let in_root = root_prov_keys.contains(name.as_str());
            let in_member = member_prov_keys.contains(name.as_str());
            if in_root && in_member {
                overridden.push(name.clone());
            } else if in_root && !in_member {
                inherited.push(name.clone());
            }
        }
    }

    MemberSummary {
        name: member.to_string(),
        path: member_dir.display().to_string(),
        config_path: cfg_path.display().to_string(),
        config_exists,
        tools,
        inherited,
        overridden,
    }
}

/// Backwards-compat shim for the existing test module — re-reads root
/// internally. Production callers use `collect_member_with_root`.
#[cfg(test)]
fn collect_member(
    root_dir: &Path,
    member: &str,
    ctx: &workspace::WorkspaceContext,
) -> MemberSummary {
    let root_value = load_root_value(&ctx.root_config);
    collect_member_with_root(root_dir, member, ctx, &root_value)
}

fn value_to_string(v: &toml::Value) -> String {
    match v {
        toml::Value::String(s) => s.clone(),
        other => other.to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    fn setup_workspace(root: &Path) {
        fs::write(
            root.join("jarvy.toml"),
            r#"
[workspace]
members = ["apps/web", "apps/api"]

[provisioner]
git = "latest"
docker = "latest"
"#,
        )
        .unwrap();
        fs::create_dir_all(root.join("apps/web")).unwrap();
        fs::create_dir_all(root.join("apps/api")).unwrap();
        fs::write(
            root.join("apps/web/jarvy.toml"),
            r#"
[provisioner]
node = "20"
docker = "24.0"
"#,
        )
        .unwrap();
        // apps/api intentionally has no jarvy.toml — exercises the
        // "workspace defaults apply" warning path.
    }

    #[test]
    fn list_includes_all_members() {
        let tmp = tempdir().unwrap();
        setup_workspace(tmp.path());
        let ctx = workspace::find_workspace_root(tmp.path()).unwrap();
        // smoke — list returns 0
        assert_eq!(list(&ctx, "pretty"), 0);
    }

    #[test]
    fn show_unknown_member_returns_config_error() {
        let tmp = tempdir().unwrap();
        setup_workspace(tmp.path());
        let ctx = workspace::find_workspace_root(tmp.path()).unwrap();
        let exit = show(&ctx, "ghost", "pretty");
        assert_eq!(exit, crate::error_codes::CONFIG_ERROR);
    }

    #[test]
    fn collect_member_marks_overridden_and_inherited() {
        let tmp = tempdir().unwrap();
        setup_workspace(tmp.path());
        let ctx = workspace::find_workspace_root(tmp.path()).unwrap();
        let summary = collect_member(tmp.path(), "apps/web", &ctx);
        // git: only in root → inherited
        assert!(summary.inherited.contains(&"git".to_string()));
        // docker: in both → overridden
        assert!(summary.overridden.contains(&"docker".to_string()));
        // node: only in member → not inherited, not overridden
        assert!(!summary.inherited.contains(&"node".to_string()));
        assert!(!summary.overridden.contains(&"node".to_string()));
        // Resolved value reflects the override (member wins).
        assert_eq!(summary.tools.get("docker"), Some(&"24.0".to_string()));
    }

    #[test]
    fn validate_flags_missing_member_jarvy_toml_as_warning() {
        let tmp = tempdir().unwrap();
        setup_workspace(tmp.path());
        let ctx = workspace::find_workspace_root(tmp.path()).unwrap();
        // apps/api has no jarvy.toml — should warn, exit 0.
        let exit = validate(&ctx, "pretty");
        assert_eq!(exit, 0);
    }

    /// Review P0 #3 — `members = ["../../etc"]` must NOT let
    /// validate / list / show probe arbitrary filesystem paths.
    #[test]
    fn resolve_member_refuses_path_traversal() {
        let root = Path::new("/repo");
        assert!(resolve_member(root, "../../etc").is_none());
        assert!(resolve_member(root, "/etc").is_none());
        assert!(resolve_member(root, "apps/../../../etc").is_none());
        assert!(resolve_member(root, "apps/web").is_some());
        assert!(resolve_member(root, "./apps/web").is_some());
    }

    #[test]
    fn validate_refuses_traversal_members_with_error() {
        let tmp = tempdir().unwrap();
        fs::write(
            tmp.path().join("jarvy.toml"),
            r#"
[workspace]
members = ["apps/web", "../../etc"]
"#,
        )
        .unwrap();
        fs::create_dir_all(tmp.path().join("apps/web")).unwrap();
        let ctx = workspace::find_workspace_root(tmp.path()).unwrap();
        // Hostile entry → validate exits CONFIG_ERROR.
        let exit = validate(&ctx, "pretty");
        assert_eq!(exit, crate::error_codes::CONFIG_ERROR);
    }

    /// Review P0 #4 — empty `inherit = []` is treated as
    /// `["provisioner"]` by both CLI display and production setup
    /// (same `effective_inherit()` helper).
    #[test]
    fn empty_inherit_widens_to_provisioner_via_helper() {
        let cfg = workspace::WorkspaceConfig {
            members: vec!["apps/web".to_string()],
            exclude: vec![],
            inherit: vec![],
        };
        assert_eq!(cfg.effective_inherit(), vec!["provisioner".to_string()]);
    }

    #[test]
    fn explicit_inherit_list_is_preserved() {
        let cfg = workspace::WorkspaceConfig {
            members: vec!["apps/web".to_string()],
            exclude: vec![],
            inherit: vec!["hooks".to_string(), "env".to_string()],
        };
        assert_eq!(
            cfg.effective_inherit(),
            vec!["hooks".to_string(), "env".to_string()]
        );
    }

    #[test]
    fn validate_returns_error_when_member_dir_missing() {
        let tmp = tempdir().unwrap();
        setup_workspace(tmp.path());
        // Add a bogus member that doesn't exist on disk.
        let new_toml = r#"
[workspace]
members = ["apps/web", "apps/api", "apps/ghost"]

[provisioner]
git = "latest"
"#;
        fs::write(tmp.path().join("jarvy.toml"), new_toml).unwrap();
        let ctx = workspace::find_workspace_root(tmp.path()).unwrap();
        let exit = validate(&ctx, "pretty");
        assert_eq!(exit, crate::error_codes::CONFIG_ERROR);
    }
}