apr-cli 0.32.0

CLI tool for APR model inspection, debugging, and operations
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
//! Ollama `/api/chat` **function-calling** response-shape classifier (CRUX-I-04).
//!
//! Pure, deterministic classifiers that discharge FALSIFY-CRUX-I-04-{001,002,003,005}
//! at the PARTIAL_ALGORITHM_LEVEL — algorithm-level necessary conditions on
//! already-parsed Ollama chat responses that carry `message.tool_calls[]`:
//!
//!   * `classify_tool_call_schema` — non-streaming response: `message` is an
//!     object, `message.tool_calls` is a non-empty array, each element has
//!     `function.name: string` and `function.arguments: object` (NOT a
//!     stringified JSON blob — the most common ollama/OpenAI drift bug).
//!   * `classify_tool_name_allowlist` — every called `function.name` appears
//!     in the request's declared `tools[*].function.name` set (no model
//!     hallucinated tool names).
//!   * `classify_streaming_tool_call` — in NDJSON streams with tool calls,
//!     exactly one `done == true` frame as the last frame, `tool_calls`
//!     appears only in that terminator frame (atomicity invariant).
//!
//! Full discharge blocks on a live `/api/chat` handler with `tools[]` support
//! in aprender-serve (BLOCKER-UPSTREAM-MISSING). Until then, these classifiers
//! run on captured JSON / NDJSON fixtures.
//!
//! Spec: `contracts/crux-I-04-v1.yaml`.

use serde_json::Value;

/// Outcome of `classify_tool_call_schema`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ToolCallSchemaOutcome {
    /// `message.tool_calls` is a non-empty array of well-formed tool calls.
    Ok,
    /// Top-level response is not a JSON object.
    NotAnObject,
    /// `message` field is missing.
    MissingMessage,
    /// `message` is present but not a JSON object.
    MessageNotAnObject,
    /// `message.tool_calls` field is missing.
    MissingToolCalls,
    /// `message.tool_calls` is present but not a JSON array.
    ToolCallsNotAnArray,
    /// `message.tool_calls` is an empty array.
    ToolCallsEmpty,
    /// A tool call at `index` is not a JSON object.
    ToolCallNotAnObject { index: usize },
    /// A tool call at `index` is missing its `function` field.
    MissingFunction { index: usize },
    /// A tool call's `function` at `index` is not a JSON object.
    FunctionNotAnObject { index: usize },
    /// A tool call's `function.name` at `index` is missing or not a string.
    FunctionNameNotAString { index: usize },
    /// A tool call's `function.arguments` at `index` is missing.
    MissingFunctionArguments { index: usize },
    /// A tool call's `function.arguments` at `index` is a **string** instead
    /// of a JSON object — this is the canonical OpenAI/Ollama drift bug that
    /// breaks strict JSON-schema validation downstream.
    FunctionArgumentsIsString { index: usize },
    /// A tool call's `function.arguments` at `index` is neither a string nor
    /// a JSON object (e.g. array, number, null).
    FunctionArgumentsNotAnObject { index: usize },
}

/// Non-streaming `/api/chat` function-call response-shape gate.
/// Pure; deterministic.
pub fn classify_tool_call_schema(response: &Value) -> ToolCallSchemaOutcome {
    let obj = match response.as_object() {
        Some(o) => o,
        None => return ToolCallSchemaOutcome::NotAnObject,
    };
    let message = match obj.get("message") {
        Some(m) => m,
        None => return ToolCallSchemaOutcome::MissingMessage,
    };
    let message_obj = match message.as_object() {
        Some(o) => o,
        None => return ToolCallSchemaOutcome::MessageNotAnObject,
    };
    let tool_calls = match message_obj.get("tool_calls") {
        Some(tc) => tc,
        None => return ToolCallSchemaOutcome::MissingToolCalls,
    };
    let arr = match tool_calls.as_array() {
        Some(a) => a,
        None => return ToolCallSchemaOutcome::ToolCallsNotAnArray,
    };
    if arr.is_empty() {
        return ToolCallSchemaOutcome::ToolCallsEmpty;
    }
    for (index, call) in arr.iter().enumerate() {
        let call_obj = match call.as_object() {
            Some(o) => o,
            None => return ToolCallSchemaOutcome::ToolCallNotAnObject { index },
        };
        let function = match call_obj.get("function") {
            Some(f) => f,
            None => return ToolCallSchemaOutcome::MissingFunction { index },
        };
        let fn_obj = match function.as_object() {
            Some(o) => o,
            None => return ToolCallSchemaOutcome::FunctionNotAnObject { index },
        };
        if !fn_obj.get("name").is_some_and(Value::is_string) {
            return ToolCallSchemaOutcome::FunctionNameNotAString { index };
        }
        let args = match fn_obj.get("arguments") {
            Some(a) => a,
            None => return ToolCallSchemaOutcome::MissingFunctionArguments { index },
        };
        if args.is_string() {
            return ToolCallSchemaOutcome::FunctionArgumentsIsString { index };
        }
        if !args.is_object() {
            return ToolCallSchemaOutcome::FunctionArgumentsNotAnObject { index };
        }
    }
    ToolCallSchemaOutcome::Ok
}

/// Outcome of `classify_tool_name_allowlist`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ToolNameAllowlistOutcome {
    /// Every called tool name appears in the declared tool set.
    Ok,
    /// A tool call at `index` invokes a name not in the declared set.
    HallucinatedToolName { index: usize, name: String },
    /// The declared set is empty (server produced tool_calls against no
    /// declared tools at all).
    NoDeclaredTools,
}

/// Allowlist gate: every called tool's `function.name` must be a member of
/// `declared_tool_names`. Does not revalidate the schema — call
/// `classify_tool_call_schema` first.
pub fn classify_tool_name_allowlist(
    response: &Value,
    declared_tool_names: &[&str],
) -> ToolNameAllowlistOutcome {
    if declared_tool_names.is_empty() {
        // If no tools were declared, any tool_call is a hallucination.
        // We still report NoDeclaredTools as the more informative outcome
        // only when there's at least one tool call to reject.
        if response
            .get("message")
            .and_then(|m| m.get("tool_calls"))
            .and_then(Value::as_array)
            .is_some_and(|a| !a.is_empty())
        {
            return ToolNameAllowlistOutcome::NoDeclaredTools;
        }
        return ToolNameAllowlistOutcome::Ok;
    }
    let calls = response
        .get("message")
        .and_then(|m| m.get("tool_calls"))
        .and_then(Value::as_array);
    let arr = match calls {
        Some(a) => a,
        None => return ToolNameAllowlistOutcome::Ok,
    };
    for (index, call) in arr.iter().enumerate() {
        let name = call
            .get("function")
            .and_then(|f| f.get("name"))
            .and_then(Value::as_str);
        if let Some(n) = name {
            if !declared_tool_names.iter().any(|d| *d == n) {
                return ToolNameAllowlistOutcome::HallucinatedToolName {
                    index,
                    name: n.to_string(),
                };
            }
        }
    }
    ToolNameAllowlistOutcome::Ok
}

/// Outcome of `classify_streaming_tool_call`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StreamingToolCallOutcome {
    /// Exactly one `done == true` frame as the last frame, and `tool_calls`
    /// (if any) appear only in that terminator.
    Ok,
    /// Frame list is empty.
    NoFrames,
    /// A frame is not a JSON object.
    FrameNotAnObject { frame_index: usize },
    /// A frame is missing the `done` field.
    MissingDoneField { frame_index: usize },
    /// A frame's `done` field is not a boolean.
    DoneNotBool { frame_index: usize },
    /// A non-final frame is `done == true`.
    EarlyDoneFrame { frame_index: usize },
    /// No frame had `done == true`.
    NoTerminalFrame,
    /// A non-terminator frame carried a non-empty `message.tool_calls[]`
    /// (violates atomicity).
    ToolCallsInNonTerminatorFrame { frame_index: usize },
}

/// Streaming NDJSON terminator-atomicity gate for tool calls.
/// Pure; deterministic.
pub fn classify_streaming_tool_call(frames: &[Value]) -> StreamingToolCallOutcome {
    if frames.is_empty() {
        return StreamingToolCallOutcome::NoFrames;
    }
    let last_idx = frames.len() - 1;
    let mut terminal_seen = false;
    for (i, frame) in frames.iter().enumerate() {
        let obj = match frame.as_object() {
            Some(o) => o,
            None => return StreamingToolCallOutcome::FrameNotAnObject { frame_index: i },
        };
        let done_val = match obj.get("done") {
            Some(v) => v,
            None => return StreamingToolCallOutcome::MissingDoneField { frame_index: i },
        };
        let done = match done_val.as_bool() {
            Some(b) => b,
            None => return StreamingToolCallOutcome::DoneNotBool { frame_index: i },
        };
        if done {
            if i != last_idx {
                return StreamingToolCallOutcome::EarlyDoneFrame { frame_index: i };
            }
            terminal_seen = true;
        } else {
            // Non-terminator frames must not carry tool_calls.
            if frame_has_nonempty_tool_calls(frame) {
                return StreamingToolCallOutcome::ToolCallsInNonTerminatorFrame { frame_index: i };
            }
        }
    }
    if !terminal_seen {
        return StreamingToolCallOutcome::NoTerminalFrame;
    }
    StreamingToolCallOutcome::Ok
}

fn frame_has_nonempty_tool_calls(frame: &Value) -> bool {
    frame
        .get("message")
        .and_then(|m| m.get("tool_calls"))
        .and_then(Value::as_array)
        .is_some_and(|a| !a.is_empty())
}

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

    // ═══ schema classifier ═══

    fn well_formed_tool_response() -> Value {
        json!({
            "model": "tiny",
            "created_at": "2026-04-22T00:00:00Z",
            "message": {
                "role": "assistant",
                "content": "",
                "tool_calls": [
                    {
                        "function": {
                            "name": "get_weather",
                            "arguments": {
                                "location": "San Francisco",
                                "unit": "celsius"
                            }
                        }
                    }
                ]
            },
            "done": true
        })
    }

    #[test]
    fn schema_ok_on_well_formed_tool_call() {
        assert_eq!(
            classify_tool_call_schema(&well_formed_tool_response()),
            ToolCallSchemaOutcome::Ok
        );
    }

    #[test]
    fn schema_rejects_non_object_top_level() {
        assert_eq!(
            classify_tool_call_schema(&json!([1, 2, 3])),
            ToolCallSchemaOutcome::NotAnObject
        );
    }

    #[test]
    fn schema_rejects_missing_message() {
        let v = json!({"done": true});
        assert_eq!(
            classify_tool_call_schema(&v),
            ToolCallSchemaOutcome::MissingMessage
        );
    }

    #[test]
    fn schema_rejects_non_object_message() {
        let v = json!({"message": "just a string", "done": true});
        assert_eq!(
            classify_tool_call_schema(&v),
            ToolCallSchemaOutcome::MessageNotAnObject
        );
    }

    #[test]
    fn schema_rejects_missing_tool_calls() {
        let v = json!({"message": {"role": "assistant", "content": "no tool"}, "done": true});
        assert_eq!(
            classify_tool_call_schema(&v),
            ToolCallSchemaOutcome::MissingToolCalls
        );
    }

    #[test]
    fn schema_rejects_tool_calls_not_array() {
        let v = json!({"message": {"role": "assistant", "tool_calls": "oops"}, "done": true});
        assert_eq!(
            classify_tool_call_schema(&v),
            ToolCallSchemaOutcome::ToolCallsNotAnArray
        );
    }

    #[test]
    fn schema_rejects_empty_tool_calls() {
        let v = json!({"message": {"role": "assistant", "tool_calls": []}, "done": true});
        assert_eq!(
            classify_tool_call_schema(&v),
            ToolCallSchemaOutcome::ToolCallsEmpty
        );
    }

    #[test]
    fn schema_rejects_non_object_tool_call() {
        let v = json!({"message": {"role": "assistant", "tool_calls": ["bad"]}, "done": true});
        assert_eq!(
            classify_tool_call_schema(&v),
            ToolCallSchemaOutcome::ToolCallNotAnObject { index: 0 }
        );
    }

    #[test]
    fn schema_rejects_missing_function() {
        let v = json!({
            "message": {"role": "assistant", "tool_calls": [{}]},
            "done": true
        });
        assert_eq!(
            classify_tool_call_schema(&v),
            ToolCallSchemaOutcome::MissingFunction { index: 0 }
        );
    }

    #[test]
    fn schema_rejects_function_not_object() {
        let v = json!({
            "message": {"role": "assistant", "tool_calls": [{"function": "x"}]},
            "done": true
        });
        assert_eq!(
            classify_tool_call_schema(&v),
            ToolCallSchemaOutcome::FunctionNotAnObject { index: 0 }
        );
    }

    #[test]
    fn schema_rejects_missing_function_name() {
        let v = json!({
            "message": {"role": "assistant", "tool_calls": [{"function": {"arguments": {}}}]},
            "done": true
        });
        assert_eq!(
            classify_tool_call_schema(&v),
            ToolCallSchemaOutcome::FunctionNameNotAString { index: 0 }
        );
    }

    #[test]
    fn schema_rejects_non_string_function_name() {
        let v = json!({
            "message": {"role": "assistant", "tool_calls": [
                {"function": {"name": 42, "arguments": {}}}
            ]},
            "done": true
        });
        assert_eq!(
            classify_tool_call_schema(&v),
            ToolCallSchemaOutcome::FunctionNameNotAString { index: 0 }
        );
    }

    #[test]
    fn schema_rejects_missing_arguments() {
        let v = json!({
            "message": {"role": "assistant", "tool_calls": [
                {"function": {"name": "get_weather"}}
            ]},
            "done": true
        });
        assert_eq!(
            classify_tool_call_schema(&v),
            ToolCallSchemaOutcome::MissingFunctionArguments { index: 0 }
        );
    }

    /// The canonical drift bug: `arguments` comes back as a **string** of
    /// JSON instead of a JSON object. Must be rejected even though the
    /// "content" looks parseable.
    #[test]
    fn schema_rejects_stringified_arguments() {
        let v = json!({
            "message": {"role": "assistant", "tool_calls": [
                {"function": {"name": "get_weather", "arguments": "{\"location\":\"SF\"}"}}
            ]},
            "done": true
        });
        assert_eq!(
            classify_tool_call_schema(&v),
            ToolCallSchemaOutcome::FunctionArgumentsIsString { index: 0 }
        );
    }

    #[test]
    fn schema_rejects_non_object_non_string_arguments() {
        let v = json!({
            "message": {"role": "assistant", "tool_calls": [
                {"function": {"name": "get_weather", "arguments": 42}}
            ]},
            "done": true
        });
        assert_eq!(
            classify_tool_call_schema(&v),
            ToolCallSchemaOutcome::FunctionArgumentsNotAnObject { index: 0 }
        );
    }

    #[test]
    fn schema_reports_second_call_violations() {
        let v = json!({
            "message": {"role": "assistant", "tool_calls": [
                {"function": {"name": "get_weather", "arguments": {}}},
                {"function": {"name": "get_time", "arguments": "stringy"}}
            ]},
            "done": true
        });
        assert_eq!(
            classify_tool_call_schema(&v),
            ToolCallSchemaOutcome::FunctionArgumentsIsString { index: 1 }
        );
    }

    #[test]
    fn schema_classifier_is_deterministic() {
        let r = well_formed_tool_response();
        let a = classify_tool_call_schema(&r);
        let b = classify_tool_call_schema(&r);
        assert_eq!(a, b);
    }

    // ═══ allowlist classifier ═══

    #[test]
    fn allowlist_ok_when_called_name_matches_declared() {
        let r = well_formed_tool_response();
        assert_eq!(
            classify_tool_name_allowlist(&r, &["get_weather", "get_time"]),
            ToolNameAllowlistOutcome::Ok
        );
    }

    #[test]
    fn allowlist_rejects_hallucinated_name() {
        let r = well_formed_tool_response();
        assert_eq!(
            classify_tool_name_allowlist(&r, &["get_time"]),
            ToolNameAllowlistOutcome::HallucinatedToolName {
                index: 0,
                name: "get_weather".to_string(),
            }
        );
    }

    #[test]
    fn allowlist_flags_no_declared_tools_when_calls_present() {
        let r = well_formed_tool_response();
        assert_eq!(
            classify_tool_name_allowlist(&r, &[]),
            ToolNameAllowlistOutcome::NoDeclaredTools
        );
    }

    #[test]
    fn allowlist_ok_when_no_declared_and_no_calls() {
        let v = json!({"message": {"role": "assistant", "content": "hi"}, "done": true});
        assert_eq!(
            classify_tool_name_allowlist(&v, &[]),
            ToolNameAllowlistOutcome::Ok
        );
    }

    #[test]
    fn allowlist_ok_when_no_tool_calls_present() {
        let v = json!({"message": {"role": "assistant", "content": "hi"}, "done": true});
        assert_eq!(
            classify_tool_name_allowlist(&v, &["get_weather"]),
            ToolNameAllowlistOutcome::Ok
        );
    }

    #[test]
    fn allowlist_reports_second_call_hallucination() {
        let v = json!({
            "message": {"role": "assistant", "tool_calls": [
                {"function": {"name": "get_weather", "arguments": {}}},
                {"function": {"name": "make_coffee", "arguments": {}}}
            ]},
            "done": true
        });
        assert_eq!(
            classify_tool_name_allowlist(&v, &["get_weather"]),
            ToolNameAllowlistOutcome::HallucinatedToolName {
                index: 1,
                name: "make_coffee".to_string()
            }
        );
    }

    #[test]
    fn allowlist_classifier_is_deterministic() {
        let r = well_formed_tool_response();
        let names = ["get_weather"];
        let a = classify_tool_name_allowlist(&r, &names);
        let b = classify_tool_name_allowlist(&r, &names);
        assert_eq!(a, b);
    }

    // ═══ streaming NDJSON classifier ═══

    fn delta_frame(content: &str) -> Value {
        json!({"message": {"role": "assistant", "content": content}, "done": false})
    }
    fn terminal_tool_frame() -> Value {
        json!({
            "message": {
                "role": "assistant",
                "content": "",
                "tool_calls": [
                    {"function": {"name": "get_weather", "arguments": {"location": "SF"}}}
                ]
            },
            "done": true
        })
    }
    fn terminal_plain_frame() -> Value {
        json!({"done": true, "eval_count": 3, "eval_duration": 500})
    }

    #[test]
    fn ndjson_ok_on_single_terminator_with_tool_calls() {
        let frames = vec![delta_frame(""), delta_frame(""), terminal_tool_frame()];
        assert_eq!(
            classify_streaming_tool_call(&frames),
            StreamingToolCallOutcome::Ok
        );
    }

    #[test]
    fn ndjson_ok_on_terminator_only() {
        let frames = vec![terminal_tool_frame()];
        assert_eq!(
            classify_streaming_tool_call(&frames),
            StreamingToolCallOutcome::Ok
        );
    }

    #[test]
    fn ndjson_ok_when_no_tool_calls_anywhere() {
        let frames = vec![delta_frame("hi"), terminal_plain_frame()];
        assert_eq!(
            classify_streaming_tool_call(&frames),
            StreamingToolCallOutcome::Ok
        );
    }

    #[test]
    fn ndjson_rejects_empty() {
        let frames: Vec<Value> = vec![];
        assert_eq!(
            classify_streaming_tool_call(&frames),
            StreamingToolCallOutcome::NoFrames
        );
    }

    #[test]
    fn ndjson_rejects_non_object_frame() {
        let frames = vec![json!([1, 2]), terminal_plain_frame()];
        assert_eq!(
            classify_streaming_tool_call(&frames),
            StreamingToolCallOutcome::FrameNotAnObject { frame_index: 0 }
        );
    }

    #[test]
    fn ndjson_rejects_missing_done() {
        let frames = vec![
            json!({"message": {"role": "assistant", "content": "x"}}),
            terminal_plain_frame(),
        ];
        assert_eq!(
            classify_streaming_tool_call(&frames),
            StreamingToolCallOutcome::MissingDoneField { frame_index: 0 }
        );
    }

    #[test]
    fn ndjson_rejects_non_bool_done() {
        let frames = vec![json!({"done": "false"}), terminal_plain_frame()];
        assert_eq!(
            classify_streaming_tool_call(&frames),
            StreamingToolCallOutcome::DoneNotBool { frame_index: 0 }
        );
    }

    #[test]
    fn ndjson_rejects_early_done_true() {
        let frames = vec![
            delta_frame("hi"),
            json!({"done": true}),
            delta_frame("!"),
            terminal_plain_frame(),
        ];
        assert_eq!(
            classify_streaming_tool_call(&frames),
            StreamingToolCallOutcome::EarlyDoneFrame { frame_index: 1 }
        );
    }

    #[test]
    fn ndjson_rejects_missing_terminator() {
        let frames = vec![delta_frame("a"), delta_frame("b")];
        assert_eq!(
            classify_streaming_tool_call(&frames),
            StreamingToolCallOutcome::NoTerminalFrame
        );
    }

    /// A tool_calls array appears in a non-terminator frame — violates
    /// atomicity. Canonical Ollama invariant.
    #[test]
    fn ndjson_rejects_tool_calls_in_non_terminator() {
        let frames = vec![
            json!({
                "message": {"role": "assistant", "tool_calls": [
                    {"function": {"name": "get_weather", "arguments": {}}}
                ]},
                "done": false
            }),
            terminal_plain_frame(),
        ];
        assert_eq!(
            classify_streaming_tool_call(&frames),
            StreamingToolCallOutcome::ToolCallsInNonTerminatorFrame { frame_index: 0 }
        );
    }

    #[test]
    fn ndjson_allows_empty_tool_calls_array_in_non_terminator() {
        // An empty array does not violate atomicity — nothing was actually split.
        let frames = vec![
            json!({"message": {"role": "assistant", "tool_calls": []}, "done": false}),
            terminal_tool_frame(),
        ];
        assert_eq!(
            classify_streaming_tool_call(&frames),
            StreamingToolCallOutcome::Ok
        );
    }

    #[test]
    fn ndjson_classifier_is_deterministic() {
        let frames = vec![delta_frame("a"), terminal_tool_frame()];
        let a = classify_streaming_tool_call(&frames);
        let b = classify_streaming_tool_call(&frames);
        assert_eq!(a, b);
    }
}