mars-agents 0.1.21

Agent package manager for .agents/ directories
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
use assert_cmd::Command;
use assert_cmd::cargo::cargo_bin;
use httpmock::prelude::*;
use serde_json::{Value, json};
use serial_test::serial;
use std::collections::BTreeSet;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command as StdCommand, Output};
use std::thread;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tempfile::{TempDir, tempdir};

const API_PATH: &str = "/api.json";

fn now_unix_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
}

fn fresh_fetched_at() -> String {
    now_unix_secs().saturating_sub(60).to_string()
}

fn stale_fetched_at() -> String {
    now_unix_secs().saturating_sub(25 * 3600).to_string()
}

fn sample_catalog_json() -> Value {
    json!({
        "anthropic": {
            "models": {
                "claude-opus-4-6": {
                    "id": "claude-opus-4-6",
                    "name": "Claude Opus 4.6",
                    "release_date": "2026-02-05",
                    "limit": {
                        "context": 1000000,
                        "output": 128000
                    }
                }
            }
        },
        "openai": {
            "models": {
                "gpt-5": {
                    "id": "gpt-5",
                    "name": "GPT-5",
                    "release_date": "2025-06-01",
                    "limit": {
                        "context": 400000,
                        "output": 128000
                    }
                }
            }
        }
    })
}

fn sample_cached_models() -> Vec<Value> {
    vec![
        json!({
            "id": "claude-opus-4-6",
            "provider": "Anthropic",
            "release_date": "2026-02-05"
        }),
        json!({
            "id": "gpt-5",
            "provider": "OpenAI",
            "release_date": "2025-06-01"
        }),
    ]
}

fn cache_path(project_root: &Path) -> PathBuf {
    project_root.join(".mars").join("models-cache.json")
}

fn models_merged_path(project_root: &Path) -> PathBuf {
    project_root.join(".mars").join("models-merged.json")
}

fn write_local_source_with_model_alias(
    temp_root: &Path,
    source_dir_name: &str,
    alias_name: &str,
    model_id: &str,
) -> PathBuf {
    let source_root = temp_root.join(source_dir_name);
    let agents_dir = source_root.join("agents");
    fs::create_dir_all(&agents_dir).expect("failed to create local source agents dir");
    fs::write(
        agents_dir.join("fixture.md"),
        "# Fixture agent for models-cache tests\n",
    )
    .expect("failed to write local source fixture agent");

    let source_manifest = format!(
        r#"[package]
name = "{source_dir_name}"
version = "0.1.0"

[models."{alias_name}"]
harness = "codex"
model = "{model_id}"
description = "fixture alias for models cache tests"
"#
    );
    fs::write(source_root.join("mars.toml"), source_manifest)
        .expect("failed to write local source mars.toml");
    source_root
}

fn resolved_model_ids_from_models_list_json(stdout: &[u8]) -> BTreeSet<String> {
    let payload: Value =
        serde_json::from_slice(stdout).expect("models list --json must be valid JSON");
    payload["aliases"]
        .as_array()
        .expect("models list JSON should include aliases array")
        .iter()
        .filter_map(|alias| {
            alias["resolved_model"]
                .as_str()
                .or_else(|| alias["model_id"].as_str())
                .map(ToOwned::to_owned)
        })
        .collect()
}

fn write_cache(project_root: &Path, models: Vec<Value>, fetched_at: &str) {
    let mars_dir = project_root.join(".mars");
    fs::create_dir_all(&mars_dir).expect("failed to create .mars directory");
    let cache = json!({
        "models": models,
        "fetched_at": fetched_at,
    });
    fs::write(
        cache_path(project_root),
        serde_json::to_vec_pretty(&cache).expect("failed to serialize cache fixture"),
    )
    .expect("failed to write cache fixture");
}

fn read_cache_json(project_root: &Path) -> Value {
    let raw = fs::read_to_string(cache_path(project_root)).expect("failed to read cache file");
    serde_json::from_str(&raw).expect("failed to parse cache file JSON")
}

fn read_cache_raw(project_root: &Path) -> String {
    fs::read_to_string(cache_path(project_root)).expect("failed to read cache file")
}

fn configure_assert_cmd(cmd: &mut Command, temp_root: &Path, api_url: &str) {
    let home = temp_root.join("home");
    let xdg_config = temp_root.join("xdg-config");
    let xdg_cache = temp_root.join("xdg-cache");
    let xdg_data = temp_root.join("xdg-data");

    for dir in [&home, &xdg_config, &xdg_cache, &xdg_data] {
        fs::create_dir_all(dir).expect("failed to create isolated env directory");
    }

    cmd.env("MARS_MODELS_API_URL", api_url)
        .env("HOME", &home)
        .env("XDG_CONFIG_HOME", &xdg_config)
        .env("XDG_CACHE_HOME", &xdg_cache)
        .env("XDG_DATA_HOME", &xdg_data)
        .env("NO_COLOR", "1")
        .env_remove("MARS_CACHE_DIR")
        .env_remove("MARS_OFFLINE");
}

fn configure_std_cmd(cmd: &mut StdCommand, temp_root: &Path, api_url: &str) {
    let home = temp_root.join("home");
    let xdg_config = temp_root.join("xdg-config");
    let xdg_cache = temp_root.join("xdg-cache");
    let xdg_data = temp_root.join("xdg-data");

    for dir in [&home, &xdg_config, &xdg_cache, &xdg_data] {
        fs::create_dir_all(dir).expect("failed to create isolated env directory");
    }

    cmd.env("MARS_MODELS_API_URL", api_url)
        .env("HOME", &home)
        .env("XDG_CONFIG_HOME", &xdg_config)
        .env("XDG_CACHE_HOME", &xdg_cache)
        .env("XDG_DATA_HOME", &xdg_data)
        .env("NO_COLOR", "1")
        .env_remove("MARS_CACHE_DIR")
        .env_remove("MARS_OFFLINE");
}

fn mars_cmd(project_root: &Path, temp_root: &Path, api_url: &str) -> Command {
    let mut cmd = Command::cargo_bin("mars").expect("failed to locate mars test binary");
    configure_assert_cmd(&mut cmd, temp_root, api_url);
    cmd.arg("--root").arg(project_root);
    cmd
}

fn init_project(project_root: &Path, temp_root: &Path, api_url: &str) {
    fs::create_dir_all(project_root).expect("failed to create project root");

    let mut cmd = mars_cmd(project_root, temp_root, api_url);
    cmd.arg("init");
    cmd.assert().success();
}

fn setup_project(server: &MockServer) -> (TempDir, PathBuf) {
    let temp = tempdir().expect("failed to create temp dir");
    let project_root = temp.path().join("project");
    init_project(&project_root, temp.path(), &server.url(API_PATH));
    (temp, project_root)
}

#[test]
#[serial]
fn scenario_a_cold_cache_refreshes_on_models_list() {
    let server = MockServer::start();
    let mock = server.mock(|when, then| {
        when.method(GET).path(API_PATH);
        then.status(200).json_body(sample_catalog_json());
    });

    let (temp, project_root) = setup_project(&server);

    let mut cmd = mars_cmd(&project_root, temp.path(), &server.url(API_PATH));
    cmd.args(["--json", "models", "list"]);

    let output = cmd.assert().success().get_output().clone();
    let stdout: Value =
        serde_json::from_slice(&output.stdout).expect("models list --json should return JSON");

    assert!(
        stdout["aliases"].is_array(),
        "expected aliases array in JSON"
    );

    let cache = read_cache_json(&project_root);
    assert!(
        cache["models"]
            .as_array()
            .expect("cache.models should be an array")
            .len()
            >= 2,
        "expected non-empty models cache"
    );
    assert!(
        cache["fetched_at"].as_str().is_some(),
        "expected fetched_at timestamp"
    );
    assert_eq!(mock.hits(), 1, "expected one fetch for cold cache");
}

#[test]
#[serial]
fn scenario_b_fresh_cache_skips_fetch() {
    let server = MockServer::start();
    let mock = server.mock(|when, then| {
        when.method(GET).path(API_PATH);
        then.status(500).body("server error");
    });

    let (temp, project_root) = setup_project(&server);
    write_cache(&project_root, sample_cached_models(), &fresh_fetched_at());
    let before = read_cache_raw(&project_root);

    let mut cmd = mars_cmd(&project_root, temp.path(), &server.url(API_PATH));
    cmd.args(["models", "list", "--all"]);
    let output = cmd.assert().success().get_output().clone();
    let stdout = String::from_utf8(output.stdout).expect("stdout should be utf-8");
    assert!(
        stdout.contains("gpt-5"),
        "expected cached model id in list output:\n{stdout}"
    );

    let after = read_cache_raw(&project_root);
    assert_eq!(before, after, "fresh cache should stay unchanged");
    assert_eq!(mock.hits(), 0, "fresh cache should skip network fetch");
}

#[test]
#[serial]
fn scenario_c_stale_cache_falls_back_on_fetch_failure() {
    let server = MockServer::start();
    let mock = server.mock(|when, then| {
        when.method(GET).path(API_PATH);
        then.status(500).body("server error");
    });

    let (temp, project_root) = setup_project(&server);
    write_cache(&project_root, sample_cached_models(), &stale_fetched_at());
    let before = read_cache_raw(&project_root);

    let mut cmd = mars_cmd(&project_root, temp.path(), &server.url(API_PATH));
    cmd.args(["models", "list", "--all"]);

    let output = cmd.assert().success().get_output().clone();
    let stdout = String::from_utf8(output.stdout).expect("stdout should be utf-8");
    let stderr = String::from_utf8(output.stderr).expect("stderr should be utf-8");
    assert!(
        stderr.contains("models cache refresh failed") && stderr.contains("stale cache"),
        "expected stale cache warning, stderr:\n{stderr}"
    );
    assert!(
        stdout.contains("gpt-5"),
        "expected cached model id in list output:\n{stdout}"
    );

    let after = read_cache_raw(&project_root);
    assert_eq!(before, after, "stale fallback must not rewrite cache");
    assert_eq!(mock.hits(), 1, "stale cache should attempt one refresh");
}

#[test]
#[serial]
fn scenario_d_empty_cache_offline_errors_cleanly() {
    let server = MockServer::start();
    let mock = server.mock(|when, then| {
        when.method(GET).path(API_PATH);
        then.status(200).json_body(sample_catalog_json());
    });
    let (temp, project_root) = setup_project(&server);

    let mut cmd = mars_cmd(&project_root, temp.path(), &server.url(API_PATH));
    cmd.env("MARS_OFFLINE", "1");
    cmd.args(["models", "resolve", "opus"]);

    let output = cmd.assert().code(3).get_output().clone();
    let stderr = String::from_utf8(output.stderr).expect("stderr should be utf-8");

    assert!(
        stderr.contains("MARS_OFFLINE"),
        "expected MARS_OFFLINE mention in stderr:\n{stderr}"
    );
    assert!(
        stderr.contains("mars models refresh"),
        "expected refresh hint in stderr:\n{stderr}"
    );
    assert_eq!(
        mock.hits(),
        0,
        "offline resolve should not hit models endpoint"
    );
    assert!(
        !cache_path(&project_root).exists(),
        "offline resolve with empty cache should not create cache file"
    );
}

#[test]
#[serial]
fn scenario_e_no_refresh_models_flag_matches_offline_behavior() {
    let server = MockServer::start();
    let mock = server.mock(|when, then| {
        when.method(GET).path(API_PATH);
        then.status(200).json_body(sample_catalog_json());
    });
    let (temp, project_root) = setup_project(&server);

    let mut cmd = mars_cmd(&project_root, temp.path(), &server.url(API_PATH));
    cmd.args(["models", "resolve", "opus", "--no-refresh-models"]);

    let output = cmd.assert().code(3).get_output().clone();
    let stderr = String::from_utf8(output.stderr).expect("stderr should be utf-8");

    assert!(
        stderr.contains("--no-refresh-models"),
        "expected --no-refresh-models mention in stderr:\n{stderr}"
    );
    assert!(
        stderr.contains("mars models refresh"),
        "expected refresh hint in stderr:\n{stderr}"
    );
    assert_eq!(
        mock.hits(),
        0,
        "no-refresh flag should not hit models endpoint when cache is missing"
    );
    assert!(
        !cache_path(&project_root).exists(),
        "--no-refresh-models with empty cache should not create cache file"
    );
}

#[test]
#[serial]
fn scenario_f_add_sync_force_and_resolve_dependency_alias() {
    let server = MockServer::start();
    let mock = server.mock(|when, then| {
        when.method(GET).path(API_PATH);
        then.status(200).json_body(sample_catalog_json());
    });

    let (temp, project_root) = setup_project(&server);
    let source_root = write_local_source_with_model_alias(
        temp.path(),
        "alias-source-force-sync",
        "test-alias",
        "openai/gpt-5",
    );

    let mut add_cmd = mars_cmd(&project_root, temp.path(), &server.url(API_PATH));
    add_cmd.arg("add").arg(source_root.as_os_str());
    add_cmd.assert().success();

    let mut cmd = mars_cmd(&project_root, temp.path(), &server.url(API_PATH));
    cmd.args(["sync", "--force"]);
    cmd.assert().success();

    let mut resolve_cmd = mars_cmd(&project_root, temp.path(), &server.url(API_PATH));
    resolve_cmd.args(["--json", "models", "resolve", "test-alias"]);
    let resolve_output = resolve_cmd.assert().success().get_output().clone();
    let resolve_json: Value =
        serde_json::from_slice(&resolve_output.stdout).expect("resolve --json should return JSON");
    assert_eq!(
        resolve_json["resolved_model"].as_str(),
        Some("openai/gpt-5"),
        "expected dependency alias to resolve to pinned model"
    );

    let cache = read_cache_json(&project_root);
    assert!(
        cache["models"]
            .as_array()
            .expect("cache.models should be an array")
            .len()
            >= 2,
        "expected sync to populate models cache"
    );
    assert!(
        cache["fetched_at"].as_str().is_some(),
        "expected fetched_at to be set after sync"
    );
    assert!(
        models_merged_path(&project_root).exists(),
        "expected models-merged.json to be written during sync"
    );
    let merged: Value = serde_json::from_str(
        &fs::read_to_string(models_merged_path(&project_root))
            .expect("failed to read models-merged.json"),
    )
    .expect("failed to parse models-merged.json");
    assert!(
        merged.get("test-alias").is_some(),
        "expected dependency alias in models-merged.json"
    );
    assert_eq!(
        mock.hits(),
        1,
        "expected add+sync+resolve flow to fetch models catalog once"
    );
}

#[test]
#[serial]
fn scenario_g_offline_sync_succeeds_without_cache_and_emits_diag() {
    let server = MockServer::start();
    let mock = server.mock(|when, then| {
        when.method(GET).path(API_PATH);
        then.status(200).json_body(sample_catalog_json());
    });
    let (temp, project_root) = setup_project(&server);

    let mut cmd = mars_cmd(&project_root, temp.path(), &server.url(API_PATH));
    cmd.env("MARS_OFFLINE", "1");
    cmd.args(["--json", "sync", "--force"]);

    let output = cmd.assert().success().get_output().clone();
    let stdout: Value =
        serde_json::from_slice(&output.stdout).expect("sync --json should return JSON");

    let diagnostics = stdout["diagnostics"]
        .as_array()
        .expect("sync JSON should include diagnostics array");
    assert!(
        diagnostics
            .iter()
            .any(|d| d["code"].as_str() == Some("models-cache-refresh")),
        "expected models-cache-refresh warning in diagnostics"
    );
    assert!(
        !cache_path(&project_root).exists(),
        "offline sync with empty cache should not create cache file"
    );
    assert!(
        models_merged_path(&project_root).exists(),
        "offline sync should still write models-merged.json"
    );
    assert_eq!(
        mock.hits(),
        0,
        "offline sync should not hit models endpoint"
    );
}

#[test]
#[serial]
fn scenario_h_add_immediately_resolve_alias_without_explicit_sync() {
    let server = MockServer::start();
    let mock = server.mock(|when, then| {
        when.method(GET).path(API_PATH);
        then.status(200).json_body(sample_catalog_json());
    });

    let (temp, project_root) = setup_project(&server);
    let source_root = write_local_source_with_model_alias(
        temp.path(),
        "alias-source-immediate",
        "test-alias-immediate",
        "openai/gpt-5",
    );

    let mut add_cmd = mars_cmd(&project_root, temp.path(), &server.url(API_PATH));
    add_cmd.arg("add").arg(source_root.as_os_str());
    add_cmd.assert().success();

    let mut resolve_cmd = mars_cmd(&project_root, temp.path(), &server.url(API_PATH));
    resolve_cmd.args(["models", "resolve", "test-alias-immediate"]);
    let resolve_output = resolve_cmd.assert().success().get_output().clone();
    let resolve_stdout =
        String::from_utf8(resolve_output.stdout).expect("resolve stdout should be utf-8");
    assert!(
        resolve_stdout.contains("openai/gpt-5"),
        "expected resolved pinned model in resolve output:\n{resolve_stdout}"
    );
    assert!(
        models_merged_path(&project_root).exists(),
        "expected models-merged.json after add-triggered sync"
    );
    assert_eq!(
        mock.hits(),
        1,
        "expected add+immediate resolve online flow to fetch models catalog once"
    );
}

#[test]
#[serial]
fn scenario_i_concurrent_processes_fetch_once() {
    let server = MockServer::start();
    let mock = server.mock(|when, then| {
        when.method(GET).path(API_PATH);
        then.status(200)
            .delay(Duration::from_millis(500))
            .json_body(sample_catalog_json());
    });

    let (temp, project_root) = setup_project(&server);
    let bin_path = cargo_bin("mars");
    let api_url = server.url(API_PATH);

    let handles: Vec<_> = (0..4)
        .map(|_| {
            let bin_path = bin_path.clone();
            let env_root = temp.path().to_path_buf();
            let root = project_root.clone();
            let api_url = api_url.clone();

            thread::spawn(move || {
                let mut cmd = StdCommand::new(&bin_path);
                configure_std_cmd(&mut cmd, &env_root, &api_url);
                cmd.arg("--root")
                    .arg(root)
                    .arg("--json")
                    .arg("models")
                    .arg("list")
                    .arg("--unavailable")
                    .output()
                    .expect("failed to execute concurrent mars models list")
            })
        })
        .collect();

    let outputs: Vec<Output> = handles
        .into_iter()
        .map(|h| h.join().expect("concurrent worker thread panicked"))
        .collect();

    let expected_catalog_ids: BTreeSet<String> =
        vec!["claude-opus-4-6".to_string(), "gpt-5".to_string()]
            .into_iter()
            .collect();
    let mut baseline_model_ids: Option<BTreeSet<String>> = None;

    for output in outputs {
        assert!(
            output.status.success(),
            "expected success, stderr:\n{}",
            String::from_utf8_lossy(&output.stderr)
        );
        let model_ids = resolved_model_ids_from_models_list_json(&output.stdout);
        let catalog_ids_seen: BTreeSet<String> = model_ids
            .intersection(&expected_catalog_ids)
            .cloned()
            .collect();
        assert!(
            catalog_ids_seen == expected_catalog_ids,
            "expected each process to resolve the same stub catalog ids; got {catalog_ids_seen:?} from {model_ids:?}"
        );
        if let Some(baseline) = &baseline_model_ids {
            assert_eq!(
                model_ids, *baseline,
                "expected concurrent runs to produce identical resolved model sets"
            );
        } else {
            baseline_model_ids = Some(model_ids);
        }
    }

    assert_eq!(
        mock.hits(),
        1,
        "expected exactly one fetch across concurrent processes"
    );
}

#[test]
#[serial]
fn scenario_j_ttl_zero_always_refreshes() {
    let server = MockServer::start();
    let mock = server.mock(|when, then| {
        when.method(GET).path(API_PATH);
        then.status(200).json_body(sample_catalog_json());
    });

    let (temp, project_root) = setup_project(&server);

    fs::write(
        project_root.join("mars.toml"),
        "[settings]\nmodels_cache_ttl_hours = 0\n",
    )
    .expect("failed to write mars.toml with ttl=0");

    let stale_but_recent = fresh_fetched_at();
    write_cache(
        &project_root,
        sample_cached_models(),
        stale_but_recent.as_str(),
    );

    let mut cmd = mars_cmd(&project_root, temp.path(), &server.url(API_PATH));
    cmd.args(["models", "list"]);
    cmd.assert().success();

    let cache = read_cache_json(&project_root);
    let updated_fetched_at = cache["fetched_at"]
        .as_str()
        .expect("fetched_at should be present after refresh");
    assert_ne!(
        updated_fetched_at, stale_but_recent,
        "ttl=0 should force refresh even with fresh cache"
    );
    assert_eq!(mock.hits(), 1, "ttl=0 should force one network fetch");
}

#[test]
#[serial]
fn resolve_alias_prefix_exits_zero() {
    let server = MockServer::start();
    let (temp, project_root) = setup_project(&server);
    write_cache(&project_root, sample_cached_models(), &fresh_fetched_at());

    let mut cmd = mars_cmd(&project_root, temp.path(), &server.url(API_PATH));
    cmd.args(["--json", "models", "resolve", "opus-4-6"]);

    let output = cmd.assert().success().get_output().clone();
    let stdout: Value =
        serde_json::from_slice(&output.stdout).expect("resolve --json should return JSON");

    assert_eq!(stdout["source"].as_str(), Some("alias_prefix"));
    assert_eq!(stdout["name"].as_str(), Some("opus-4-6"));
    assert_eq!(stdout["resolved_model"].as_str(), Some("claude-opus-4-6"));
}

#[test]
#[serial]
fn resolve_unknown_exits_zero_with_passthrough() {
    let server = MockServer::start();
    let (temp, project_root) = setup_project(&server);
    write_cache(&project_root, sample_cached_models(), &fresh_fetched_at());

    let mut cmd = mars_cmd(&project_root, temp.path(), &server.url(API_PATH));
    cmd.args(["--json", "models", "resolve", "unknown-xyz"]);

    let output = cmd.assert().success().get_output().clone();
    let stdout: Value =
        serde_json::from_slice(&output.stdout).expect("resolve --json should return JSON");

    assert_eq!(stdout["source"].as_str(), Some("passthrough"));
    assert_eq!(stdout["model_id"].as_str(), Some("unknown-xyz"));
    assert_eq!(stdout["resolved_model"].as_str(), Some("unknown-xyz"));
    assert_eq!(stdout["provider"], Value::Null);
    assert_eq!(stdout["harness"], Value::Null);
    assert_eq!(stdout["harness_source"].as_str(), Some("unavailable"));
    assert_eq!(stdout["harness_candidates"], json!([]));
    assert!(stdout["availability"].is_string());
    assert!(stdout["availability_source"].is_string());
    assert!(
        stdout["runnable_paths"].is_array(),
        "passthrough JSON should include availability runnable paths"
    );
    assert!(
        stdout["warning"]
            .as_str()
            .expect("passthrough warning should be present")
            .contains("passing through to harness")
    );
}

#[test]
#[serial]
fn models_list_visibility_include_does_not_add_catalog_rows() {
    let server = MockServer::start();
    let (temp, project_root) = setup_project(&server);
    fs::write(
        project_root.join("mars.toml"),
        r#"[settings]

[settings.model_visibility]
include = ["catalog-only-*"]
"#,
    )
    .expect("failed to write mars.toml with model visibility");
    write_cache(
        &project_root,
        vec![json!({
            "id": "catalog-only-model",
            "provider": "OpenAI",
            "release_date": "2026-01-01"
        })],
        &fresh_fetched_at(),
    );

    let mut cmd = mars_cmd(&project_root, temp.path(), &server.url(API_PATH));
    cmd.args(["--json", "models", "list"]);

    let output = cmd.assert().success().get_output().clone();
    let stdout: Value =
        serde_json::from_slice(&output.stdout).expect("models list --json should return JSON");

    let aliases = stdout["aliases"]
        .as_array()
        .expect("models list JSON should include aliases");
    assert!(
        aliases.is_empty(),
        "default models list should not expand visibility includes into catalog rows"
    );
}

#[test]
#[serial]
fn resolve_prefix_no_match_exits_zero_with_passthrough() {
    let server = MockServer::start();
    let (temp, project_root) = setup_project(&server);
    write_cache(&project_root, sample_cached_models(), &fresh_fetched_at());

    let mut cmd = mars_cmd(&project_root, temp.path(), &server.url(API_PATH));
    cmd.args(["--json", "models", "resolve", "opus-9-9"]);

    let output = cmd.assert().success().get_output().clone();
    let stdout: Value =
        serde_json::from_slice(&output.stdout).expect("resolve --json should return JSON");

    assert_eq!(stdout["source"].as_str(), Some("passthrough"));
    assert_eq!(stdout["resolved_model"].as_str(), Some("opus-9-9"));
}

#[test]
#[serial]
fn resolve_passthrough_pattern_guesses_harness() {
    let server = MockServer::start();
    let (temp, project_root) = setup_project(&server);
    write_cache(&project_root, sample_cached_models(), &fresh_fetched_at());

    let mut cmd = mars_cmd(&project_root, temp.path(), &server.url(API_PATH));
    cmd.args(["--json", "models", "resolve", "claude-brand-new"]);

    let output = cmd.assert().success().get_output().clone();
    let stdout: Value =
        serde_json::from_slice(&output.stdout).expect("resolve --json should return JSON");

    let expected_harness = ["claude", "opencode", "gemini"]
        .iter()
        .find(|bin| which::which(bin).is_ok())
        .map(|bin| (*bin).to_string());
    let expected_source = if expected_harness.is_some() {
        "pattern_guess"
    } else {
        "unavailable"
    };

    assert_eq!(stdout["source"].as_str(), Some("passthrough"));
    assert_eq!(stdout["provider"].as_str(), Some("anthropic"));
    assert_eq!(
        stdout["harness_candidates"],
        json!(["claude", "opencode", "gemini"])
    );
    assert_eq!(stdout["harness_source"].as_str(), Some(expected_source));
    assert_eq!(stdout["harness"].as_str(), expected_harness.as_deref());
}

#[test]
#[serial]
fn resolve_passthrough_unrecognized_pattern_harness_null() {
    let server = MockServer::start();
    let (temp, project_root) = setup_project(&server);
    write_cache(&project_root, sample_cached_models(), &fresh_fetched_at());

    let mut cmd = mars_cmd(&project_root, temp.path(), &server.url(API_PATH));
    cmd.args(["--json", "models", "resolve", "xyz-unknown"]);

    let output = cmd.assert().success().get_output().clone();
    let stdout: Value =
        serde_json::from_slice(&output.stdout).expect("resolve --json should return JSON");

    assert_eq!(stdout["source"].as_str(), Some("passthrough"));
    assert_eq!(stdout["provider"], Value::Null);
    assert_eq!(stdout["harness"], Value::Null);
    assert_eq!(stdout["harness_source"].as_str(), Some("unavailable"));
    assert_eq!(stdout["harness_candidates"], json!([]));
}

#[test]
#[serial]
fn resolve_unknown_with_no_refresh_without_cache_is_non_zero() {
    let server = MockServer::start();
    let (temp, project_root) = setup_project(&server);

    let mut cmd = mars_cmd(&project_root, temp.path(), &server.url(API_PATH));
    cmd.args(["models", "resolve", "unknown-xyz", "--no-refresh-models"]);

    let output = cmd.assert().code(3).get_output().clone();
    let stderr = String::from_utf8(output.stderr).expect("stderr should be utf-8");
    assert!(
        stderr.contains("--no-refresh-models"),
        "expected no-refresh cache error, stderr:\n{stderr}"
    );
}