multi-llm 1.0.0

Unified multi-provider LLM client with support for OpenAI, Anthropic, Ollama, and LMStudio
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
//! Unit Tests for Custom Tool Call Format Parser
//!
//! UNIT UNDER TEST: CustomFormatParser
//!
//! BUSINESS RESPONSIBILITY:
//!   - Parse 5 different custom tool call formats from model responses
//!   - Extract function name and arguments from each format
//!   - Clean content by removing tool call markers
//!   - Handle malformed JSON with repair attempts
//!   - Support formats: GPT-OSS v1, XML tool_call, DeepSeek TOOL_REQUEST, tool_call_with_args, JSON-only
//!
//! TEST COVERAGE:
//!   - Each of the 5 format patterns (happy path)
//!   - No match scenarios
//!   - Malformed JSON handling
//!   - Content cleaning (removing tool call markers)
//!   - Edge cases: empty content, nested JSON, incomplete tool calls

use super::super::utils::CustomFormatParser;

// ============================================================================
// Parser Initialization Tests
// ============================================================================

#[test]
fn test_parser_initializes_successfully() {
    // Test verifies parser initializes without panicking
    // Critical: All patterns must compile successfully

    let _parser = CustomFormatParser::new();
    // If we get here, parser initialized successfully
}

#[test]
fn test_parser_default_initializes() {
    // Test verifies Default trait implementation works
    // Ensures consistent initialization

    let _parser1 = CustomFormatParser::new();
    let _parser2 = CustomFormatParser::default();
    // Both should initialize without panicking
}

// ============================================================================
// GPT-OSS v1 Format Tests
// ============================================================================

#[test]
fn test_parse_gpt_oss_v1_format() {
    // Test verifies GPT-OSS v1 format parsing
    // Format: commentary to=functions.FUNC_NAME <|constrain|>json<|message|>{...}

    let parser = CustomFormatParser::new();
    let content = r#"commentary to=functions.get_weather <|constrain|>json<|message|>{"city": "London", "units": "celsius"}"#;

    let result = parser.parse(content).unwrap();
    assert!(result.is_some(), "Should parse GPT-OSS v1 format");

    let match_result = result.unwrap();
    assert_eq!(match_result.function_name, "get_weather");
    assert_eq!(match_result.arguments["city"], "London");
    assert_eq!(match_result.arguments["units"], "celsius");
}

#[test]
fn test_parse_gpt_oss_v1_with_text_around() {
    // Test verifies GPT-OSS format embedded in text is parsed
    // Content before/after the tool call should be preserved in cleaned_content

    let parser = CustomFormatParser::new();
    let content = r#"Let me check the weather. commentary to=functions.get_weather <|constrain|>json<|message|>{"city": "NYC"} I'll get that for you."#;

    let result = parser.parse(content).unwrap();
    assert!(result.is_some());

    let match_result = result.unwrap();
    assert_eq!(match_result.function_name, "get_weather");
    assert!(match_result.cleaned_content.contains("Let me check"));
    assert!(match_result.cleaned_content.contains("I'll get that"));
}

// ============================================================================
// XML Tool Call Format Tests (Qwen models)
// ============================================================================

#[test]
fn test_parse_xml_tool_call_format() {
    // Test verifies XML <tool_call> format parsing
    // Format: <tool_call>{"name": "func", "arguments": {...}}</tool_call>

    let parser = CustomFormatParser::new();
    let content = r#"<tool_call>{"name": "search", "arguments": {"query": "rust"}}</tool_call>"#;

    let result = parser.parse(content).unwrap();
    assert!(result.is_some(), "Should parse XML tool_call format");

    let match_result = result.unwrap();
    assert_eq!(match_result.function_name, "search");
    assert_eq!(match_result.arguments["query"], "rust");
    assert!(
        match_result.cleaned_content.is_empty(),
        "Content should be cleaned"
    );
}

#[test]
fn test_parse_xml_tool_call_without_closing_tag() {
    // Test verifies XML format without closing tag is handled
    // Some models don't include </tool_call>

    let parser = CustomFormatParser::new();
    let content =
        r#"<tool_call>{"name": "calculator", "arguments": {"operation": "add", "a": 5, "b": 3}}"#;

    let result = parser.parse(content).unwrap();
    assert!(result.is_some(), "Should parse XML without closing tag");

    let match_result = result.unwrap();
    assert_eq!(match_result.function_name, "calculator");
    assert_eq!(match_result.arguments["operation"], "add");
}

#[test]
fn test_parse_xml_tool_call_multiline() {
    // Test verifies XML format across multiple lines
    // (?s) flag in regex should handle newlines

    let parser = CustomFormatParser::new();
    let content = r#"<tool_call>
{
  "name": "get_user",
  "arguments": {
    "user_id": 123
  }
}
</tool_call>"#;

    let result = parser.parse(content).unwrap();
    assert!(result.is_some(), "Should parse multiline XML");

    let match_result = result.unwrap();
    assert_eq!(match_result.function_name, "get_user");
    assert_eq!(match_result.arguments["user_id"], 123);
}

// ============================================================================
// DeepSeek TOOL_REQUEST Format Tests
// ============================================================================

#[test]
fn test_parse_deepseek_tool_request_format() {
    // Test verifies DeepSeek [TOOL_REQUEST] format parsing
    // Format: [TOOL_REQUEST]{"name": "func", "arguments": {...}}[END_TOOL_REQUEST]

    let parser = CustomFormatParser::new();
    let content = r#"[TOOL_REQUEST]{"name": "file_read", "arguments": {"path": "/tmp/file.txt"}}[END_TOOL_REQUEST]"#;

    let result = parser.parse(content).unwrap();
    assert!(
        result.is_some(),
        "Should parse DeepSeek TOOL_REQUEST format"
    );

    let match_result = result.unwrap();
    assert_eq!(match_result.function_name, "file_read");
    assert_eq!(match_result.arguments["path"], "/tmp/file.txt");
}

#[test]
fn test_parse_deepseek_with_surrounding_text() {
    // Test verifies DeepSeek format with text before/after

    let parser = CustomFormatParser::new();
    let content = r#"I'll read the file now. [TOOL_REQUEST]{"name": "read", "arguments": {"file": "data.json"}}[END_TOOL_REQUEST] Done."#;

    let result = parser.parse(content).unwrap();
    assert!(result.is_some());

    let match_result = result.unwrap();
    assert_eq!(match_result.function_name, "read");
    assert!(match_result.cleaned_content.contains("I'll read"));
    assert!(match_result.cleaned_content.contains("Done"));
}

// ============================================================================
// Tool Call With Args Format Tests
// ============================================================================

#[test]
fn test_parse_tool_call_with_args_format() {
    // Test verifies "Tool call: func with args: {...}" format
    // Self-generated format from structured content

    let parser = CustomFormatParser::new();
    let content = r#"Tool call: calculate with args: {"x": 10, "y": 20}"#;

    let result = parser.parse(content).unwrap();
    assert!(result.is_some(), "Should parse tool_call_with_args format");

    let match_result = result.unwrap();
    assert_eq!(match_result.function_name, "calculate");
    assert_eq!(match_result.arguments["x"], 10);
    assert_eq!(match_result.arguments["y"], 20);
}

// ============================================================================
// JSON-Only Format Tests
// ============================================================================

#[test]
fn test_parse_json_only_format() {
    // Test verifies bare JSON format
    // Format: {"name": "func", "arguments": {...}} (isolated)
    // Note: This pattern is very restrictive and may not match in practice

    let parser = CustomFormatParser::new();
    let content =
        r#"{"name": "send_email", "arguments": {"to": "user@example.com", "subject": "Hello"}}"#;

    let result = parser.parse(content).unwrap();
    // JSON-only pattern is very strict, may not match complex nested objects
    // If it doesn't match, that's expected behavior - other patterns should catch it
    if let Some(match_result) = result {
        assert_eq!(match_result.function_name, "send_email");
        assert_eq!(match_result.arguments["to"], "user@example.com");
    }
    // Either matches or doesn't - both are valid outcomes for this edge case pattern
}

// ============================================================================
// No Match Tests
// ============================================================================

#[test]
fn test_parse_returns_none_for_plain_text() {
    // Test verifies plain text without tool calls returns None
    // No pattern should match regular conversation

    let parser = CustomFormatParser::new();
    let content = "This is just a regular response with no tool calls.";

    let result = parser.parse(content).unwrap();
    assert!(result.is_none(), "Plain text should not match any pattern");
}

#[test]
fn test_parse_returns_none_for_empty_string() {
    // Test verifies empty content returns None
    // Edge case: empty model response

    let parser = CustomFormatParser::new();
    let content = "";

    let result = parser.parse(content).unwrap();
    assert!(result.is_none(), "Empty string should not match");
}

#[test]
fn test_parse_returns_none_for_incomplete_format() {
    // Test verifies incomplete formats don't match
    // Ensures robust pattern matching

    let parser = CustomFormatParser::new();
    let content = "<tool_call>incomplete json";

    let result = parser.parse(content);
    // Should either return None or error, both acceptable
    assert!(result.is_err() || result.unwrap().is_none());
}

// ============================================================================
// Error Handling Tests
// ============================================================================

#[test]
fn test_parse_handles_invalid_json() {
    // Test verifies invalid JSON produces appropriate error
    // Parser should fail gracefully on malformed JSON

    let parser = CustomFormatParser::new();
    let content = r#"<tool_call>{"name": "func", "arguments": {invalid json}}</tool_call>"#;

    let result = parser.parse(content);
    // Should return error or None if repair fails
    assert!(result.is_err() || result.unwrap().is_none());
}

#[test]
fn test_parse_handles_missing_name_field() {
    // Test verifies missing 'name' field produces error
    // Tool calls must have function name

    let parser = CustomFormatParser::new();
    let content = r#"<tool_call>{"arguments": {"x": 1}}</tool_call>"#;

    let result = parser.parse(content);
    assert!(result.is_err(), "Should error on missing 'name' field");
}

#[test]
fn test_parse_handles_missing_arguments_field() {
    // Test verifies missing 'arguments' field produces error
    // Tool calls must have arguments (even if empty object)

    let parser = CustomFormatParser::new();
    let content = r#"<tool_call>{"name": "test_func"}</tool_call>"#;

    let result = parser.parse(content);
    assert!(result.is_err(), "Should error on missing 'arguments' field");
}

// ============================================================================
// Content Cleaning Tests
// ============================================================================

#[test]
fn test_cleaned_content_removes_tool_marker() {
    // Test verifies tool call markers are removed from content
    // Cleaned content should only contain surrounding text

    let parser = CustomFormatParser::new();
    let content =
        r#"Let me help. <tool_call>{"name": "help", "arguments": {}}</tool_call> Here you go."#;

    let result = parser.parse(content).unwrap();
    assert!(result.is_some());

    let match_result = result.unwrap();
    assert!(!match_result.cleaned_content.contains("<tool_call>"));
    assert!(!match_result.cleaned_content.contains("</tool_call>"));
    assert!(match_result.cleaned_content.contains("Let me help"));
    assert!(match_result.cleaned_content.contains("Here you go"));
}

#[test]
fn test_raw_match_preserves_full_pattern() {
    // Test verifies raw_match contains the complete matched pattern
    // Useful for debugging and logging

    let parser = CustomFormatParser::new();
    let content = r#"<tool_call>{"name": "test", "arguments": {"key": "value"}}</tool_call>"#;

    let result = parser.parse(content).unwrap();
    assert!(result.is_some());

    let match_result = result.unwrap();
    assert!(match_result.raw_match.starts_with("<tool_call>"));
    assert!(match_result.raw_match.ends_with("</tool_call>"));
    assert!(match_result.raw_match.contains("test"));
}

// ============================================================================
// Format Priority Tests
// ============================================================================

#[test]
fn test_parser_tries_patterns_in_order() {
    // Test verifies parser tries patterns in defined order
    // First match wins if content could match multiple patterns

    let parser = CustomFormatParser::new();
    // This content could potentially match multiple patterns depending on implementation
    // Test that parser returns a result (any valid parse is acceptable)
    let content = r#"commentary to=functions.test <|constrain|>json<|message|>{"x": 1}"#;

    let result = parser.parse(content).unwrap();
    assert!(result.is_some(), "Should match first applicable pattern");
}

// ============================================================================
// Complex/Nested JSON Tests
// ============================================================================

#[test]
fn test_parse_handles_nested_objects() {
    // Test verifies nested JSON objects are preserved
    // Arguments can contain complex nested structures

    let parser = CustomFormatParser::new();
    let content = r#"<tool_call>{"name": "create_user", "arguments": {"user": {"name": "John", "address": {"city": "NYC", "zip": "10001"}}}}</tool_call>"#;

    let result = parser.parse(content).unwrap();
    assert!(result.is_some());

    let match_result = result.unwrap();
    assert_eq!(match_result.function_name, "create_user");
    assert_eq!(match_result.arguments["user"]["name"], "John");
    assert_eq!(match_result.arguments["user"]["address"]["city"], "NYC");
}

#[test]
fn test_parse_handles_array_arguments() {
    // Test verifies array arguments are preserved
    // Arguments can be arrays, not just objects

    let parser = CustomFormatParser::new();
    let content = r#"<tool_call>{"name": "batch_process", "arguments": {"items": [1, 2, 3, 4, 5]}}</tool_call>"#;

    let result = parser.parse(content).unwrap();
    assert!(result.is_some());

    let match_result = result.unwrap();
    assert_eq!(match_result.function_name, "batch_process");
    assert!(match_result.arguments["items"].is_array());
    assert_eq!(match_result.arguments["items"].as_array().unwrap().len(), 5);
}

// ============================================================================
// JSON Repair Tests (clean_tool_call_patterns, attempt_json_repair)
// ============================================================================

#[test]
fn test_clean_tool_call_patterns_removes_xml_tags() {
    // Test verifies XML tool call tags are cleaned from content
    // Fallback when parsing fails to prevent showing raw XML to users

    let content = "Some text <tool_call>{\"broken\": json}</tool_call> more text";
    let cleaned = CustomFormatParser::clean_tool_call_patterns(content);

    assert!(!cleaned.contains("<tool_call>"));
    assert!(!cleaned.contains("</tool_call>"));
    assert!(cleaned.contains("Some text"));
    assert!(cleaned.contains("more text"));
}

#[test]
fn test_clean_tool_call_patterns_removes_deepseek_format() {
    // Test verifies DeepSeek tool request patterns are cleaned

    let content = "Result: [TOOL_REQUEST]{\"invalid\": data}[END_TOOL_REQUEST] Done";
    let cleaned = CustomFormatParser::clean_tool_call_patterns(content);

    assert!(!cleaned.contains("[TOOL_REQUEST]"));
    assert!(!cleaned.contains("[END_TOOL_REQUEST]"));
    assert!(cleaned.contains("Result:"));
    assert!(cleaned.contains("Done"));
}

#[test]
fn test_clean_tool_call_patterns_removes_tool_call_format() {
    // Test verifies "Tool call: X with args: {...}" format is cleaned

    let content = "I'll help. Tool call: search with args: {\"query\": \"test\"} Here.";
    let cleaned = CustomFormatParser::clean_tool_call_patterns(content);

    assert!(!cleaned.contains("Tool call:"));
    assert!(!cleaned.contains("with args:"));
    assert!(cleaned.contains("I'll help."));
    assert!(cleaned.contains("Here."));
}

#[test]
fn test_clean_tool_call_patterns_handles_unclosed_xml() {
    // Test verifies unclosed XML tags are cleaned
    // Models sometimes don't close tags properly

    let content = "Text <tool_call>incomplete json without closing";
    let cleaned = CustomFormatParser::clean_tool_call_patterns(content);

    // Should remove everything from <tool_call> onward
    assert!(!cleaned.contains("<tool_call>"));
    assert!(cleaned.contains("Text"));
}

#[test]
fn test_clean_tool_call_patterns_no_patterns_unchanged() {
    // Test verifies content without tool patterns is unchanged

    let content = "This is just regular text without any tool calls.";
    let cleaned = CustomFormatParser::clean_tool_call_patterns(content);

    assert_eq!(cleaned, content);
}

#[test]
fn test_clean_tool_call_patterns_empty_string() {
    // Test verifies empty string handling

    let content = "";
    let cleaned = CustomFormatParser::clean_tool_call_patterns(content);

    assert_eq!(cleaned, "");
}

// ============================================================================
// Balanced JSON Extraction Tests
// ============================================================================

#[test]
fn test_extract_balanced_json_simple() {
    // Test verifies simple JSON extraction

    let text = r#"{"key": "value"} extra text"#;
    let result = CustomFormatParser::extract_balanced_json(text);

    assert!(result.is_some());
    let (json_str, end_pos) = result.unwrap();
    assert_eq!(json_str, r#"{"key": "value"}"#);
    assert!(end_pos > 0);
}

#[test]
fn test_extract_balanced_json_nested() {
    // Test verifies nested JSON extraction

    let text = r#"{"outer": {"inner": {"deep": true}}} more"#;
    let result = CustomFormatParser::extract_balanced_json(text);

    assert!(result.is_some());
    let (json_str, _) = result.unwrap();
    assert!(json_str.contains("outer"));
    assert!(json_str.contains("inner"));
    assert!(json_str.contains("deep"));
}

#[test]
fn test_extract_balanced_json_with_braces_in_strings() {
    // Test verifies braces inside strings don't confuse parser

    let text = r#"{"code": "if (x) { return }"} rest"#;
    let result = CustomFormatParser::extract_balanced_json(text);

    assert!(result.is_some());
    let (json_str, _) = result.unwrap();
    assert!(json_str.contains("if (x) { return }"));
}

#[test]
fn test_extract_balanced_json_no_json() {
    // Test verifies non-JSON text returns None

    let text = "This is not JSON";
    let result = CustomFormatParser::extract_balanced_json(text);

    assert!(result.is_none());
}

#[test]
fn test_extract_balanced_json_unbalanced() {
    // Test verifies unbalanced braces returns None

    let text = r#"{"key": "value""#; // Missing closing brace
    let result = CustomFormatParser::extract_balanced_json(text);

    assert!(result.is_none());
}

#[test]
fn test_extract_balanced_json_with_leading_whitespace() {
    // Test verifies leading whitespace is handled

    let text = "   {\"key\": 1}";
    let result = CustomFormatParser::extract_balanced_json(text);

    assert!(result.is_some());
    let (json_str, _) = result.unwrap();
    assert_eq!(json_str, r#"{"key": 1}"#);
}

// ============================================================================
// DeepSeek Format Edge Cases
// ============================================================================

#[test]
fn test_parse_deepseek_without_end_marker_returns_none() {
    // Test verifies DeepSeek format without [END_TOOL_REQUEST] marker returns None
    // The regex pattern requires the end marker for proper matching

    let parser = CustomFormatParser::new();
    let content = r#"[TOOL_REQUEST]{"name": "test", "arguments": {"x": 1}}"#;

    let result = parser.parse(content).unwrap();
    // Without [END_TOOL_REQUEST], the pattern doesn't match
    assert!(result.is_none());
}

#[test]
fn test_parse_deepseek_multiline() {
    // Test verifies DeepSeek format works with multiline JSON

    let parser = CustomFormatParser::new();
    let content = r#"[TOOL_REQUEST]{
        "name": "multiline_tool",
        "arguments": {
            "param1": "value1",
            "param2": 42
        }
    }[END_TOOL_REQUEST]"#;

    let result = parser.parse(content).unwrap();
    assert!(result.is_some());

    let match_result = result.unwrap();
    assert_eq!(match_result.function_name, "multiline_tool");
    assert_eq!(match_result.arguments["param1"], "value1");
    assert_eq!(match_result.arguments["param2"], 42);
}

// ============================================================================
// JSON Brace Counting Tests
// ============================================================================

#[test]
fn test_count_json_braces_simple() {
    // Test verifies basic brace counting

    let (open, close) = CustomFormatParser::count_json_braces(r#"{"key": "value"}"#);
    assert_eq!(open, 1);
    assert_eq!(close, 1);
}

#[test]
fn test_count_json_braces_nested() {
    // Test verifies nested brace counting

    let (open, close) = CustomFormatParser::count_json_braces(r#"{"a": {"b": {"c": 1}}}"#);
    assert_eq!(open, 3);
    assert_eq!(close, 3);
}

#[test]
fn test_count_json_braces_ignores_braces_in_strings() {
    // Test verifies braces inside strings are not counted

    let (open, close) = CustomFormatParser::count_json_braces(r#"{"code": "if (x) { } else { }"}"#);
    // Only the outer {} should be counted, not the ones in the string
    assert_eq!(open, 1);
    assert_eq!(close, 1);
}

#[test]
fn test_count_json_braces_unbalanced() {
    // Test verifies unbalanced braces are detected

    let (open, close) = CustomFormatParser::count_json_braces(r#"{"key": "value""#);
    assert_eq!(open, 1);
    assert_eq!(close, 0);
}

#[test]
fn test_count_json_braces_with_escaped_quotes() {
    // Test verifies escaped quotes don't break string detection

    let (open, close) = CustomFormatParser::count_json_braces(r#"{"text": "say \"hello\""}"#);
    assert_eq!(open, 1);
    assert_eq!(close, 1);
}

// ============================================================================
// JSON Repair Tests
// ============================================================================

#[test]
fn test_attempt_json_repair_already_valid() {
    // Test verifies valid JSON is returned unchanged

    let text = r#"{"key": "value"}"#;
    let repaired = CustomFormatParser::attempt_json_repair(text);
    assert_eq!(repaired, text);
}

#[test]
fn test_attempt_json_repair_missing_one_brace() {
    // Test verifies single missing brace is added

    let text = r#"{"key": "value""#;
    let repaired = CustomFormatParser::attempt_json_repair(text);
    assert_eq!(repaired, r#"{"key": "value"}"#);
}

#[test]
fn test_attempt_json_repair_missing_multiple_braces() {
    // Test verifies multiple missing braces are added

    let text = r#"{"outer": {"inner": "value""#;
    let repaired = CustomFormatParser::attempt_json_repair(text);
    assert_eq!(repaired, r#"{"outer": {"inner": "value"}}"#);
}

#[test]
fn test_attempt_json_repair_non_json_unchanged() {
    // Test verifies non-JSON text is returned as-is

    let text = "This is not JSON";
    let repaired = CustomFormatParser::attempt_json_repair(text);
    assert_eq!(repaired, text);
}

#[test]
fn test_attempt_json_repair_with_whitespace() {
    // Test verifies leading/trailing whitespace is trimmed and brace added

    let text = "  {\"key\": \"value\"  ";
    let repaired = CustomFormatParser::attempt_json_repair(text);
    // Whitespace trimmed, then missing brace detected and added
    assert_eq!(repaired, r#"{"key": "value"}"#);
}

#[test]
fn test_add_missing_braces_single() {
    // Test verifies single brace is added

    let repaired = CustomFormatParser::add_missing_braces(r#"{"key": "value""#, 1);
    assert_eq!(repaired, r#"{"key": "value"}"#);
}

#[test]
fn test_add_missing_braces_multiple() {
    // Test verifies multiple braces are added

    let repaired = CustomFormatParser::add_missing_braces(r#"{"a": {"b": 1"#, 2);
    assert_eq!(repaired, r#"{"a": {"b": 1}}"#);
}

#[test]
fn test_add_missing_braces_zero() {
    // Test verifies zero braces doesn't change text

    let text = r#"{"key": "value"}"#;
    let repaired = CustomFormatParser::add_missing_braces(text, 0);
    assert_eq!(repaired, text);
}

// ============================================================================
// GPT-OSS Format Edge Cases
// ============================================================================

#[test]
fn test_parse_gpt_oss_with_nested_json_arguments() {
    // Test verifies GPT-OSS format with deeply nested JSON arguments

    let parser = CustomFormatParser::new();
    let content = r#"commentary to=functions.complex_call <|constrain|>json<|message|>{"nested": {"level": {"deep": {"value": 42}}}}"#;

    let result = parser.parse(content).unwrap();
    assert!(result.is_some());

    let match_result = result.unwrap();
    assert_eq!(match_result.function_name, "complex_call");
    assert_eq!(
        match_result.arguments["nested"]["level"]["deep"]["value"],
        42
    );
}