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
//! The strict document reader.
//!
//! A hand written reader over the document bytes in place of the
//! Python json module, shaped by three contract facts. A repeated
//! key is refused as the key arrives, because a general reader
//! that keeps the last value and says nothing cannot carry DM-8.
//! An integer wider than the machine forms stands as its decimal
//! text, so the DM-9 bounds judge the value Python judged. And
//! the byte decoding detects the same encodings the Python reader
//! detects, by the same first bytes rule.

use std::collections::HashSet;

use crate::value::Value;
use crate::{INT_DIGIT_LIMIT, MAX_NESTING};

pub(crate) enum ParseFailure {
    /// The document does not parse, with detail text from this
    /// reader standing after the shared message head.
    Syntax(String),
    /// A key stands twice in one object, named by the key.
    DuplicateKey(String),
}

pub(crate) fn parse_document(bytes: &[u8]) -> std::result::Result<Value, ParseFailure> {
    let text = decode_document_bytes(bytes).map_err(ParseFailure::Syntax)?;
    let mut parser = Parser {
        chars: text.chars().collect(),
        pos: 0,
        depth: 0,
    };
    let value = parser.parse_value()?;
    parser.skip_whitespace();
    if parser.pos != parser.chars.len() {
        return Err(ParseFailure::Syntax(format!(
            "trailing text stands after the document at character {}",
            parser.pos
        )));
    }
    Ok(value)
}

/// Decode document bytes to text the way the Python json module
/// decoded them, detecting a byte order mark and the null byte
/// patterns of mark free UTF-16 and UTF-32, and refusing what
/// does not decode.
fn decode_document_bytes(bytes: &[u8]) -> std::result::Result<String, String> {
    if bytes.starts_with(&[0xff, 0xfe, 0x00, 0x00]) {
        decode_utf32(&bytes[4..], true)
    } else if bytes.starts_with(&[0x00, 0x00, 0xfe, 0xff]) {
        decode_utf32(&bytes[4..], false)
    } else if bytes.starts_with(&[0xff, 0xfe]) {
        decode_utf16(&bytes[2..], true)
    } else if bytes.starts_with(&[0xfe, 0xff]) {
        decode_utf16(&bytes[2..], false)
    } else if bytes.starts_with(&[0xef, 0xbb, 0xbf]) {
        decode_utf8(&bytes[3..])
    } else if bytes.len() >= 4 {
        if bytes[0] == 0 {
            if bytes[1] == 0 {
                decode_utf32(bytes, false)
            } else {
                decode_utf16(bytes, false)
            }
        } else if bytes[1] == 0 {
            if bytes[2] == 0 && bytes[3] == 0 {
                decode_utf32(bytes, true)
            } else {
                decode_utf16(bytes, true)
            }
        } else {
            decode_utf8(bytes)
        }
    } else if bytes.len() >= 2 {
        if bytes[0] == 0 {
            decode_utf16(bytes, false)
        } else if bytes[1] == 0 {
            decode_utf16(bytes, true)
        } else {
            decode_utf8(bytes)
        }
    } else {
        decode_utf8(bytes)
    }
}

fn decode_utf8(bytes: &[u8]) -> std::result::Result<String, String> {
    String::from_utf8(bytes.to_vec())
        .map_err(|err| format!("the document does not decode as UTF-8, {err}"))
}

fn decode_utf16(bytes: &[u8], little_endian: bool) -> std::result::Result<String, String> {
    if !bytes.len().is_multiple_of(2) {
        return Err("the document does not decode as UTF-16".to_string());
    }
    let units: Vec<u16> = bytes
        .chunks(2)
        .map(|pair| {
            if little_endian {
                (pair[0] as u16) | ((pair[1] as u16) << 8)
            } else {
                ((pair[0] as u16) << 8) | pair[1] as u16
            }
        })
        .collect();
    // An unpaired surrogate decodes to the replacement character
    // here, where the Python decoder holds the surrogate itself.
    // Every field such a character can stand in is refused by the
    // reading validation of both implementations, the difference
    // the port amendment records for surrogate escapes.
    Ok(char::decode_utf16(units)
        .map(|decoded| decoded.unwrap_or(char::REPLACEMENT_CHARACTER))
        .collect())
}

fn decode_utf32(bytes: &[u8], little_endian: bool) -> std::result::Result<String, String> {
    if !bytes.len().is_multiple_of(4) {
        return Err("the document does not decode as UTF-32".to_string());
    }
    let mut out = String::new();
    for group in bytes.chunks(4) {
        let code = if little_endian {
            (group[0] as u32)
                | ((group[1] as u32) << 8)
                | ((group[2] as u32) << 16)
                | ((group[3] as u32) << 24)
        } else {
            ((group[0] as u32) << 24)
                | ((group[1] as u32) << 16)
                | ((group[2] as u32) << 8)
                | group[3] as u32
        };
        match char::from_u32(code) {
            Some(ch) => out.push(ch),
            None => return Err("the document does not decode as UTF-32".to_string()),
        }
    }
    Ok(out)
}

struct Parser {
    chars: Vec<char>,
    pos: usize,
    depth: usize,
}

impl Parser {
    fn peek(&self) -> Option<char> {
        self.chars.get(self.pos).copied()
    }

    fn syntax(&self, detail: &str) -> ParseFailure {
        ParseFailure::Syntax(format!("{detail} at character {}", self.pos))
    }

    fn skip_whitespace(&mut self) {
        while matches!(self.peek(), Some(' ' | '\t' | '\n' | '\r')) {
            self.pos += 1;
        }
    }

    fn parse_value(&mut self) -> std::result::Result<Value, ParseFailure> {
        self.skip_whitespace();
        match self.peek() {
            Some('{') => self.parse_object(),
            Some('[') => self.parse_array(),
            Some('"') => Ok(Value::Str(self.parse_string()?)),
            Some('t') => self.parse_literal("true", Value::Bool(true)),
            Some('f') => self.parse_literal("false", Value::Bool(false)),
            Some('n') => self.parse_literal("null", Value::Null),
            Some('N') => self.parse_literal("NaN", Value::Float(f64::NAN)),
            Some('I') => self.parse_literal("Infinity", Value::Float(f64::INFINITY)),
            Some('-') => {
                if self.chars.get(self.pos + 1) == Some(&'I') {
                    self.pos += 1;
                    self.parse_literal("Infinity", Value::Float(f64::NEG_INFINITY))
                } else {
                    self.parse_number()
                }
            }
            Some(ch) if ch.is_ascii_digit() => self.parse_number(),
            _ => Err(self.syntax("a value stands expected here")),
        }
    }

    fn parse_literal(
        &mut self,
        text: &str,
        value: Value,
    ) -> std::result::Result<Value, ParseFailure> {
        // The literal stands compared character by character
        // against the input ahead of the cursor, with no
        // collection built for the comparison. The literals of
        // this grammar are plain ASCII, so the character count
        // the comparison advances is the byte count the
        // position has always advanced by.
        let matched = text
            .chars()
            .zip(self.chars[self.pos..].iter())
            .take_while(|(want, have)| want == *have)
            .count();
        if matched == text.chars().count() {
            self.pos += matched;
            Ok(value)
        } else {
            Err(self.syntax("a value stands expected here"))
        }
    }

    fn parse_number(&mut self) -> std::result::Result<Value, ParseFailure> {
        let start = self.pos;
        if self.peek() == Some('-') {
            self.pos += 1;
        }
        // The integer part is one zero or a nonzero digit and its
        // run, the grammar the Python reader accepts.
        match self.peek() {
            Some('0') => {
                self.pos += 1;
            }
            Some(ch) if ch.is_ascii_digit() => {
                while matches!(self.peek(), Some(ch) if ch.is_ascii_digit()) {
                    self.pos += 1;
                }
            }
            _ => return Err(self.syntax("a number stands malformed here")),
        }
        let mut is_float = false;
        if self.peek() == Some('.') {
            is_float = true;
            self.pos += 1;
            if !matches!(self.peek(), Some(ch) if ch.is_ascii_digit()) {
                return Err(self.syntax("a number stands malformed here"));
            }
            while matches!(self.peek(), Some(ch) if ch.is_ascii_digit()) {
                self.pos += 1;
            }
        }
        if matches!(self.peek(), Some('e' | 'E')) {
            is_float = true;
            self.pos += 1;
            if matches!(self.peek(), Some('+' | '-')) {
                self.pos += 1;
            }
            if !matches!(self.peek(), Some(ch) if ch.is_ascii_digit()) {
                return Err(self.syntax("a number stands malformed here"));
            }
            while matches!(self.peek(), Some(ch) if ch.is_ascii_digit()) {
                self.pos += 1;
            }
        }
        let literal: String = self.chars[start..self.pos].iter().collect();
        if is_float {
            return literal
                .parse::<f64>()
                .map(Value::Float)
                .map_err(|_| self.syntax("a number stands malformed here"));
        }
        let digits = literal.trim_start_matches('-');
        if digits.len() > INT_DIGIT_LIMIT {
            return Err(ParseFailure::Syntax(format!(
                "the integer literal of {} digits exceeds the parse limit of {INT_DIGIT_LIMIT} digits",
                digits.len()
            )));
        }
        if literal == "-0" {
            return Ok(Value::Int(0));
        }
        match literal.parse::<i128>() {
            Ok(value) => Ok(Value::Int(value)),
            Err(_) => Ok(Value::BigInt(literal)),
        }
    }

    fn parse_string(&mut self) -> std::result::Result<String, ParseFailure> {
        // The caller has seen the opening quote.
        self.pos += 1;
        let mut out = String::new();
        loop {
            let ch = match self.peek() {
                Some(ch) => ch,
                None => return Err(self.syntax("a string stands unterminated")),
            };
            self.pos += 1;
            match ch {
                '"' => return Ok(out),
                '\\' => {
                    let escape = match self.peek() {
                        Some(ch) => ch,
                        None => return Err(self.syntax("a string stands unterminated")),
                    };
                    self.pos += 1;
                    match escape {
                        '"' => out.push('"'),
                        '\\' => out.push('\\'),
                        '/' => out.push('/'),
                        'b' => out.push('\u{0008}'),
                        'f' => out.push('\u{000c}'),
                        'n' => out.push('\n'),
                        'r' => out.push('\r'),
                        't' => out.push('\t'),
                        'u' => {
                            let unit = self.parse_hex_unit()?;
                            if (0xd800..0xdc00).contains(&unit) {
                                // A high surrogate. A low surrogate
                                // escape following it combines, and
                                // anything else leaves the replacement
                                // character standing for the unpaired
                                // half, where the Python reader holds
                                // the surrogate itself. The port
                                // amendment records the difference.
                                if self.peek() == Some('\\')
                                    && self.chars.get(self.pos + 1) == Some(&'u')
                                {
                                    self.pos += 2;
                                    let low = self.parse_hex_unit()?;
                                    if (0xdc00..0xe000).contains(&low) {
                                        let combined = 0x10000
                                            + (((unit as u32 - 0xd800) << 10)
                                                + (low as u32 - 0xdc00));
                                        out.push(
                                            char::from_u32(combined)
                                                .unwrap_or(char::REPLACEMENT_CHARACTER),
                                        );
                                    } else {
                                        out.push(char::REPLACEMENT_CHARACTER);
                                        out.push(
                                            char::from_u32(low as u32)
                                                .unwrap_or(char::REPLACEMENT_CHARACTER),
                                        );
                                    }
                                } else {
                                    out.push(char::REPLACEMENT_CHARACTER);
                                }
                            } else {
                                out.push(
                                    char::from_u32(unit as u32)
                                        .unwrap_or(char::REPLACEMENT_CHARACTER),
                                );
                            }
                        }
                        _ => return Err(self.syntax("a string escape stands unknown")),
                    }
                }
                ch if (ch as u32) < 0x20 => {
                    return Err(self.syntax("a string holds a raw control character"));
                }
                ch => out.push(ch),
            }
        }
    }

    fn parse_hex_unit(&mut self) -> std::result::Result<u16, ParseFailure> {
        let mut value: u16 = 0;
        for _ in 0..4 {
            let ch = match self.peek() {
                Some(ch) => ch,
                None => return Err(self.syntax("a string escape stands short")),
            };
            let digit = match ch.to_digit(16) {
                Some(digit) => digit as u16,
                None => return Err(self.syntax("a string escape holds a non hex digit")),
            };
            value = value * 16 + digit;
            self.pos += 1;
        }
        Ok(value)
    }

    fn parse_array(&mut self) -> std::result::Result<Value, ParseFailure> {
        self.depth += 1;
        if self.depth > MAX_NESTING {
            return Err(self.syntax("the document nests past the depth the reader reads"));
        }
        self.pos += 1;
        let mut items = Vec::new();
        self.skip_whitespace();
        if self.peek() == Some(']') {
            self.pos += 1;
            self.depth -= 1;
            return Ok(Value::Array(items));
        }
        loop {
            let item = self.parse_value()?;
            items.push(item);
            self.skip_whitespace();
            match self.peek() {
                Some(',') => {
                    self.pos += 1;
                }
                Some(']') => {
                    self.pos += 1;
                    self.depth -= 1;
                    return Ok(Value::Array(items));
                }
                _ => return Err(self.syntax("an array stands unterminated")),
            }
        }
    }

    fn parse_object(&mut self) -> std::result::Result<Value, ParseFailure> {
        self.depth += 1;
        if self.depth > MAX_NESTING {
            return Err(self.syntax("the document nests past the depth the reader reads"));
        }
        self.pos += 1;
        let mut pairs: Vec<(String, Value)> = Vec::new();
        self.skip_whitespace();
        if self.peek() == Some('}') {
            self.pos += 1;
            self.depth -= 1;
            return Ok(Value::Object(pairs));
        }
        loop {
            self.skip_whitespace();
            if self.peek() != Some('"') {
                return Err(self.syntax("an object key stands expected here"));
            }
            let key = self.parse_string()?;
            self.skip_whitespace();
            if self.peek() != Some(':') {
                return Err(self.syntax("an object colon stands expected here"));
            }
            self.pos += 1;
            let value = self.parse_value()?;
            pairs.push((key, value));
            self.skip_whitespace();
            match self.peek() {
                Some(',') => {
                    self.pos += 1;
                }
                Some('}') => {
                    self.pos += 1;
                    self.depth -= 1;
                    // The duplicate check runs as the object
                    // completes, the moment the Python reader's
                    // pairs hook runs, so the key named is the
                    // first repeated key of the innermost object
                    // that completes with one.
                    let mut seen: HashSet<&str> = HashSet::new();
                    for (key, _) in &pairs {
                        if !seen.insert(key.as_str()) {
                            return Err(ParseFailure::DuplicateKey(key.clone()));
                        }
                    }
                    return Ok(Value::Object(pairs));
                }
                _ => return Err(self.syntax("an object stands unterminated")),
            }
        }
    }
}