arvin 0.2.0

A staged cutoff for agent runs, where a run keeps its tools, budget, and sandbox only while it keeps proving progress. Three triggers move the stage, an operator pull, a budget ceiling, and missed proofs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
//! Command line for arvin, a thin shell over the arvin
//! library.
//!
//! Every command names the state file first. The clock the
//! command line uses is the wall clock in UTC, and no flag
//! overrides it, so the evaluation a caller sees is the
//! evaluation the machine clock gives. Errors the switch raises
//! are printed as one line on stderr with the exit code the
//! error carries, and no traceback is ever printed for them.
//!
//! The argument parsing mirrors the Python argparse surface of
//! Round 1, its usage texts and parser error messages and exit
//! codes, its acceptance of unambiguous long option prefixes,
//! its collection of unrecognized arguments at the top level,
//! and its integer conversion with the Unicode digit and
//! whitespace families of the Python int grammar, probed against
//! the Python runtime before the port was written.

use std::io::Write;
use std::path::PathBuf;
use std::process::ExitCode;
use std::time::Duration;

use arvin::{
    consultation_from_reply_body, py_float_repr, py_repr_str, timeout_printable,
    validate_judge_form, validate_model_id, Error, FixtureTransport, Instant, ModelTransport,
    Record, SubprocessTransport, Switch, Value, DEFAULT_JUDGE_TIMEOUT_SECONDS,
    DEFAULT_MISSED_PROOF_LIMIT, DEFAULT_PROOF_INTERVAL_SECONDS, MODEL_NAME,
};

const MAIN_USAGE: &str =
    "usage: arvin [-h] [-V] --state STATE {register,prove,spend,pull,stage,log,runs} ...";

const MAIN_HELP: &str = "\
usage: arvin [-h] [-V] --state STATE {register,prove,spend,pull,stage,log,runs} ...

Watch agent runs and walk them down a staged cutoff as the evidence of a
runaway grows.

positional arguments:
  {register,prove,spend,pull,stage,log,runs}
    register            open a run record
    prove               record a progress proof for a run
    spend               record a spend report for a run
    pull                pull the switch and kill the run
    stage               evaluate a run and report its stage
    log                 show the recorded decision log of a run
    runs                list the standing summary of every run

options:
  -h, --help            show this help message and exit
  -V, --version         show program's version number and exit
  --state STATE         the state file holding the runs, created by the first
                        mutation";

const COMMANDS: [&str; 7] = ["register", "prove", "spend", "pull", "stage", "log", "runs"];

fn sub_usage(command: &str) -> &'static str {
    match command {
        "register" => {
            "usage: arvin register [-h] [--proof-interval PROOF_INTERVAL]\n                        [--missed-limit MISSED_LIMIT]\n                        [--soft-ceiling SOFT_CEILING]\n                        [--hard-ceiling HARD_CEILING]\n                        run"
        }
        "prove" => "usage: arvin prove [-h] [--note NOTE] run",
        "spend" => "usage: arvin spend [-h] --amount AMOUNT run",
        "pull" => "usage: arvin pull [-h] run",
        "stage" => {
            "usage: arvin stage [-h] [--judge JUDGE]\n                        [--judge-arg JUDGE_ARG]\n                        [--judge-timeout JUDGE_TIMEOUT]\n                        [--judge-fixture JUDGE_FIXTURE]\n                        [--judge-model JUDGE_MODEL]\n                        [--host-context HOST_CONTEXT]\n                        run"
        }
        "runs" => "usage: arvin runs [-h]",
        _ => "usage: arvin log [-h] run",
    }
}

fn sub_help(command: &str) -> String {
    let body = match command {
        "register" => {
            "positional arguments:\n  run\n\noptions:\n  -h, --help            show this help message and exit\n  --proof-interval PROOF_INTERVAL\n                        the proof interval in seconds, default 60\n  --missed-limit MISSED_LIMIT\n                        the missed proof limit that warrants kill, default 5\n  --soft-ceiling SOFT_CEILING\n                        the spend at or above which cut budget is warranted\n  --hard-ceiling HARD_CEILING\n                        the spend at or above which kill is warranted"
        }
        "prove" => {
            "positional arguments:\n  run\n\noptions:\n  -h, --help   show this help message and exit\n  --note NOTE  a short progress note, never judged"
        }
        "spend" => {
            "positional arguments:\n  run\n\noptions:\n  -h, --help       show this help message and exit\n  --amount AMOUNT  the spend to add, in host units"
        }
        "pull" => {
            "positional arguments:\n  run\n\noptions:\n  -h, --help  show this help message and exit"
        }
        "stage" => {
            "positional arguments:\n  run\n\noptions:\n  -h, --help            show this help message and exit\n  --judge JUDGE         the helper program that judges the picture\n  --judge-arg JUDGE_ARG\n                        one argument handed to the helper before the payload flag, repeatable\n  --judge-timeout JUDGE_TIMEOUT\n                        the seconds the helper may take before the call fails, default 10\n  --judge-fixture JUDGE_FIXTURE\n                        a file holding one recorded reply body, judged instead of calling a helper\n  --judge-model JUDGE_MODEL\n                        the decision model identifier pinned for the consultation, default jev-1.14.0\n  --host-context HOST_CONTEXT\n                        host supplied context rendered into the picture"
        }
        "runs" => "options:\n  -h, --help  show this help message and exit",
        _ => {
            "positional arguments:\n  run\n\noptions:\n  -h, --help  show this help message and exit"
        }
    };
    format!("{}\n\n{}", sub_usage(command), body)
}

fn value_options(command: &str) -> &'static [&'static str] {
    match command {
        "register" => &[
            "--proof-interval",
            "--missed-limit",
            "--soft-ceiling",
            "--hard-ceiling",
        ],
        "prove" => &["--note"],
        "spend" => &["--amount"],
        "stage" => &[
            "--judge",
            "--judge-arg",
            "--judge-timeout",
            "--judge-fixture",
            "--judge-model",
            "--host-context",
        ],
        _ => &[],
    }
}

fn is_int_option(command: &str, option: &str) -> bool {
    match command {
        "register" => matches!(
            option,
            "--proof-interval" | "--missed-limit" | "--soft-ceiling" | "--hard-ceiling"
        ),
        "spend" => option == "--amount",
        "stage" => option == "--judge-timeout",
        _ => false,
    }
}

fn required_options(command: &str) -> &'static [&'static str] {
    match command {
        "spend" => &["--amount"],
        _ => &[],
    }
}

struct ParserError {
    usage: &'static str,
    prog: String,
    message: String,
}

fn parser_error(usage: &'static str, prog: &str, message: String) -> ParserError {
    ParserError {
        usage,
        prog: prog.to_string(),
        message,
    }
}

/// Write one line to stderr, fallibly (DM-A24). The result
/// is ignored on purpose: the reporters of failure must not
/// themselves panic when stderr also fails, and the exit
/// code carries the failure either way.
fn eprint_line(text: &str) {
    let stderr = std::io::stderr();
    let mut lock = stderr.lock();
    let _ = writeln!(lock, "{text}");
}

/// Write one line of command output to stdout, checked
/// (DM-A24). A failed write, a broken pipe or a full device,
/// answers the output error line on stderr and exits 1,
/// where the panicking print macros answered with a panic
/// report at exit 101, against this module's doctrine that
/// no traceback is ever printed. Where the command was a
/// mutation, the mutation has already published when its
/// print fails; the failure stands in the reporting, and
/// the message names the output, not the command.
fn print_line(text: &str) {
    let stdout = std::io::stdout();
    let mut lock = stdout.lock();
    if writeln!(lock, "{text}").is_err() || lock.flush().is_err() {
        eprint_line("error: the command's output could not be written");
        std::process::exit(1);
    }
}

fn parser_fail(usage: &str, prog: &str, message: &str) -> ExitCode {
    eprint_line(usage);
    eprint_line(&format!("{prog}: error: {message}"));
    ExitCode::from(2)
}

fn is_option_like(token: &str) -> bool {
    if token.len() < 2 || !token.starts_with('-') || token == "-" {
        return false;
    }
    // A token in the shape of a negative number is positional,
    // as argparse's negative number matcher holds when no
    // option looks like a negative number. The digits of that
    // shape are the decimal digits of the Python grammar, the
    // same set the integer conversion below accepts.
    let body = &token[1..];
    let digits: String = body.chars().filter(|c| *c != '.').collect();
    if !digits.is_empty() && digits.chars().all(|c| py_digit_value(c).is_some()) {
        return false;
    }
    true
}

/// Resolve a long option token against the candidates of one
/// parser, the argparse way: an exact match wins, an
/// unambiguous prefix matches, an ambiguous prefix is an
/// error, and no match means the token is an extra.
fn resolve_long<'a>(name: &'a str, candidates: &[&'a str]) -> Result<Option<&'a str>, String> {
    if candidates.contains(&name) {
        return Ok(Some(name));
    }
    let matches: Vec<&str> = candidates
        .iter()
        .filter(|candidate| candidate.starts_with(name))
        .copied()
        .collect();
    match matches.len() {
        0 => Ok(None),
        1 => Ok(Some(matches[0])),
        _ => Err(format!(
            "ambiguous option: {name} could match {}",
            matches.join(", ")
        )),
    }
}

enum SubValue {
    Text(String),
    Int(Value),
}

struct SubArgs {
    positionals: Vec<String>,
    options: Vec<(String, SubValue)>,
    extras: Vec<String>,
}

/// The decimal digit ranges of the Unicode character set,
/// each ten codepoints wide with the digit value standing at
/// the offset inside its range, as probed against the Python
/// runtime the conversion mirrors, Python 3.12.3 carrying
/// Unicode 15.0.0. The Python int conversion accepts a digit
/// from any of these families and no other numeric character.
const DECIMAL_DIGIT_RANGES: [(u32, u32); 68] = [
    (0x0030, 0x0039),
    (0x0660, 0x0669),
    (0x06f0, 0x06f9),
    (0x07c0, 0x07c9),
    (0x0966, 0x096f),
    (0x09e6, 0x09ef),
    (0x0a66, 0x0a6f),
    (0x0ae6, 0x0aef),
    (0x0b66, 0x0b6f),
    (0x0be6, 0x0bef),
    (0x0c66, 0x0c6f),
    (0x0ce6, 0x0cef),
    (0x0d66, 0x0d6f),
    (0x0de6, 0x0def),
    (0x0e50, 0x0e59),
    (0x0ed0, 0x0ed9),
    (0x0f20, 0x0f29),
    (0x1040, 0x1049),
    (0x1090, 0x1099),
    (0x17e0, 0x17e9),
    (0x1810, 0x1819),
    (0x1946, 0x194f),
    (0x19d0, 0x19d9),
    (0x1a80, 0x1a89),
    (0x1a90, 0x1a99),
    (0x1b50, 0x1b59),
    (0x1bb0, 0x1bb9),
    (0x1c40, 0x1c49),
    (0x1c50, 0x1c59),
    (0xa620, 0xa629),
    (0xa8d0, 0xa8d9),
    (0xa900, 0xa909),
    (0xa9d0, 0xa9d9),
    (0xa9f0, 0xa9f9),
    (0xaa50, 0xaa59),
    (0xabf0, 0xabf9),
    (0xff10, 0xff19),
    (0x104a0, 0x104a9),
    (0x10d30, 0x10d39),
    (0x11066, 0x1106f),
    (0x110f0, 0x110f9),
    (0x11136, 0x1113f),
    (0x111d0, 0x111d9),
    (0x112f0, 0x112f9),
    (0x11450, 0x11459),
    (0x114d0, 0x114d9),
    (0x11650, 0x11659),
    (0x116c0, 0x116c9),
    (0x11730, 0x11739),
    (0x118e0, 0x118e9),
    (0x11950, 0x11959),
    (0x11c50, 0x11c59),
    (0x11d50, 0x11d59),
    (0x11da0, 0x11da9),
    (0x11f50, 0x11f59),
    (0x16a60, 0x16a69),
    (0x16ac0, 0x16ac9),
    (0x16b50, 0x16b59),
    (0x1d7ce, 0x1d7d7),
    (0x1d7d8, 0x1d7e1),
    (0x1d7e2, 0x1d7eb),
    (0x1d7ec, 0x1d7f5),
    (0x1d7f6, 0x1d7ff),
    (0x1e140, 0x1e149),
    (0x1e2f0, 0x1e2f9),
    (0x1e4f0, 0x1e4f9),
    (0x1e950, 0x1e959),
    (0x1fbf0, 0x1fbf9),
];

/// The value of one character under the Python int conversion,
/// a decimal digit in any family of the table above, or None
/// for any other character.
fn py_digit_value(c: char) -> Option<u32> {
    let n = c as u32;
    DECIMAL_DIGIT_RANGES
        .iter()
        .find(|&&(low, high)| n >= low && n <= high)
        .map(|&(low, _)| n - low)
}

/// The whitespace the Python int conversion strips, the
/// Py_UNICODE_ISSPACE set, which is wider than the Rust
/// whitespace property by the information separators.
fn is_python_space(c: char) -> bool {
    matches!(c,
        '\u{0009}'..='\u{000d}'
        | '\u{001c}'..='\u{001f}'
        | ' '
        | '\u{0085}'
        | '\u{00a0}'
        | '\u{1680}'
        | '\u{2000}'..='\u{200a}'
        | '\u{2028}'
        | '\u{2029}'
        | '\u{202f}'
        | '\u{205f}'
        | '\u{3000}')
}

/// Python's int conversion for the numeric arguments: optional
/// surrounding whitespace from the Python whitespace set, an
/// optional sign, decimal digits from any family of the table
/// above with single underscores between them. The conversion
/// refuses a digit count past 4300 digit characters, the limit
/// the Python runtime applies, where a wider conversion would
/// stand as a parser failure where Python converted the value.
/// The value is kept whole, at 128 bit width when it fits and
/// as its canonical digit text when it does not, so a later
/// validation prints the number the caller typed.
fn python_int(text: &str) -> Option<Value> {
    let trimmed = text.trim_matches(is_python_space);
    let (negative, body) = if let Some(rest) = trimmed.strip_prefix('-') {
        (true, rest)
    } else if let Some(rest) = trimmed.strip_prefix('+') {
        (false, rest)
    } else {
        (false, trimmed)
    };
    if body.is_empty() {
        return None;
    }
    let mut digits = String::new();
    let mut digit_count = 0usize;
    let mut previous_digit = false;
    let mut previous_underscore = false;
    let mut seen_digit = false;
    for ch in body.chars() {
        if ch == '_' {
            if !previous_digit || previous_underscore {
                return None;
            }
            previous_underscore = true;
            previous_digit = false;
        } else if let Some(value) = py_digit_value(ch) {
            digits.push(char::from_digit(value, 10).unwrap());
            digit_count += 1;
            previous_digit = true;
            previous_underscore = false;
            seen_digit = true;
        } else {
            return None;
        }
    }
    if previous_underscore || !seen_digit {
        return None;
    }
    if digit_count > 4300 {
        return None;
    }
    let canonical_digits = {
        let stripped = digits.trim_start_matches('0');
        if stripped.is_empty() {
            "0".to_string()
        } else {
            stripped.to_string()
        }
    };
    let signed = if negative && canonical_digits != "0" {
        format!("-{canonical_digits}")
    } else {
        canonical_digits.clone()
    };
    match signed.parse::<i128>() {
        Ok(number) => Some(Value::Int(number)),
        Err(_) => Some(Value::BigInt(signed)),
    }
}

/// Parse one subcommand's arguments. Option values are drawn
/// from the following token unless it is option like, numeric
/// options are converted as they are consumed, and tokens the
/// subcommand does not consume are collected as extras for the
/// top level parser to report. A double dash stops option
/// handling and is itself consumed, as the Python parser
/// consumed it below the subcommand.
fn parse_sub(command: &str, tokens: &[String]) -> Result<SubArgs, ParserError> {
    let mut candidates: Vec<&str> = vec!["--help"];
    candidates.extend_from_slice(value_options(command));
    let mut result = SubArgs {
        positionals: Vec::new(),
        options: Vec::new(),
        extras: Vec::new(),
    };
    let mut index = 0;
    let mut after_separator = false;
    while index < tokens.len() {
        let token = &tokens[index];
        if !after_separator && token == "--" {
            after_separator = true;
            if command == "runs" {
                result.extras.push(token.clone());
            }
            index += 1;
            continue;
        }
        if !after_separator
            && (token == "-h"
                || token == "--help"
                || (token.starts_with("-h") && !token.starts_with("--")))
        {
            print_line(&sub_help(command));
            std::process::exit(0);
        }
        if !after_separator && token.starts_with("--") && token.len() > 2 {
            let (name, inline_value) = match token.find('=') {
                Some(pos) => (&token[..pos], Some(token[pos + 1..].to_string())),
                None => (&token[..], None),
            };
            match resolve_long(name, &candidates) {
                Ok(Some("--help")) => {
                    if let Some(value) = inline_value {
                        return Err(parser_error(
                            sub_usage(command),
                            &format!("arvin {command}"),
                            format!(
                                "argument -h/--help: ignored explicit argument {}",
                                py_repr_str(&value)
                            ),
                        ));
                    }
                    print_line(&sub_help(command));
                    std::process::exit(0);
                }
                Ok(Some(option)) => {
                    let raw = if let Some(value) = inline_value {
                        index += 1;
                        value
                    } else if index + 1 < tokens.len() && !is_option_like(&tokens[index + 1]) {
                        let value = tokens[index + 1].clone();
                        index += 2;
                        value
                    } else {
                        return Err(parser_error(
                            sub_usage(command),
                            &format!("arvin {command}"),
                            format!("argument {option}: expected one argument"),
                        ));
                    };
                    if is_int_option(command, option) {
                        match python_int(&raw) {
                            Some(value) => {
                                result
                                    .options
                                    .push((option.to_string(), SubValue::Int(value)));
                            }
                            None => {
                                return Err(parser_error(
                                    sub_usage(command),
                                    &format!("arvin {command}"),
                                    format!(
                                        "argument {option}: invalid int value: {}",
                                        py_repr_str(&raw)
                                    ),
                                ));
                            }
                        }
                    } else {
                        result
                            .options
                            .push((option.to_string(), SubValue::Text(raw)));
                    }
                    continue;
                }
                Ok(None) => {
                    result.extras.push(token.clone());
                    index += 1;
                    continue;
                }
                Err(message) => {
                    return Err(parser_error(
                        sub_usage(command),
                        &format!("arvin {command}"),
                        message,
                    ));
                }
            }
        }
        if !after_separator && is_option_like(token) {
            result.extras.push(token.clone());
            index += 1;
            continue;
        }
        if command != "runs" && result.positionals.is_empty() {
            result.positionals.push(token.clone());
        } else {
            result.extras.push(token.clone());
        }
        index += 1;
    }
    Ok(result)
}

/// The values recorded under one option name, in the order
/// the caller named them. The option readers state their
/// direction and their projection over this one scan, so the
/// name matching stands in one place.
fn option_values<'a>(args: &'a SubArgs, name: &str) -> Vec<&'a SubValue> {
    args.options
        .iter()
        .filter(|(seen, _)| seen == name)
        .map(|(_, value)| value)
        .collect()
}

fn option_text<'a>(args: &'a SubArgs, name: &str) -> Option<&'a str> {
    option_values(args, name)
        .into_iter()
        .rev()
        .find_map(|value| match value {
            SubValue::Text(text) => Some(text.as_str()),
            SubValue::Int(_) => None,
        })
}

/// Every value of a repeatable option, in the order the
/// caller named them.
fn option_list<'a>(args: &'a SubArgs, name: &str) -> Vec<&'a str> {
    option_values(args, name)
        .into_iter()
        .filter_map(|value| match value {
            SubValue::Text(text) => Some(text.as_str()),
            SubValue::Int(_) => None,
        })
        .collect()
}

fn option_int<'a>(args: &'a SubArgs, name: &str) -> Option<&'a Value> {
    option_values(args, name)
        .into_iter()
        .rev()
        .find_map(|value| match value {
            SubValue::Int(value) => Some(value),
            SubValue::Text(_) => None,
        })
}

fn require(command: &str, args: &SubArgs) -> Result<(), ParserError> {
    let mut missing: Vec<String> = Vec::new();
    if command != "runs" && args.positionals.is_empty() {
        missing.push("run".to_string());
    }
    for name in required_options(command) {
        if option_int(args, name).is_none() {
            missing.push(name.to_string());
        }
    }
    if missing.is_empty() {
        Ok(())
    } else {
        Err(parser_error(
            sub_usage(command),
            &format!("arvin {command}"),
            format!(
                "the following arguments are required: {}",
                missing.join(", ")
            ),
        ))
    }
}

fn report_error(error: &Error) -> ExitCode {
    eprint_line(&format!("error: {}", error.message()));
    ExitCode::from(error.exit_code())
}

fn run() -> ExitCode {
    let os_argv: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
    let argv: Vec<String> = os_argv
        .iter()
        .map(|arg| arg.to_string_lossy().into_owned())
        .collect();
    match dispatch(&argv, &os_argv) {
        Ok(code) => code,
        Err(error) => report_error(&error),
    }
}

/// The state path is the one argument carried as raw bytes,
/// because it names a file, as the state option's seat in
/// dispatch records. Every other argument is read as text,
/// and an argument that is not valid UTF-8 text is refused
/// rather than rewritten with replacement characters on its
/// way into a run id, a proof note, a host context, or a
/// judge path, the lossy carriage DM-A13 recorded. The scan
/// walks the raw arguments as dispatch's own state scan
/// consumes them and exempts exactly the state value, in its
/// inline form after the first equals sign and in its
/// following token form. The refusal names the argument by
/// its position, the only name an undecodable argument has.
fn first_undecodable_argument(os_argv: &[std::ffi::OsString]) -> Option<usize> {
    let mut exempt: Vec<bool> = vec![false; os_argv.len()];
    let mut index = 0;
    while index < os_argv.len() {
        let token = os_argv[index].to_string_lossy();
        if token == "--" {
            break;
        }
        if token == "-h"
            || token == "--help"
            || (token.starts_with("-h") && !token.starts_with("--"))
            || token == "-V"
            || token == "--version"
        {
            break;
        }
        if token.starts_with("--") && token.len() > 2 {
            let (name, inline_value) = match token.find('=') {
                Some(pos) => (&token[..pos], true),
                None => (&token[..], false),
            };
            match resolve_long(name, &["--help", "--version", "--state"]) {
                Ok(Some("--state")) => {
                    if inline_value {
                        exempt[index] = true;
                        index += 1;
                    } else if index + 1 < os_argv.len()
                        && !is_option_like(&os_argv[index + 1].to_string_lossy())
                    {
                        exempt[index] = true;
                        exempt[index + 1] = true;
                        index += 2;
                    } else {
                        index += 1;
                    }
                }
                Ok(Some(_)) => break,
                Ok(None) => index += 1,
                Err(_) => break,
            }
            continue;
        }
        if is_option_like(&token) {
            index += 1;
            continue;
        }
        break;
    }
    (0..os_argv.len()).find(|&i| !exempt[i] && os_argv[i].to_str().is_none())
}

/// The current instant in UTC. The command line is the one
/// clock reader in the repo (CONTRACT DM-6): it reads SystemTime
/// here and passes the instant in, and the library reads no
/// wall clock.
fn now_utc() -> Result<Instant, Error> {
    instant_from_read(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH))
}

/// The instant a clock read names. A read that fails stands
/// before the epoch, and no command may run on an instant the
/// clock never gave (perfection finding DM-P8): the read
/// answers a failure naming the case, at the failure exit,
/// instead of the epoch the standing form fabricated.
fn instant_from_read(read: Result<Duration, std::time::SystemTimeError>) -> Result<Instant, Error> {
    read.map(|elapsed| Instant::from_epoch_micros(elapsed.as_micros() as i128, Some(0)))
        .map_err(|_| Error::Failure("the system clock stands before the epoch".to_string()))
}

fn inline_os_after_equals(arg: &std::ffi::OsStr) -> std::ffi::OsString {
    #[cfg(unix)]
    {
        use std::os::unix::ffi::{OsStrExt, OsStringExt};
        let raw = arg.as_bytes();
        let at = raw.iter().position(|byte| *byte == b'=').unwrap();
        std::ffi::OsString::from_vec(raw[at + 1..].to_vec())
    }
    #[cfg(windows)]
    {
        use std::os::windows::ffi::{OsStrExt, OsStringExt};
        let wide: Vec<u16> = arg.encode_wide().collect();
        let at = wide
            .iter()
            .position(|unit| *unit == u16::from(b'='))
            .unwrap();
        std::ffi::OsString::from_wide(&wide[at + 1..])
    }
    #[cfg(not(any(unix, windows)))]
    {
        let text = arg.to_string_lossy();
        let (_, rest) = text.split_once('=').unwrap();
        std::ffi::OsString::from(rest)
    }
}

fn dispatch(argv: &[String], os_argv: &[std::ffi::OsString]) -> Result<ExitCode, Error> {
    if let Some(index) = first_undecodable_argument(os_argv) {
        return Ok(parser_fail(
            MAIN_USAGE,
            "arvin",
            &format!("argument {} is not valid UTF-8 text", index + 1),
        ));
    }
    // Parse the top level: the state option and the subcommand
    // word, with the remaining tokens handed to the subcommand.
    // A double dash standing where the subcommand word is
    // expected is taken as the subcommand word itself, and a
    // double dash with nothing after it is taken as nothing,
    // both as the Python parser took them.
    let mut state_path: Option<PathBuf> = None;
    let mut index = 0;
    let mut command: Option<String> = None;
    let mut rest: Vec<String> = Vec::new();
    let mut extras: Vec<String> = Vec::new();
    while index < argv.len() {
        let token = &argv[index];
        if token == "--" {
            if index + 1 < argv.len() {
                command = Some(token.clone());
                rest = argv[index + 1..].to_vec();
            }
            break;
        }
        if token == "-h"
            || token == "--help"
            || (token.starts_with("-h") && !token.starts_with("--"))
        {
            print_line(MAIN_HELP);
            return Ok(ExitCode::from(0));
        }
        if token == "-V" {
            print_line(&format!("arvin {}", env!("CARGO_PKG_VERSION")));
            return Ok(ExitCode::from(0));
        }
        if token.starts_with("--") && token.len() > 2 {
            let (name, inline_value) = match token.find('=') {
                Some(pos) => (&token[..pos], Some(token[pos + 1..].to_string())),
                None => (&token[..], None),
            };
            match resolve_long(name, &["--help", "--version", "--state"]) {
                Ok(Some("--help")) => {
                    if let Some(value) = inline_value {
                        return Ok(parser_fail(
                            MAIN_USAGE,
                            "arvin",
                            &format!(
                                "argument -h/--help: ignored explicit argument {}",
                                py_repr_str(&value)
                            ),
                        ));
                    }
                    print_line(MAIN_HELP);
                    return Ok(ExitCode::from(0));
                }
                Ok(Some("--version")) => {
                    if let Some(value) = inline_value {
                        return Ok(parser_fail(
                            MAIN_USAGE,
                            "arvin",
                            &format!(
                                "argument -V/--version: ignored explicit argument {}",
                                py_repr_str(&value)
                            ),
                        ));
                    }
                    print_line(&format!("arvin {}", env!("CARGO_PKG_VERSION")));
                    return Ok(ExitCode::from(0));
                }
                Ok(Some("--state")) => {
                    if inline_value.is_some() {
                        // The state value is carried as the raw
                        // argument bytes, so a state path that is
                        // not valid UTF-8 names the file the caller
                        // named, as the Python surface names it.
                        state_path = Some(PathBuf::from(inline_os_after_equals(&os_argv[index])));
                        index += 1;
                    } else if index + 1 < argv.len() && !is_option_like(&argv[index + 1]) {
                        state_path = Some(PathBuf::from(os_argv[index + 1].clone()));
                        index += 2;
                    } else {
                        return Ok(parser_fail(
                            MAIN_USAGE,
                            "arvin",
                            "argument --state: expected one argument",
                        ));
                    }
                    continue;
                }
                Ok(Some(_)) => unreachable!(),
                Ok(None) => {
                    extras.push(token.clone());
                    index += 1;
                    continue;
                }
                Err(message) => {
                    return Ok(parser_fail(MAIN_USAGE, "arvin", &message));
                }
            }
        }
        if is_option_like(token) {
            extras.push(token.clone());
            index += 1;
            continue;
        }
        command = Some(token.clone());
        rest = argv[index + 1..].to_vec();
        break;
    }
    let Some(command) = command else {
        let mut missing = Vec::new();
        if state_path.is_none() {
            missing.push("--state");
        }
        missing.push("command");
        return Ok(parser_fail(
            MAIN_USAGE,
            "arvin",
            &format!(
                "the following arguments are required: {}",
                missing.join(", ")
            ),
        ));
    };
    if !COMMANDS.contains(&command.as_str()) {
        return Ok(parser_fail(
            MAIN_USAGE,
            "arvin",
            &format!(
                "argument command: invalid choice: {} (choose from 'register', 'prove', 'spend', 'pull', 'stage', 'log', 'runs')",
                py_repr_str(&command)
            ),
        ));
    }
    let args = match parse_sub(&command, &rest) {
        Ok(args) => args,
        Err(failure) => {
            return Ok(parser_fail(failure.usage, &failure.prog, &failure.message));
        }
    };
    if let Err(failure) = require(&command, &args) {
        return Ok(parser_fail(failure.usage, &failure.prog, &failure.message));
    }
    if state_path.is_none() {
        return Ok(parser_fail(
            MAIN_USAGE,
            "arvin",
            "the following arguments are required: --state",
        ));
    }
    extras.extend(args.extras.iter().cloned());
    if !extras.is_empty() {
        return Ok(parser_fail(
            MAIN_USAGE,
            "arvin",
            &format!("unrecognized arguments: {}", extras.join(" ")),
        ));
    }
    let switch = Switch::new(state_path.unwrap());
    let run = args.positionals.first().cloned().unwrap_or_default();
    let run_value = Value::Str(run.clone());
    match command.as_str() {
        "register" => {
            let now = now_utc()?;
            let proof_interval = option_int(&args, "--proof-interval")
                .cloned()
                .unwrap_or(Value::Int(DEFAULT_PROOF_INTERVAL_SECONDS as i128));
            let missed_limit = option_int(&args, "--missed-limit")
                .cloned()
                .unwrap_or(Value::Int(DEFAULT_MISSED_PROOF_LIMIT as i128));
            let soft_ceiling = option_int(&args, "--soft-ceiling")
                .cloned()
                .unwrap_or(Value::Null);
            let hard_ceiling = option_int(&args, "--hard-ceiling")
                .cloned()
                .unwrap_or(Value::Null);
            switch.register(
                &run_value,
                &now,
                &proof_interval,
                &missed_limit,
                &soft_ceiling,
                &hard_ceiling,
            )?;
            print_line(&format!("registered {run}"));
        }
        "prove" => {
            let now = now_utc()?;
            let note = option_text(&args, "--note").unwrap_or("").to_string();
            switch.prove(&run_value, &Value::Str(note), &now)?;
            print_line(&format!("proved {run}"));
        }
        "spend" => {
            let now = now_utc()?;
            let amount = option_int(&args, "--amount").unwrap().clone();
            let total = switch.spend(&run_value, &amount, &now)?;
            print_line(&format!("spend_total {total}"));
        }
        "pull" => {
            let now = now_utc()?;
            let stage = switch.pull(&run_value, &now)?;
            print_line(&format!("stage {stage}"));
        }
        "stage" => {
            let now = now_utc()?;
            stage_command(&switch, &run_value, &now, &args)?;
        }
        "runs" => {
            for summary in switch.runs()? {
                let interval_text = match &summary.proof_interval_seconds {
                    Value::Int(number) => number.to_string(),
                    Value::BigInt(text) => text.clone(),
                    _ => unreachable!(),
                };
                let soft_text = summary
                    .soft_ceiling
                    .map_or_else(|| "none".to_string(), |value| value.to_string());
                let hard_text = summary
                    .hard_ceiling
                    .map_or_else(|| "none".to_string(), |value| value.to_string());
                let last_proof_text = summary.last_proof_at.as_deref().unwrap_or("none");
                print_line(&format!(
                    "{} stage={} killed={} spend_total={} soft_ceiling={} hard_ceiling={} proof_interval_seconds={} missed_proof_limit={} registered_at={} last_proof_at={}",
                    summary.id,
                    summary.stage,
                    summary.killed,
                    summary.spend_total,
                    soft_text,
                    hard_text,
                    interval_text,
                    summary.missed_proof_limit,
                    summary.registered_at,
                    last_proof_text,
                ));
            }
        }
        _ => {
            for record in switch.log(&run_value)? {
                let mut line = format!(
                    "{} {} at={} stage={}",
                    record.seq, record.kind, record.at, record.stage
                );
                for reason in &record.reasons {
                    line.push_str(&format!(" reason={reason}"));
                }
                print_line(&line);
            }
        }
    }
    Ok(ExitCode::from(0))
}

/// The stage command, in its deterministic form and its model
/// form over the one model entry point of DM-20. The command
/// builds at most one transport from its judge options and
/// calls stage_with_model in every case, so the deterministic
/// behaviour is the library no transport case of that call and
/// no second evaluation path stands in the binary. The surface
/// refuses its own malformed shapes before any state changes,
/// in the invalid request class the library refusals of the
/// same conditions take.
fn stage_command(
    switch: &Switch,
    run_value: &Value,
    now: &Instant,
    args: &SubArgs,
) -> Result<(), Error> {
    let judge = option_text(args, "--judge");
    let fixture_file = option_text(args, "--judge-fixture");
    let judge_args = option_list(args, "--judge-arg");
    let judge_timeout = option_int(args, "--judge-timeout");
    let judge_model = option_text(args, "--judge-model");
    let host_context = option_text(args, "--host-context");
    validate_judge_form(
        judge.is_some(),
        fixture_file.is_some(),
        !judge_args.is_empty(),
        judge_timeout.is_some(),
    )?;
    if judge_model.is_some() && judge.is_none() && fixture_file.is_none() {
        return Err(Error::InvalidRequest(
            "a judge model stands named with no judge form to carry it".to_string(),
        ));
    }
    if let Some(model_name) = judge_model {
        validate_model_id(model_name)?;
    }
    let pinned_model = judge_model.unwrap_or(MODEL_NAME);
    let timeout = match judge_timeout {
        Some(value) => Some(judge_timeout_duration(value)?),
        None => None,
    };
    let subprocess_transport;
    let fixture_transport;
    let transport: Option<&dyn ModelTransport> = if let Some(program) = judge {
        subprocess_transport = SubprocessTransport::with_model(
            PathBuf::from(program),
            judge_args.iter().map(|arg| arg.to_string()).collect(),
            timeout.unwrap_or(Duration::from_secs(DEFAULT_JUDGE_TIMEOUT_SECONDS)),
            pinned_model,
        )?;
        Some(&subprocess_transport)
    } else if let Some(path) = fixture_file {
        let body = read_judge_fixture(path)?;
        fixture_transport = FixtureTransport::new(
            pinned_model,
            vec![consultation_from_reply_body(&body, pinned_model)],
        );
        Some(&fixture_transport)
    } else {
        None
    };
    let report = switch.stage_with_model(run_value, now, transport, host_context)?;
    print_line(&format!("stage {}", report.stage));
    for reason in &report.reasons {
        print_line(&format!("reason {reason}"));
    }
    if let Some(lines) = report.appended.as_ref().and_then(consultation_lines) {
        for line in lines {
            print_line(&line);
        }
    }
    Ok(())
}

/// The deadline a judge timeout value names, refused as an
/// invalid request where the value does not stand as a
/// positive number of seconds the transport duration can
/// hold, with the message naming the value and the condition.
/// A value standing at or past the surfaces' whole ceiling
/// refuses without being held, because no surface reads a
/// number it cannot hold to name the value it refuses.
fn judge_timeout_duration(value: &Value) -> Result<Duration, Error> {
    let seconds = match value {
        Value::Int(number) if *number >= 1 && *number <= u64::MAX as i128 => Some(*number as u64),
        _ => None,
    };
    match seconds {
        Some(seconds) => Ok(Duration::from_secs(seconds)),
        None => Err(Error::InvalidRequest(format!(
            "judge timeout {} does not stand as a positive number of seconds the \
             transport can hold",
            timeout_printable(value)
        ))),
    }
}

/// Read the reply body a judge fixture file holds. The file
/// is an input the command must open before any evaluation can
/// stand, so a file that cannot be read is a failure of the
/// command at exit 1 with a message naming the file, and no
/// state changes and no record stands appended. Bytes that
/// stand as no text parse under the reply grammar as no
/// document, in the malformed reply class the grammar states
/// for them.
fn read_judge_fixture(path: &str) -> Result<String, Error> {
    match std::fs::read(path) {
        Ok(bytes) => Ok(String::from_utf8(bytes).unwrap_or_default()),
        Err(err) => Err(Error::Failure(format!(
            "the judge fixture file {} cannot be read, {err}",
            py_repr_str(path)
        ))),
    }
}

/// The consultation lines the stage command prints after its
/// stage and reason lines, read from the record the
/// evaluation handed back in its report, or nothing where
/// that record carries no consultation. Only a consultation
/// record carries a model name, so the model fields of the
/// record are the whole identification, read off the record
/// the evaluation itself appended inside its lock, and no
/// second reading of the state and no reconstruction after
/// the fact stands between the evaluation and its lines.
/// The confidence and the score render by the library float
/// rendering the document writer uses, so the printed
/// numbers and the stored fields cannot disagree.
fn consultation_lines(record: &Record) -> Option<Vec<String>> {
    let model = record.model_name.as_ref()?;
    if let Some(class) = &record.fallback_taken {
        Some(vec![format!("model {model}"), format!("fallback {class}")])
    } else if let Some(verdict) = &record.model_verdict {
        let confidence = record.model_confidence?;
        let score = record.model_score?;
        Some(vec![
            format!("model {model}"),
            format!("verdict {verdict}"),
            format!("confidence {}", py_float_repr(confidence)),
            format!("score {}", py_float_repr(score)),
        ])
    } else {
        None
    }
}

fn main() -> ExitCode {
    run()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_clock_standing_before_the_epoch_answers_the_failure() {
        let read =
            (std::time::UNIX_EPOCH - Duration::from_secs(1)).duration_since(std::time::UNIX_EPOCH);
        assert!(read.is_err());
        let error = instant_from_read(read).unwrap_err();
        assert!(matches!(error, Error::Failure(_)));
        assert_eq!(error.message(), "the system clock stands before the epoch");
        assert_eq!(error.exit_code(), 1);
    }

    #[test]
    fn a_clock_at_or_after_the_epoch_builds_its_instant() {
        let at_epoch = instant_from_read(Ok(Duration::ZERO)).expect("the epoch read builds");
        assert_eq!(at_epoch.epoch_micros(), 0);
        let after =
            instant_from_read(Ok(Duration::from_micros(90_000_000))).expect("a later read builds");
        assert_eq!(after.epoch_micros(), 90_000_000);
    }
}