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
//! Tool-argument repair.
//!
//! The crate does not know about Bline errors, chat requests, or the tool
//! catalog. Callers pass the raw argument string and, when they have it,
//! the tool's JSON schema.

mod salvage;
mod schema;
mod syntax;

use serde_json::Value;

pub use schema::normalize;

/// Result of [`repair_json`].
#[derive(Debug, Clone, PartialEq)]
pub enum RepairOutcome {
    /// The input parsed. Nothing was rewritten.
    Valid(Value),
    /// The input was rewritten and then parsed.
    Repaired { value: Value, repairs: Vec<Rewrite> },
    /// The input is not JSON this crate can salvage.
    Unfixable(String),
    /// More than one repair was possible, so nothing was chosen.
    Ambiguous(String),
}

/// One recorded rewrite. Valid JSON that needs no schema change has none.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Rewrite {
    pub kind: RewriteKind,
    pub detail: String,
}

/// Why a rewrite was applied.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RewriteKind {
    Syntax,
    Fence,
    ClosedTruncation,
    XmlParameters,
    Alias,
    BoolString,
    NumberString,
    DroppedUnknown,
    Empty,
}

/// Arguments plus an optional JSON schema.
#[derive(Debug, Clone, Copy)]
pub struct RepairRequest<'a> {
    pub tool_name: &'a str,
    pub raw: &'a str,
    pub schema: Option<&'a Value>,
}

/// A value the host can execute, with every rewrite that produced it.
#[derive(Debug, Clone, PartialEq)]
pub struct Repaired {
    pub value: Value,
    pub rewrites: Vec<Rewrite>,
}

/// Repair refused. [`RepairError::Ambiguous`] is not a guess.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum RepairError {
    #[error("{0}")]
    Unfixable(String),
    #[error("{0}")]
    Ambiguous(String),
}

/// Syntax repair only. Empty input and garbage stay [`RepairOutcome::Unfixable`].
///
/// A repeated XML parameter name is [`RepairOutcome::Ambiguous`].
pub fn repair_json(raw: &str) -> RepairOutcome {
    match salvage_value(raw) {
        Ok((value, repairs)) if repairs.is_empty() => RepairOutcome::Valid(value),
        Ok((value, repairs)) => RepairOutcome::Repaired { value, repairs },
        Err(RepairError::Unfixable(reason)) => RepairOutcome::Unfixable(reason),
        Err(RepairError::Ambiguous(reason)) => RepairOutcome::Ambiguous(reason),
    }
}

fn salvage_value(raw: &str) -> Result<(Value, Vec<Rewrite>), RepairError> {
    if let Ok(value) = serde_json::from_str(raw) {
        return Ok((value, Vec::new()));
    }

    let mut prefix = Vec::new();
    let mut body = raw.to_string();
    if let Some(inner) = salvage::unwrap_fence(raw) {
        prefix.push(note(RewriteKind::Fence, "unwrapped markdown fence"));
        body = inner;
        if let Ok(value) = serde_json::from_str(&body) {
            return Ok((value, prefix));
        }
    }

    if prefix.is_empty() {
        match syntax::repair_tool_call_json(raw) {
            RepairOutcome::Valid(value) => return Ok((value, Vec::new())),
            RepairOutcome::Repaired { value, repairs } => return Ok((value, repairs)),
            RepairOutcome::Unfixable(_) | RepairOutcome::Ambiguous(_) => {}
        }
    }

    let staged = syntax::apply_stages(&body);
    let parse_error = match serde_json::from_str::<Value>(&staged.text) {
        Ok(value) => {
            prefix.extend(staged.repairs);
            return Ok((value, prefix));
        }
        Err(err) => err,
    };

    if let Some(closed) = salvage::close_truncated(&staged.text)
        && let Ok(value) = serde_json::from_str::<Value>(&closed)
    {
        prefix.extend(staged.repairs);
        prefix.push(note(RewriteKind::ClosedTruncation, "closed truncated json"));
        return Ok((value, prefix));
    }

    match salvage::xml_parameters(&body)? {
        Some(value) => {
            prefix.push(note(RewriteKind::XmlParameters, "read xml parameters"));
            Ok((value, prefix))
        }
        None => Err(RepairError::Unfixable(format!(
            "parse failed after all repairs: {parse_error}"
        ))),
    }
}

fn note(kind: RewriteKind, detail: &str) -> Rewrite {
    Rewrite {
        kind,
        detail: detail.to_string(),
    }
}

/// Parse `raw`, then apply [`normalize`] when a schema is present.
///
/// Empty input is `{}`.
pub fn repair_args(request: &RepairRequest<'_>) -> Result<Repaired, RepairError> {
    if request.raw.is_empty() {
        let value = Value::Object(serde_json::Map::new());
        let mut repaired = Repaired {
            value,
            rewrites: vec![Rewrite {
                kind: RewriteKind::Empty,
                detail: "empty input is {}".into(),
            }],
        };
        if let Some(schema) = request.schema {
            let normalized = normalize(&repaired.value, schema)?;
            repaired.value = normalized.value;
            repaired.rewrites.extend(normalized.rewrites);
        }
        return Ok(repaired);
    }

    let (value, mut rewrites) = match salvage_value(request.raw) {
        Ok(parsed) => parsed,
        Err(err) => return Err(named(request.tool_name, err)),
    };
    if let Some(schema) = request.schema {
        let normalized = normalize(&value, schema).map_err(|err| named(request.tool_name, err))?;
        rewrites.extend(normalized.rewrites);
        return Ok(Repaired {
            value: normalized.value,
            rewrites,
        });
    }
    Ok(Repaired { value, rewrites })
}

fn named(tool_name: &str, err: RepairError) -> RepairError {
    if tool_name.is_empty() {
        return err;
    }
    let reason = err.to_string();
    let text = format!("tool '{tool_name}': {reason}");
    match err {
        RepairError::Unfixable(_) => RepairError::Unfixable(text),
        RepairError::Ambiguous(_) => RepairError::Ambiguous(text),
    }
}

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

    #[test]
    fn fence_then_bare_key() {
        let raw = "```json\n{file: \"a.rs\"}\n```";
        match repair_json(raw) {
            RepairOutcome::Repaired { value, repairs } => {
                assert_eq!(value["file"], "a.rs");
                assert!(
                    repairs.iter().any(|item| item.kind == RewriteKind::Fence),
                    "{repairs:?}"
                );
            }
            other => panic!("expected Repaired, got {other:?}"),
        }
    }

    #[test]
    fn truncated_object_closes() {
        match repair_json(r#"{"file": "a.rs""#) {
            RepairOutcome::Repaired { value, repairs } => {
                assert_eq!(value["file"], "a.rs");
                assert!(
                    repairs
                        .iter()
                        .any(|item| item.kind == RewriteKind::ClosedTruncation)
                );
            }
            other => panic!("expected Repaired, got {other:?}"),
        }
    }

    #[test]
    fn open_string_stays_unfixable() {
        assert!(matches!(
            repair_json("{\"path\": \"src/mai"),
            RepairOutcome::Unfixable(_)
        ));
    }

    #[test]
    fn missing_value_stays_unfixable() {
        assert!(matches!(
            repair_json(r#"{"file":"#),
            RepairOutcome::Unfixable(_)
        ));
    }

    #[test]
    fn xml_bare_scalars_stay_strings() {
        let truth = repair_json(r#"<parameter name="file">true</parameter>"#);
        let number = repair_json(r#"<parameter name="file">1</parameter>"#);
        match (truth, number) {
            (
                RepairOutcome::Repaired { value: left, .. },
                RepairOutcome::Repaired { value: right, .. },
            ) => {
                assert_eq!(left["file"], "true");
                assert_eq!(right["file"], "1");
            }
            other => panic!("expected both repaired, got {other:?}"),
        }
    }

    #[test]
    fn xml_containers_still_parse() {
        let raw = r#"<parameter name="meta">{"ok":true}</parameter><parameter name="items">[1]</parameter><parameter name="note">"quoted"</parameter>"#;
        match repair_json(raw) {
            RepairOutcome::Repaired { value, .. } => {
                assert_eq!(value["meta"]["ok"], true);
                assert_eq!(value["items"][0], 1);
                assert_eq!(value["note"], "quoted");
            }
            other => panic!("expected Repaired, got {other:?}"),
        }
    }

    #[test]
    fn xml_boolean_string_coerces_when_the_schema_says_boolean() {
        let schema = json!({"type": "object", "properties": {"force": {"type": "boolean"}}});
        let repaired = repair_args(&RepairRequest {
            tool_name: "edit_file",
            raw: r#"<parameter name="force">true</parameter>"#,
            schema: Some(&schema),
        })
        .expect("schema coerce");
        assert_eq!(repaired.value["force"], true);
    }

    #[test]
    fn xml_parameter_forms() {
        let named = repair_json(r#"<parameter name="dirPath">src</parameter>"#);
        let equals = repair_json(r#"<parameter=dirPath>src</parameter>"#);
        match (named, equals) {
            (
                RepairOutcome::Repaired { value: left, .. },
                RepairOutcome::Repaired { value: right, .. },
            ) => {
                assert_eq!(left["dirPath"], "src");
                assert_eq!(right["dirPath"], "src");
            }
            other => panic!("expected both repaired, got {other:?}"),
        }
    }

    #[test]
    fn repeated_xml_parameter_is_ambiguous() {
        let raw = r#"<parameter name="file">a</parameter><parameter name="file">b</parameter>"#;
        let err = repair_args(&RepairRequest {
            tool_name: "edit_file",
            raw,
            schema: None,
        })
        .unwrap_err();
        assert!(matches!(err, RepairError::Ambiguous(_)), "{err:?}");
        assert!(matches!(repair_json(raw), RepairOutcome::Ambiguous(_)));
    }

    #[test]
    fn trailing_text_after_xml_parameters_is_unfixable() {
        let raw = r#"<parameter name="file">a.rs</parameter> leftover"#;
        assert!(matches!(repair_json(raw), RepairOutcome::Unfixable(_)));
        let between = r#"<parameter name="a">1</parameter> junk <parameter name="b">2</parameter>"#;
        assert!(matches!(repair_json(between), RepairOutcome::Unfixable(_)));
    }

    #[test]
    fn whitespace_after_xml_parameters_is_kept() {
        let raw = "<parameter name=\"file\">a.rs</parameter>\n";
        match repair_json(raw) {
            RepairOutcome::Repaired { value, .. } => assert_eq!(value["file"], "a.rs"),
            other => panic!("expected Repaired, got {other:?}"),
        }
    }

    #[test]
    fn unfixable_json_keeps_the_serde_error() {
        match repair_json("garbage") {
            RepairOutcome::Unfixable(reason) => {
                assert!(
                    reason.starts_with("parse failed after all repairs:"),
                    "{reason}"
                );
                assert!(reason.contains("expected"), "{reason}");
            }
            other => panic!("expected Unfixable, got {other:?}"),
        }
    }

    #[test]
    fn parameter_tag_inside_prose_is_not_xml() {
        let raw = "not json <parameter name=\"file\">a</parameter>";
        assert!(matches!(repair_json(raw), RepairOutcome::Unfixable(_)));
    }

    #[test]
    fn path_alias_renames_to_schema_property() {
        let schema = json!({"type": "object", "properties": {"file": {"type": "string"}}});
        let repaired = repair_args(&RepairRequest {
            tool_name: "edit_file",
            raw: r#"{"path": "a.rs"}"#,
            schema: Some(&schema),
        })
        .expect("alias");
        assert_eq!(repaired.value["file"], "a.rs");
        assert!(
            repaired
                .rewrites
                .iter()
                .any(|item| item.kind == RewriteKind::Alias)
        );
    }

    #[test]
    fn two_path_properties_are_ambiguous() {
        let schema = json!({
            "type": "object",
            "properties": {
                "file": {"type": "string"},
                "path": {"type": "string"}
            }
        });
        let err = normalize(&json!({"filepath": "a.rs"}), &schema).unwrap_err();
        assert!(matches!(err, RepairError::Ambiguous(_)));
    }

    #[test]
    fn boolean_and_integer_strings() {
        let schema = json!({
            "type": "object",
            "properties": {
                "force": {"type": "boolean"},
                "line": {"type": "integer"}
            }
        });
        let repaired = normalize(&json!({"force": "true", "line": "3"}), &schema).expect("coerce");
        assert_eq!(repaired.value["force"], true);
        assert_eq!(repaired.value["line"], 3);
    }

    #[test]
    fn two_unknown_keys_are_refused() {
        let schema = json!({
            "type": "object",
            "additionalProperties": false,
            "properties": {"file": {"type": "string"}},
            "required": ["file"]
        });
        let err = normalize(&json!({"file": "a.rs", "a": 1, "b": 2}), &schema).unwrap_err();
        assert!(matches!(err, RepairError::Ambiguous(_)));
    }

    #[test]
    fn one_unknown_key_is_dropped_when_required_is_present() {
        let schema = json!({
            "type": "object",
            "additionalProperties": false,
            "properties": {"file": {"type": "string"}},
            "required": ["file"]
        });
        let repaired = normalize(&json!({"file": "a.rs", "note": "x"}), &schema).expect("drop");
        assert!(repaired.value.get("note").is_none());
        assert_eq!(repaired.value["file"], "a.rs");
    }

    #[test]
    fn valid_json_without_schema_is_not_rewritten() {
        let repaired = repair_args(&RepairRequest {
            tool_name: "edit_file",
            raw: r#"{"path": "a.rs"}"#,
            schema: None,
        })
        .expect("valid");
        assert!(repaired.rewrites.is_empty());
        assert_eq!(repaired.value["path"], "a.rs");
    }

    #[test]
    fn garbage_stays_unfixable() {
        assert!(matches!(
            repair_json("this is not json at all }{[]"),
            RepairOutcome::Unfixable(_)
        ));
        assert!(matches!(repair_json(""), RepairOutcome::Unfixable(_)));
    }
}