turbospark-server 0.3.0

OpenAI Chat Completions and Anthropic Messages server on loopback: request/response envelopes, SSE streaming framing, and the axum router, wired to the raw-completion loop.
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
use std::path::PathBuf;

use super::args::{parse_model_args, short_circuit, BindMode, ModelArgs};
use super::bind::tailnet_host;
use super::resolve_api_key;

fn parse(argv: &[&str]) -> Result<Option<ModelArgs>, String> {
    let owned: Vec<String> = argv.iter().map(|s| s.to_string()).collect();
    parse_model_args(&owned)
}

#[test]
fn legacy_positional_mode_is_left_alone() {
    assert!(parse(&["/tmp/tok", "9000"]).unwrap().is_none());
}

/// The parser reads only `--api-key`, never `$TURBOSPARK_API_KEY` -- the env
/// fallback is `main`'s job, applied once after parsing, so a test asserting
/// what a given argv parses to is not at the mercy of whatever the test
/// process's own environment happens to carry.
#[test]
fn api_key_defaults_to_absent_and_reads_the_flag_value() {
    let d = parse(&["--model", "/tmp/m"]).unwrap().unwrap();
    assert_eq!(d.api_key, None);

    let o = parse(&["--model", "/tmp/m", "--api-key", "sk-test-123"])
        .unwrap()
        .unwrap();
    assert_eq!(o.api_key.as_deref(), Some("sk-test-123"));
}

#[test]
fn an_empty_api_key_is_refused() {
    let err = parse(&["--model", "/tmp/m", "--api-key", ""]).unwrap_err();
    assert!(err.contains("--api-key"), "{err}");
}

#[test]
fn tailnet_requires_an_api_key_before_opening_the_model() {
    let err = resolve_api_key(BindMode::Tailnet, None, None).unwrap_err();
    assert!(err.contains("--bind tailnet requires --api-key"), "{err}");
    assert_eq!(
        resolve_api_key(BindMode::Tailnet, Some("flag-key".into()), None).unwrap(),
        Some("flag-key".into())
    );
    assert_eq!(
        resolve_api_key(BindMode::Tailnet, None, Some("env-key".into())).unwrap(),
        Some("env-key".into())
    );
    assert!(resolve_api_key(BindMode::Tailnet, None, Some(String::new())).is_err());
}

#[test]
fn loopback_keeps_optional_auth_and_flag_precedence() {
    assert_eq!(
        resolve_api_key(BindMode::Loopback, None, None).unwrap(),
        None
    );
    assert_eq!(
        resolve_api_key(
            BindMode::Loopback,
            Some("flag-key".into()),
            Some("env-key".into())
        )
        .unwrap(),
        Some("flag-key".into())
    );
}

// --- vision sidecar (vision memory sidecar, Part A4) -----------------------

#[test]
fn vision_sidecar_defaults_to_none() {
    let d = parse(&["--model", "/tmp/m"]).unwrap().unwrap();
    assert_eq!(d.vision_sidecar, None);
}

/// The path stays an OPAQUE string here, exactly as `--steering`'s does:
/// this binary reads no directory itself, so a missing or malformed sidecar
/// is `RealChatModel::open`'s error to report, not a parse failure.
#[test]
fn a_vision_sidecar_path_is_not_validated_by_the_parser() {
    let d = parse(&[
        "--model",
        "/tmp/m",
        "--vision-sidecar",
        "/does/not/exist.gturbo-vision",
    ])
    .unwrap()
    .unwrap();
    assert_eq!(
        d.vision_sidecar.as_deref(),
        Some("/does/not/exist.gturbo-vision")
    );
}

/// `--model` reaches the catalog store, so one install serves this
/// binary and `turbospark-check` under one alias.
///
/// The assertion is deliberately on a name that is NOT a directory:
/// swapping `resolve_model_arg` back for `PathBuf::from` leaves every
/// path case passing, because for a real path the two agree. Only the
/// alias arm can tell them apart, and this is the cheapest form of it
/// -- the "default install location that happens to exist" arm, which
/// needs no `installed.json` and no model.
///
/// It is the only test in this binary that touches `TURBOSPARK_HOME`,
/// which is what keeps it safe under the default parallel test threads.
#[cfg(target_os = "macos")]
#[test]
fn an_alias_resolves_to_its_install_directory() {
    let root = std::env::temp_dir().join(format!(
        "turbospark-server-alias-{}-{}",
        std::process::id(),
        line!()
    ));
    let installed = root.join("models").join("some-alias.gturbo");
    std::fs::create_dir_all(&installed).unwrap();
    std::env::set_var("TURBOSPARK_HOME", &root);

    assert_eq!(
        catalog::resolve_model_arg("some-alias"),
        installed,
        "an alias should resolve to its install directory"
    );
    // The property the resolution order exists to protect: a bare name
    // that is also a real directory is that directory, never the alias.
    assert_ne!(
        catalog::resolve_model_arg("some-alias"),
        PathBuf::from("some-alias"),
        "resolution must not be a pass-through for a known alias"
    );

    std::env::remove_var("TURBOSPARK_HOME");
    let _ = std::fs::remove_dir_all(&root);
}

#[test]
fn power_flags_default_to_unset_and_parse_their_documented_values() {
    // Unset rather than `performance`: the Low Power Mode default is
    // resolved at model open, where the OS can be asked.
    let d = parse(&["--model", "/tmp/m"]).unwrap().unwrap();
    assert_eq!(d.power_profile, None);
    assert_eq!(d.max_tokens_per_sec, None);

    let o = parse(&[
        "--model",
        "/tmp/m",
        "--power-profile",
        "efficiency",
        "--max-tokens-per-sec",
        "7.5",
    ])
    .unwrap()
    .unwrap();
    assert_eq!(o.power_profile, Some(runtime::PowerProfile::Efficiency));
    assert_eq!(o.max_tokens_per_sec, Some(7.5));
}

#[test]
fn bad_power_flag_values_are_rejected() {
    assert!(parse(&["--model", "/tmp/m", "--power-profile", "turbo"]).is_err());
    for bad in ["0", "-1", "abc", "inf"] {
        assert!(
            parse(&["--model", "/tmp/m", "--max-tokens-per-sec", bad]).is_err(),
            "expected {bad} to be rejected"
        );
    }
}

#[test]
fn model_mode_defaults_and_overrides() {
    let d = parse(&["--model", "/tmp/m"]).unwrap().unwrap();
    // BOTH sized knobs default to `None`, i.e. `auto`: the slot count is
    // sized against this machine and this install and never drops below
    // the shipped 16, and the context window is sized against the
    // checkpoint's trained context and what memory holds.
    assert_eq!(
        (d.port, d.max_context, d.expert_cache_slots),
        (8080, None, None)
    );
    let o = parse(&[
        "--model",
        "/tmp/m",
        "--port",
        "9",
        "--max-context",
        "1024",
        "--expert-cache-slots",
        "32",
    ])
    .unwrap()
    .unwrap();
    assert_eq!(
        (o.port, o.max_context, o.expert_cache_slots),
        (9, Some(1024), Some(32))
    );
    // `auto` is accepted by name as well as by omission, and is the one
    // value the allowed-set check must not reject.
    let a = parse(&["--model", "/tmp/m", "--expert-cache-slots", "auto"])
        .unwrap()
        .unwrap();
    assert_eq!(a.expert_cache_slots, None);
    assert!(parse(&["--model", "/tmp/m", "--expert-cache-slots", "20"]).is_err());

    // The context window takes the same `auto`-or-a-number grammar, and
    // unlike the slot count it has no allowed set to check against: every
    // positive value is a legal KV allocation.
    let c = parse(&["--model", "/tmp/m", "--max-context", "auto"])
        .unwrap()
        .unwrap();
    assert_eq!(c.max_context, None);
    // Zero is refused rather than read as `auto`: a window of zero admits
    // no prompt, and the flag already has a spelling for "you decide".
    assert!(parse(&["--model", "/tmp/m", "--max-context", "0"]).is_err());
    assert!(parse(&["--model", "/tmp/m", "--max-context", "lots"]).is_err());
}

#[test]
fn repeated_model_flags_attach_distinct_installs_in_order() {
    let parsed = parse(&[
        "--model",
        "/tmp/alpha.gturbo",
        "--model",
        "/tmp/beta.gturbo",
    ])
    .unwrap()
    .unwrap();
    assert_eq!(parsed.model, "/tmp/alpha.gturbo");
    assert_eq!(parsed.models, vec!["/tmp/alpha.gturbo", "/tmp/beta.gturbo"]);
}

#[test]
fn a_multi_install_registry_cannot_also_request_a_same_install_pool() {
    let err = parse(&[
        "--model",
        "/tmp/alpha.gturbo",
        "--model",
        "/tmp/beta.gturbo",
        "--pool-size",
        "2",
    ])
    .unwrap_err();
    assert!(err.contains("multiple --model flags"), "{err}");
}

/// **A flag-led invocation must not fall through to the scripted mode.**
/// The mode test used to be `args[0] == "--model"`, so
/// `--port 8080 --model X` was read as a positional TOKENIZER DIRECTORY
/// named `--port` and died with a filesystem error about a path nobody
/// typed. Anything starting with `-` belongs to this parser.
#[test]
fn a_flag_in_any_position_stays_out_of_the_scripted_mode() {
    // Mis-ordered but complete: parsed, not mistaken for a directory.
    let ordered = parse(&["--port", "9", "--model", "/tmp/m"])
        .unwrap()
        .unwrap();
    assert_eq!((ordered.port, ordered.model.as_str()), (9, "/tmp/m"));
    // A misspelled flag gets the usage text rather than a tokenizer error.
    let err = parse(&["--modle", "/tmp/m"]).unwrap_err();
    assert!(err.contains("unknown option"), "{err}");
    // And a real positional path still reaches the scripted mode.
    assert!(parse(&["/tmp/tokenizer-dir"]).unwrap().is_none());
}

/// `--help` and `--version` are handled ahead of the flag loop, because
/// that loop advances two tokens per flag and would eat what follows.
/// Whichever is reached first in a left-to-right scan wins.
#[test]
fn help_and_version_short_circuit_before_anything_is_parsed() {
    assert!(short_circuit(&owned(&["--help"]))
        .unwrap()
        .contains("usage:"));
    assert!(short_circuit(&owned(&["-h"])).unwrap().contains("usage:"));
    // Reachable past other flags, and NOT consuming a value.
    assert!(short_circuit(&owned(&["--model", "/tmp/m", "--help"])).is_some());
    assert!(short_circuit(&owned(&["--model", "/tmp/m"])).is_none());
    assert!(short_circuit(&owned(&["/tmp/dir"])).is_none());
}

/// The version line matches `turbospark-check`'s to the character. The
/// two are produced independently (this binary reads `CARGO_PKG_VERSION`
/// directly rather than depending on the parser crate for one format
/// string), so nothing but this pins them together.
#[test]
fn the_version_line_matches_the_clis() {
    let ours = short_circuit(&owned(&["--version"])).unwrap();
    assert_eq!(ours, format!("turbospark {}\n", env!("CARGO_PKG_VERSION")));
    assert!(short_circuit(&owned(&["-V"])).unwrap() == ours);
}

fn owned(items: &[&str]) -> Vec<String> {
    items.iter().map(|s| s.to_string()).collect()
}

#[test]
fn bad_model_mode_arguments_are_rejected() {
    // A slot count outside the allowed set would panic the runtime
    // config setter, so it has to fail here instead.
    assert!(parse(&["--model", "/tmp/m", "--expert-cache-slots", "12"]).is_err());
    assert!(parse(&["--model", "/tmp/m", "--port", "70000"]).is_err());
    assert!(parse(&["--model"]).is_err());
    assert!(parse(&["--model", "/tmp/m", "--nope", "1"]).is_err());
    assert!(parse(&["--model", "/tmp/m", "--bind", "lan"]).is_err());
}

#[test]
fn bind_mode_defaults_to_loopback() {
    assert_eq!(
        parse(&["--model", "/tmp/m"]).unwrap().unwrap().bind,
        BindMode::Loopback
    );
    let t = parse(&["--model", "/tmp/m", "--bind", "tailnet"])
        .unwrap()
        .unwrap();
    assert_eq!(t.bind, BindMode::Tailnet);
    assert_eq!(BindMode::Loopback.host().unwrap(), "127.0.0.1");
}

#[test]
fn tailnet_host_accepts_exactly_one_in_range_address() {
    assert_eq!(tailnet_host("100.64.0.1\n").unwrap(), "100.64.0.1");
    assert_eq!(
        tailnet_host("100.127.255.254\n").unwrap(),
        "100.127.255.254"
    );
}

#[test]
fn tailnet_host_never_falls_back() {
    // Empty, ambiguous, out-of-range, IPv6, and malformed all fail rather
    // than widening to a loopback/LAN/wildcard bind.
    assert!(tailnet_host("").is_err());
    assert!(tailnet_host("  \n").is_err());
    assert!(tailnet_host("100.64.0.1 100.64.0.2\n").is_err());
    assert!(tailnet_host("100.63.0.1").is_err());
    assert!(tailnet_host("100.128.0.1").is_err());
    assert!(tailnet_host("192.168.1.5").is_err());
    assert!(tailnet_host("127.0.0.1").is_err());
    assert!(tailnet_host("0.0.0.0").is_err());
    assert!(tailnet_host("fd7a:115c:a1e0::1").is_err());
    assert!(tailnet_host("100.64.0").is_err());
    assert!(tailnet_host("100.64.0.256").is_err());
    assert!(tailnet_host("100.064.0.1").is_err());
    assert!(tailnet_host("100.64.0.1;rm -rf /").is_err());
}

/// The single-field error message used to slice at a raw byte offset
/// (`&only[..64]`), which panics if byte 64 is not a char boundary.
/// `"h"` plus thirty-two `"\u{00e9}"` (2 bytes each) puts the 32nd `\u{00e9}` at bytes
/// 63-64, so byte 64 sits mid-character.
#[test]
fn a_non_ascii_boundary_in_the_bad_field_does_not_panic() {
    let field = format!("h{}", "\u{00e9}".repeat(32));
    assert!(!field.is_char_boundary(64), "fixture must straddle byte 64");
    let err = tailnet_host(&field).unwrap_err();
    assert!(err.contains("not a Tailnet IPv4 address"), "{err}");
}

// --- directional steering (docs/OBLITERATION.md) --------------------------
//
// The CLI's half of these six flags is covered by `crates/invocation`'s parse
// tests. THIS parser is a second implementation of the same precedence rules
// against a different type, and until now none of the cases above touched it,
// so the two could drift with nothing to catch it. The order-dependence case
// below is the one no other file can cover at all: `crates/invocation`
// collects every flag before resolving anything, while this loop applies the
// layer range as it goes and has to repair it in two places.

#[test]
fn steering_defaults_to_off_and_reads_no_file() {
    let d = parse(&["--model", "/tmp/m"]).unwrap().unwrap();
    assert!(d.steering.vectors.is_empty());
    assert!(!d.steering.is_active());
    assert!(d.steering.primary().is_none());
}

/// A steering PARAMETER without `--steering` is refused rather than ignored.
/// Without a direction set the process serves every request unsteered, so the
/// flag would be a command line saying one thing while the server does
/// another -- on the one axis here that changes the TOKENS.
///
/// All five, because they reach the parsed policy by three different routes:
/// `--steering-mode` and `--steering-scale` are held aside, `--steering-target`
/// and `--steering-gate` are written straight into it, and
/// `--steering-layers` is held aside AND replayed.
#[test]
fn a_steering_parameter_without_a_vector_is_refused() {
    for (flag, value) in [
        ("--steering-mode", "renorm"),
        ("--steering-scale", "0.8"),
        ("--steering-layers", "30:40"),
        ("--steering-target", "2.5"),
        ("--steering-gate", "0.5"),
    ] {
        let err = parse(&["--model", "/tmp/m", flag, value])
            .expect_err(&format!("{flag} alone should be refused"));
        assert!(
            err.contains(flag) && err.contains("--steering"),
            "message should name the flag and what it needs: {err}"
        );
    }
}

/// The rejection has to be SPELLED from the accepted set. This message named
/// three modes for a release after `renorm` landed, so a caller who misspelled
/// the fourth was told it did not exist.
///
/// TWO ASSERTIONS, because the first one alone is SELF-REFERENTIAL and was
/// measured to be: the message is built from `STEERING_MODE_NAMES`, so
/// iterating that same list only proves the message was not hand-written, and
/// shortening the list leaves this green (checked -- it is `crates/core`'s
/// `the_mode_names_are_exactly_what_parse_accepts` that reddens there). The
/// literal is what pins the regression that actually happened, and the loop
/// is what pins the mechanism that prevents it recurring. Neither replaces the
/// other.
#[test]
fn an_unknown_steering_mode_names_every_mode_it_accepts() {
    let err = parse(&["--model", "/tmp/m", "--steering-mode", "renrom"])
        .expect_err("a misspelled mode should be refused");
    assert!(
        err.contains("renorm"),
        "the fourth mode is the one this message lost once, and reads: {err}"
    );
    for name in foundation::STEERING_MODE_NAMES {
        assert!(
            err.contains(name),
            "the rejection should name {name}, and reads: {err}"
        );
    }
}

#[cfg(target_os = "macos")]
fn write_vector(tag: &str, layers: usize, mode: Option<foundation::SteeringMode>) -> PathBuf {
    let dir = std::env::temp_dir().join(format!(
        "turbospark-server-steer-{}-{tag}",
        std::process::id()
    ));
    std::fs::create_dir_all(&dir).unwrap();
    let path = dir.join("v.gguf");
    // Blocks 1..=layers: `direction.0` has no name in this format, so a
    // control vector cannot carry an edit for block 0.
    let dirs: std::collections::BTreeMap<usize, Vec<f32>> = (1..=layers)
        .map(|l| (l, (0..8).map(|i| (l * 8 + i) as f32 * 0.125).collect()))
        .collect();
    std::fs::write(
        &path,
        repack::control_vector::write_control_vector(&dirs, "qwen35", mode).unwrap(),
    )
    .unwrap();
    path
}

/// Precedence, stated the same way `crates/cli`'s `resolve_steering` states
/// it: the flag wins over the file's declared mode, the file's over the
/// default. A set present with no `--steering-scale` means FULL strength, not
/// the zero `SteeringPolicy::off()` carries -- that last one is the trap,
/// since inheriting the default would load a vector and apply the identity.
#[cfg(target_os = "macos")]
#[test]
fn the_mode_comes_from_the_flag_then_the_file_then_the_default() {
    let declared = write_vector("declared", 4, Some(foundation::SteeringMode::Renorm));
    let bare = write_vector("bare", 4, None);
    let p = |args: &[&str]| parse(args).unwrap().unwrap().steering;

    let from_file = p(&[
        "--model",
        "/tmp/m",
        "--steering",
        declared.to_str().unwrap(),
    ]);
    let file_vector = from_file.primary().expect("a vector was given");
    assert_eq!(file_vector.mode, foundation::SteeringMode::Renorm);
    assert_eq!(
        file_vector.alpha, 1.0,
        "a loaded vector means full strength"
    );

    let from_flag = p(&[
        "--model",
        "/tmp/m",
        "--steering",
        declared.to_str().unwrap(),
        "--steering-mode",
        "add",
    ]);
    assert_eq!(
        from_flag.primary().expect("a vector was given").mode,
        foundation::SteeringMode::Add
    );

    let defaulted = p(&["--model", "/tmp/m", "--steering", bare.to_str().unwrap()]);
    assert_eq!(
        defaulted.primary().expect("a vector was given").mode,
        foundation::SteeringMode::Ablate
    );
}

/// `--steering-layers` must survive BOTH orders, and this loop is the only
/// place in the workspace where that is a live question: it restricts the set
/// as the flag arrives, so the range has to be replayed when the vector comes
/// second and applied on arrival when it comes first. Getting one half wrong
/// steers the layers the caller excluded, which is fluent and wrong.
#[cfg(target_os = "macos")]
#[test]
fn a_layer_range_applies_whichever_side_of_the_vector_it_is_given() {
    let v = write_vector("range", 6, None);
    let path = v.to_str().unwrap();
    let covered = |args: &[&str]| {
        let s = parse(args).unwrap().unwrap().steering;
        let set = &s.primary().expect("a vector was given").set;
        (
            set.covered_layers(),
            set.layer(0).is_some(),
            set.layer(3).is_some(),
        )
    };

    let after = covered(&[
        "--model",
        "/tmp/m",
        "--steering",
        path,
        "--steering-layers",
        "2:4",
    ]);
    let before = covered(&[
        "--model",
        "/tmp/m",
        "--steering-layers",
        "2:4",
        "--steering",
        path,
    ]);
    assert_eq!(after, (3, false, true));
    assert_eq!(before, after, "the range must not depend on flag order");
}

/// An inverted range is refused here rather than silently selecting nothing,
/// matching `crates/invocation`'s `parse_layer_range`.
#[cfg(target_os = "macos")]
#[test]
fn an_inverted_layer_range_is_refused() {
    let v = write_vector("inverted", 6, None);
    assert!(parse(&[
        "--model",
        "/tmp/m",
        "--steering",
        v.to_str().unwrap(),
        "--steering-layers",
        "4:2",
    ])
    .is_err());
}

#[test]
fn reasoning_flag_defaults_to_off_and_parses_documented_levels() {
    let d = parse(&["--model", "/tmp/m"]).unwrap().unwrap();
    assert_eq!(d.reasoning, tokenizer::ReasoningEffort::Off);

    for (arg, expected) in [
        ("off", tokenizer::ReasoningEffort::Off),
        ("low", tokenizer::ReasoningEffort::Low),
        ("medium", tokenizer::ReasoningEffort::Medium),
        ("high", tokenizer::ReasoningEffort::High),
        ("xhigh", tokenizer::ReasoningEffort::XHigh),
    ] {
        let p = parse(&["--model", "/tmp/m", "--reasoning", arg])
            .unwrap()
            .unwrap();
        assert_eq!(p.reasoning, expected, "failed for --reasoning {arg}");
    }

    assert!(parse(&["--model", "/tmp/m", "--reasoning", "max"]).is_err());
    assert!(parse(&["--model", "/tmp/m", "--reasoning", "true"]).is_err());
}

#[test]
fn kv_bits_flag_defaults_to_off_and_parses_documented_widths() {
    let d = parse(&["--model", "/tmp/m"]).unwrap().unwrap();
    assert_eq!(d.kv_bits, runtime::KvQuant::Off);

    for (arg, expected) in [
        ("off", runtime::KvQuant::Off),
        (
            "2",
            runtime::KvQuant::TurboQuant {
                k_bits: 2,
                v_bits: 2,
            },
        ),
        (
            "3",
            runtime::KvQuant::TurboQuant {
                k_bits: 3,
                v_bits: 3,
            },
        ),
        (
            "3.5",
            runtime::KvQuant::TurboQuant {
                k_bits: 3,
                v_bits: 4,
            },
        ),
        (
            "4",
            runtime::KvQuant::TurboQuant {
                k_bits: 4,
                v_bits: 4,
            },
        ),
    ] {
        let p = parse(&["--model", "/tmp/m", "--kv-bits", arg])
            .unwrap()
            .unwrap();
        assert_eq!(p.kv_bits, expected, "failed for --kv-bits {arg}");
    }

    assert!(parse(&["--model", "/tmp/m", "--kv-bits", "5"]).is_err());
    assert!(parse(&["--model", "/tmp/m", "--kv-bits", "2.5"]).is_err());
}

#[test]
fn prefix_reuse_flag_defaults_to_off_and_parses_on_off() {
    let d = parse(&["--model", "/tmp/m"]).unwrap().unwrap();
    assert!(!d.prefix_reuse);

    let on = parse(&["--model", "/tmp/m", "--prefix-reuse", "on"])
        .unwrap()
        .unwrap();
    assert!(on.prefix_reuse);

    let off = parse(&["--model", "/tmp/m", "--prefix-reuse", "off"])
        .unwrap()
        .unwrap();
    assert!(!off.prefix_reuse);

    assert!(parse(&["--model", "/tmp/m", "--prefix-reuse", "maybe"]).is_err());
}

#[test]
fn session_slots_defaults_to_one_and_parses_a_count() {
    let d = parse(&["--model", "/tmp/m"]).unwrap().unwrap();
    assert_eq!(d.session_slots, 1);

    let three = parse(&[
        "--model",
        "/tmp/m",
        "--prefix-reuse",
        "on",
        "--session-slots",
        "3",
    ])
    .unwrap()
    .unwrap();
    assert_eq!(three.session_slots, 3);

    assert!(
        parse(&["--model", "/tmp/m", "--session-slots", "0"]).is_err(),
        "a zero-slot pool is not a smaller version of the feature, it is nonsense"
    );
    assert!(parse(&["--model", "/tmp/m", "--session-slots", "auto"]).is_err());
    assert!(parse(&["--model", "/tmp/m", "--session-slots", "-1"]).is_err());
}

/// The orphan-flag refusal, mirroring the `--steering-*`-without-`--steering`
/// pattern this file already asserts elsewhere: a parked session is never
/// reused without prefix reuse enabled, so naming a pool while explicitly
/// disabling reuse is a command line that says one thing while the server
/// does another.
#[test]
fn session_slots_above_one_needs_prefix_reuse_on() {
    assert!(parse(&["--model", "/tmp/m", "--session-slots", "2"]).is_err());
    assert!(parse(&[
        "--model",
        "/tmp/m",
        "--prefix-reuse",
        "off",
        "--session-slots",
        "2",
    ])
    .is_err());
    // Flag order must not matter.
    assert!(parse(&[
        "--model",
        "/tmp/m",
        "--session-slots",
        "2",
        "--prefix-reuse",
        "off",
    ])
    .is_err());
    // A pool of exactly 1 (the default) needs no --prefix-reuse at all: it
    // commits nothing extra, so there is nothing for the flag to be an
    // orphan of.
    assert!(parse(&[
        "--model",
        "/tmp/m",
        "--prefix-reuse",
        "off",
        "--session-slots",
        "1",
    ])
    .is_ok());
}

// ---------------------------------------------------------------------------
// `--system` / `--system-file`

#[test]
fn system_flag_defaults_to_absent_and_joins_repeats_with_a_newline() {
    let d = parse(&["--model", "/tmp/m"]).unwrap().unwrap();
    assert_eq!(d.default_system, None);

    let one = parse(&["--model", "/tmp/m", "--system", "be brief"])
        .unwrap()
        .unwrap();
    assert_eq!(one.default_system.as_deref(), Some("be brief"));

    // Repeatable with the same grammar `turbospark-check --system` has, so a
    // multi-line prompt can be written without embedding a newline in a shell
    // argument.
    let many = parse(&[
        "--model", "/tmp/m", "--system", "be brief", "--system", "and kind",
    ])
    .unwrap()
    .unwrap();
    assert_eq!(many.default_system.as_deref(), Some("be brief\nand kind"));
}

/// An empty prompt is refused rather than treated as "no default". A caller
/// who named the flag meant to set one, and serving every request unprompted
/// is the failure they would not notice.
#[test]
fn an_empty_system_prompt_is_refused() {
    let err = parse(&["--model", "/tmp/m", "--system", "   "]).unwrap_err();
    assert!(err.contains("--system"), "{err}");
}

#[test]
fn system_file_reads_the_prompt_from_disk() {
    let dir = std::env::temp_dir().join(format!("ts-system-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    let path = dir.join("prompt.txt");
    // The trailing newline a text editor leaves is trimmed, so the same prompt
    // written two ways renders to the same prompt.
    std::fs::write(&path, "answer only in haiku\n").unwrap();

    let p = parse(&["--model", "/tmp/m", "--system-file", path.to_str().unwrap()])
        .unwrap()
        .unwrap();
    assert_eq!(p.default_system.as_deref(), Some("answer only in haiku"));

    std::fs::write(&path, "\n  \n").unwrap();
    let err = parse(&["--model", "/tmp/m", "--system-file", path.to_str().unwrap()]).unwrap_err();
    assert!(err.contains("empty"), "{err}");

    std::fs::remove_dir_all(&dir).ok();
}

#[test]
fn a_missing_system_file_is_refused_by_name() {
    let err = parse(&["--model", "/tmp/m", "--system-file", "/tmp/no/such/prompt"]).unwrap_err();
    assert!(err.contains("/tmp/no/such/prompt"), "{err}");
}

/// Two spellings of one setting. Resolving a conflict silently is the shape
/// this parser already refuses for an orphan steering parameter.
#[test]
fn system_and_system_file_together_are_refused() {
    let err = parse(&[
        "--model",
        "/tmp/m",
        "--system",
        "be brief",
        "--system-file",
        "/tmp/whatever",
    ])
    .unwrap_err();
    assert!(err.contains("--system-file"), "{err}");
}

/// Both flags appear in the usage text, or an operator cannot discover them.
#[test]
fn the_usage_text_documents_both_system_flags() {
    assert!(
        super::args::USAGE.contains("--system "),
        "{}",
        super::args::USAGE
    );
    assert!(super::args::USAGE.contains("--system-file"));
}

#[test]
fn omlx_compatibility_memory_guard_flags() {
    let safe_args = parse(&["--model", "/tmp/m", "--memory-guard", "safe"])
        .unwrap()
        .unwrap();
    assert_eq!(safe_args.load_policy.guard, runtime::LoadGuard::Balanced);

    let gb_args = parse(&["--model", "/tmp/m", "--memory-guard-gb", "48"])
        .unwrap()
        .unwrap();
    assert_eq!(
        gb_args.load_policy.guard,
        runtime::LoadGuard::Custom {
            max_counted_bytes: 48 * 1024 * 1024 * 1024
        }
    );
}

#[test]
fn omlx_compatibility_extended_flags() {
    let args = parse(&[
        "--model",
        "/tmp/m",
        "--prefix-reuse",
        "on",
        "--max-concurrent-requests",
        "16",
        "--hf-endpoint",
        "https://hf-mirror.com",
        "--paged-ssd-cache-dir",
        "/tmp/omlx-cache",
        "--hot-cache-max-size",
        "20%",
        "--mcp-config",
        "/tmp/mcp.json",
    ])
    .unwrap()
    .unwrap();

    assert_eq!(args.session_slots, 16);
    assert_eq!(args.hf_endpoint.as_deref(), Some("https://hf-mirror.com"));
    assert_eq!(
        args.paged_ssd_cache_dir,
        Some(PathBuf::from("/tmp/omlx-cache"))
    );
    assert_eq!(args.hot_cache_max_size.as_deref(), Some("20%"));
    assert_eq!(args.mcp_config, Some(PathBuf::from("/tmp/mcp.json")));
}

/// F7: `--embedding-model` alone used to be refused with "--model needs a
/// value" before this parser ever consulted it, even though
/// `main.rs::open_models_registry`'s `(false, Some(emb_arg))` arm exists
/// specifically to serve an embedding-only server with no chat model.
#[test]
fn embedding_model_alone_is_accepted_with_no_chat_model() {
    let args = parse(&["--embedding-model", "/tmp/emb"]).unwrap().unwrap();
    assert!(args.model.is_empty(), "{args:?}");
    assert_eq!(args.embedding_model.as_deref(), Some("/tmp/emb"));
}

/// Neither flag at all is still refused, and by name -- this is the case
/// the fix above must not silently swallow.
#[test]
fn neither_model_nor_embedding_model_is_refused() {
    let err = parse(&["--bind", "loopback"]).unwrap_err();
    assert!(err.contains("--model"), "{err}");
    assert!(err.contains("--embedding-model"), "{err}");
}

/// Audio flags are repeatable per task and stand in for `--model`: an
/// audio-only server is a real configuration.
#[test]
fn audio_models_alone_are_accepted_and_repeat_per_task() {
    let args = parse(&[
        "--stt-model",
        "whisper-base-en",
        "--stt-model",
        "/tmp/qwen",
        "--tts-model",
        "kokoro-82m",
        "--music-model",
        "minimax-music3-4bit",
    ])
    .unwrap()
    .unwrap();
    assert!(args.model.is_empty() && args.models.is_empty(), "{args:?}");
    assert_eq!(args.stt_models, ["whisper-base-en", "/tmp/qwen"]);
    assert_eq!(args.tts_models, ["kokoro-82m"]);
    assert_eq!(args.music_models, ["minimax-music3-4bit"]);
    assert!(args.has_audio());
}

#[test]
fn audio_models_ride_along_with_a_chat_model() {
    let args = parse(&["--model", "/tmp/m", "--stt-model", "whisper-base-en"])
        .unwrap()
        .unwrap();
    assert_eq!(args.models, ["/tmp/m"]);
    assert_eq!(args.stt_models, ["whisper-base-en"]);
}

#[test]
fn no_audio_flags_means_no_audio() {
    let args = parse(&["--model", "/tmp/m"]).unwrap().unwrap();
    assert!(!args.has_audio());
}

#[test]
fn an_audio_flag_without_a_value_is_refused() {
    let err = parse(&["--model", "/tmp/m", "--tts-model"]).unwrap_err();
    assert!(err.contains("--tts-model"), "{err}");
}

#[test]
fn help_text_names_the_audio_flags() {
    let usage = super::args::usage();
    for flag in ["--stt-model", "--tts-model", "--music-model"] {
        assert!(usage.contains(flag), "{flag} missing from --help");
    }
}

/// F21: a `--memory-guard-gb` large enough to overflow a byte count must be
/// refused rather than silently wrapping (release) or panicking (debug).
#[test]
fn an_overflowing_memory_guard_gb_is_refused() {
    let err = parse(&[
        "--model",
        "/tmp/m",
        "--memory-guard-gb",
        "18446744073709551615",
    ])
    .unwrap_err();
    assert!(err.contains("--memory-guard-gb"), "{err}");
}

#[test]
fn model_dir_auto_discovery() {
    let tmp = std::env::temp_dir().join(format!("turbospark-test-model-dir-{}", line!()));
    let model_folder = tmp.join("test-model.gturbo");
    std::fs::create_dir_all(&model_folder).unwrap();
    std::fs::write(model_folder.join("manifest.json"), "{}").unwrap();

    let args = parse(&["--model-dir", tmp.to_str().unwrap()])
        .unwrap()
        .unwrap();
    assert_eq!(args.model, model_folder.display().to_string());

    std::fs::remove_dir_all(&tmp).ok();
}