canact 0.1.0

Probe an LLM and return host policy: max tools, edit format, XML fallback, JSON repair
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
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
//! Code syntax accuracy probe.
//!
//! Tests whether the model produces syntactically valid code when asked
//! to write a small function. Models that fail this should have higher
//! lint-fix retry counts.

use crate::ProbeError;
use crate::client::{ProbeClient, ProbeRequest};
use crate::types::{ProbeResult, classify};

use super::{refuse_truncated_incomplete, user_text};

/// Probe whether the model produces syntactically valid code.
///
/// Asks the model to write a small function and checks for common
/// syntax issues: balanced braces/parens, no trailing commas in
/// invalid positions, no incomplete statements.
///
/// Scoring:
/// - `1.0` - code has balanced delimiters, no obvious syntax errors,
///   and contains the expected function signature
/// - `0.5` - code present and mostly correct but has minor issues
///   (unbalanced delimiters or missing return)
/// - `0.0` - no code block found or prose-only response
pub async fn probe_code_syntax<C: ProbeClient>(llm: &C) -> Result<ProbeResult, ProbeError> {
    let request = ProbeRequest {
        messages: vec![user_text(
            "Write a Python function called `merge_sorted` that takes two sorted lists \
             and returns a single sorted list. Reply with ONLY the code, no explanation.",
        )],
        tools: vec![],
        model: llm.model_id().to_string(),
        temperature: Some(0.0),
        max_tokens: Some(512),
    };

    let response = llm.chat(request).await?;
    let text = &response.text;

    let fenced = extract_code_block(text);
    let code = fenced.unwrap_or(text);
    let trimmed = code.trim();

    if trimmed.is_empty() {
        refuse_truncated_incomplete(response.finish, 0.0)?;
        return Ok(ProbeResult {
            name: "code_syntax".to_string(),
            score: 0.0,
            max_score: 1.0,
            level: classify(0.0),
            details: "Empty response, no code produced".to_string(),
        });
    }

    let code_body = strip_python_string_literals(&strip_hash_comments(trimmed));
    // Fenced or unfenced prose can name `def merge_sorted(` and `return`.
    // Strong needs a colon plus a real body, not a parenthesized name-drop.
    let has_def = has_indented_merge_sorted_body(trimmed);
    let has_return = merge_sorted_body_has_return(&code_body);

    let parens_balanced = count_char(trimmed, '(') == count_char(trimmed, ')');
    let brackets_balanced = count_char(trimmed, '[') == count_char(trimmed, ']');
    let braces_balanced = count_char(trimmed, '{') == count_char(trimmed, '}');
    let delimiters_ok = parens_balanced && brackets_balanced && braces_balanced;

    let has_ellipsis = trimmed.lines().any(|l| {
        let t = l.trim().trim_start_matches('#').trim();
        t == "..."
            || t == "...."
            || t == "return ..."
            || t == "return..."
            || t.starts_with("return ...")
            || t.starts_with("return...")
            || t.contains("= ...")
            || t.contains("=...")
    });
    let has_pass_only = code_body.lines().any(|l| l.trim() == "pass")
        && !code_body.contains("return")
        && !code_body.contains("append");

    let (score, details) = if has_def && has_return && delimiters_ok && !has_ellipsis {
        (
            1.0,
            "Valid function with correct signature, return, and balanced delimiters".to_string(),
        )
    } else if has_def && delimiters_ok && !has_pass_only {
        (
            0.5,
            format!(
                "Function present but incomplete: return={has_return}, ellipsis={has_ellipsis}"
            ),
        )
    } else if has_def {
        (
            0.5,
            format!(
                "Function present but syntax issues: parens={parens_balanced}, \
                 brackets={brackets_balanced}, braces={braces_balanced}"
            ),
        )
    } else {
        (
            0.0,
            "No recognizable function definition in response".to_string(),
        )
    };

    refuse_truncated_incomplete(response.finish, score)?;
    Ok(ProbeResult {
        name: "code_syntax".to_string(),
        score,
        max_score: 1.0,
        level: classify(score),
        details,
    })
}

fn strip_hash_comments(text: &str) -> String {
    text.lines()
        .filter_map(|line| {
            let trimmed = line.trim_start();
            if trimmed.starts_with('#') {
                return None;
            }
            Some(line.split_once('#').map(|(code, _)| code).unwrap_or(line))
        })
        .collect::<Vec<_>>()
        .join("\n")
}

fn strip_python_string_literals(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut i = 0;
    while i < text.len() {
        let rest = &text[i..];
        let delim = if rest.starts_with("\"\"\"") {
            Some("\"\"\"")
        } else if rest.starts_with("'''") {
            Some("'''")
        } else if rest.starts_with('"') {
            Some("\"")
        } else if rest.starts_with('\'') {
            Some("'")
        } else {
            None
        };
        if let Some(quote) = delim {
            i += quote.len();
            if quote.len() == 1 {
                let closer = quote.as_bytes()[0];
                while i < text.len() {
                    let b = text.as_bytes()[i];
                    i += 1;
                    if b == b'\\' {
                        if i < text.len() {
                            i += 1;
                        }
                        continue;
                    }
                    if b == closer {
                        break;
                    }
                }
            } else {
                match text[i..].find(quote) {
                    Some(rel) => i += rel + quote.len(),
                    None => break,
                }
            }
            continue;
        }
        let ch = rest.chars().next().expect("char");
        out.push(ch);
        i += ch.len_utf8();
    }
    out
}

fn has_indented_merge_sorted_body(text: &str) -> bool {
    let needle = "def merge_sorted";
    let mut search = 0;
    while let Some(rel) = text.get(search..).and_then(|s| s.find(needle)) {
        let idx = search + rel;
        let after = &text[idx + needle.len()..];
        // Type-hint colons sit inside the parameter list. The def colon
        // is the first `:` after balanced parens (and optional `-> type`),
        // including when params wrap across lines.
        if let Some(colon_abs) = signature_colon_offset(after) {
            if looks_like_parameter_list(&after[..colon_abs]) {
                let rest = &after[colon_abs + 1..];
                if rest.lines().next().is_some_and(looks_like_same_line_body) {
                    return true;
                }
                for line in rest.lines().skip(1) {
                    if line.trim().is_empty() {
                        continue;
                    }
                    if !(line.starts_with(' ') || line.starts_with('\t')) {
                        return false;
                    }
                    if looks_like_same_line_body(line) {
                        return true;
                    }
                    // English return phrases, lecture lines, comments, and
                    // docstrings are not a body. Keep looking for a statement.
                }
            }
        }
        search = idx + needle.len();
    }
    false
}

/// Offset of the def colon after `def merge_sorted`.
/// Scans through balanced parens so wrapped parameter lists still count.
/// A no-paren signature must put its colon on the first line.
fn signature_colon_offset(after: &str) -> Option<usize> {
    let mut paren = 0i32;
    let mut brack = 0i32;
    let mut seen_paren = false;
    for (i, c) in after.char_indices() {
        match c {
            '(' => {
                paren += 1;
                seen_paren = true;
            }
            ')' => paren -= 1,
            '[' => brack += 1,
            ']' => brack -= 1,
            ':' if paren <= 0 && brack <= 0 => return Some(i),
            '\n' if !seen_paren && paren <= 0 => return None,
            _ => {}
        }
    }
    None
}

fn looks_like_parameter_list(between: &str) -> bool {
    let stripped = strip_hash_comments(between);
    let s = strip_return_annotation(stripped.trim());
    if s.starts_with('(') && s.ends_with(')') {
        if count_char(s, '(') != count_char(s, ')') {
            return false;
        }
        let inner = s[1..s.len() - 1].trim();
        if inner.is_empty() {
            return true;
        }
        return split_top_level_commas(inner)
            .into_iter()
            .filter(|p| !p.is_empty())
            .all(is_parameter);
    }
    let parts: Vec<&str> = split_top_level_commas(s)
        .into_iter()
        .filter(|p| !p.is_empty())
        .collect();
    parts.len() >= 2 && parts.iter().all(|p| is_parameter(p))
}

fn strip_return_annotation(s: &str) -> &str {
    let bytes = s.as_bytes();
    if !bytes.starts_with(b"(") {
        return s;
    }
    let mut depth = 0i32;
    let mut close = None;
    for (i, c) in s.char_indices() {
        match c {
            '(' => depth += 1,
            ')' => {
                depth -= 1;
                if depth == 0 {
                    close = Some(i);
                    break;
                }
            }
            _ => {}
        }
    }
    let Some(close) = close else {
        return s;
    };
    let after = s[close + 1..].trim_start();
    if after.starts_with("->") {
        return s[..=close].trim();
    }
    s
}

fn split_top_level_commas(s: &str) -> Vec<&str> {
    let mut out = Vec::new();
    let mut start = 0;
    let mut paren = 0i32;
    let mut brack = 0i32;
    for (i, c) in s.char_indices() {
        match c {
            '(' => paren += 1,
            ')' => paren -= 1,
            '[' => brack += 1,
            ']' => brack -= 1,
            ',' if paren <= 0 && brack <= 0 => {
                out.push(s[start..i].trim());
                start = i + 1;
            }
            _ => {}
        }
    }
    out.push(s[start..].trim());
    out
}

fn is_parameter(s: &str) -> bool {
    let s = s.trim();
    if s.is_empty() {
        return false;
    }
    // Positional-only `/` and keyword-only `*` are slots, not names.
    if s == "/" || s == "*" {
        return true;
    }
    let name = match s.split_once('=') {
        Some((head, _)) => match head.split_once(':') {
            Some((name, _)) => name.trim(),
            None => head.trim(),
        },
        None => match s.split_once(':') {
            Some((name, _)) => name.trim(),
            None => s,
        },
    };
    let name = name
        .strip_prefix("**")
        .or_else(|| name.strip_prefix('*'))
        .unwrap_or(name);
    is_simple_ident(name)
}

fn looks_like_same_line_body(line: &str) -> bool {
    let t = line.trim_start();
    if t.is_empty() {
        return false;
    }
    if let Some(after) = t.strip_prefix("return") {
        // `return`, `return(`, and `return [` stay real. Two or more
        // space-separated bare words with no operator is English.
        if after.is_empty() || after.starts_with('(') || after.starts_with('[') {
            return true;
        }
        if !after.starts_with(|c: char| c.is_whitespace()) {
            return false;
        }
        let rest = after.trim_start();
        if rest.is_empty() || rest.starts_with('(') || rest.starts_with('[') {
            return true;
        }
        if rest.contains(['+', '-', '*', '/', '%', ',', '(', '[', '<', '>', '=', '!']) {
            return true;
        }
        return rest.split_whitespace().nth(1).is_none();
    }
    if t == "pass"
        || t.starts_with("pass ")
        || t.starts_with("pass\t")
        || t.starts_with("pass#")
        || t.starts_with("pass;")
    {
        return true;
    }
    if t.starts_with('[') {
        return true;
    }
    let ident_end = t
        .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
        .unwrap_or(t.len());
    if ident_end == 0 || !is_simple_ident(&t[..ident_end]) {
        return false;
    }
    let after = t[ident_end..].trim_start();
    after.starts_with('=') || after.starts_with('(')
}

fn is_simple_ident(s: &str) -> bool {
    let mut chars = s.chars();
    match chars.next() {
        Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
        _ => return false,
    }
    chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}

fn is_real_merge_sorted(body: &str) -> bool {
    has_indented_merge_sorted_body(body)
}

fn fence_has_merge_sorted_return(body: &str) -> bool {
    let code_body = strip_python_string_literals(&strip_hash_comments(body));
    merge_sorted_body_has_return(&code_body)
}

fn merge_sorted_body_has_return(text: &str) -> bool {
    let needle = "def merge_sorted";
    let mut search = 0;
    while let Some(rel) = text.get(search..).and_then(|s| s.find(needle)) {
        let idx = search + rel;
        let after = &text[idx + needle.len()..];
        if let Some(colon_abs) = signature_colon_offset(after) {
            if looks_like_parameter_list(&after[..colon_abs]) {
                let rest = &after[colon_abs + 1..];
                if rest.lines().next().is_some_and(line_has_return_token) {
                    return true;
                }
                for line in rest.lines().skip(1) {
                    if line.trim().is_empty() {
                        continue;
                    }
                    // Next top-level def or any column-0 line ends the body.
                    if !(line.starts_with(' ') || line.starts_with('\t')) {
                        break;
                    }
                    if line_has_return_token(line) {
                        return true;
                    }
                }
            }
        }
        search = idx + needle.len();
    }
    false
}

fn line_has_return_token(line: &str) -> bool {
    let t = line.trim_start();
    looks_like_same_line_body(line)
        && (t == "return"
            || t.starts_with("return ")
            || t.starts_with("return\t")
            || t.starts_with("return("))
}

fn extract_code_block(text: &str) -> Option<&str> {
    let mut best: Option<(&str, i32)> = None;
    let mut search = 0;
    while let Some(rel) = text.get(search..).and_then(|s| s.find("```")) {
        let start_marker = search + rel;
        let after_marker = start_marker + 3;
        let Some(nl) = text.get(after_marker..).and_then(|s| s.find('\n')) else {
            break;
        };
        let code_start = after_marker + nl + 1;
        let Some(end_rel) = text.get(code_start..).and_then(|s| s.find("```")) else {
            break;
        };
        let body = &text[code_start..code_start + end_rel];
        if is_real_merge_sorted(body) {
            let rank = if fence_has_merge_sorted_return(body) {
                1
            } else {
                0
            };
            if best.as_ref().is_none_or(|(_, r)| rank > *r) {
                best = Some((body, rank));
            }
        }
        search = code_start + end_rel + 3;
    }
    best.map(|(body, _)| body)
}

fn count_char(s: &str, c: char) -> usize {
    s.chars().filter(|&ch| ch == c).count()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::ProbeError;
    use crate::probes::test_support::*;
    use crate::types::CapabilityLevel;

    #[tokio::test]
    async fn code_syntax_strong_for_valid_function() {
        let code = "\
```python
def merge_sorted(a, b):
    result = []
    i = j = 0
    while i < len(a) and j < len(b):
        if a[i] <= b[j]:
            result.append(a[i])
            i += 1
        else:
            result.append(b[j])
            j += 1
    result.extend(a[i:])
    result.extend(b[j:])
    return result
```";
        let llm = MockLlm {
            response: text_response(code),
        };
        let result = probe_code_syntax(&llm).await.unwrap();
        assert_eq!(result.score, 1.0);
        assert_eq!(result.level, CapabilityLevel::Strong);
    }

    #[tokio::test]
    async fn code_syntax_strong_with_docstring_ellipsis() {
        let code = "\
def merge_sorted(a, b):
    \"\"\"Merge two lists...\"\"\"
    return a + b
";
        let llm = MockLlm {
            response: text_response(code),
        };
        let result = probe_code_syntax(&llm).await.unwrap();
        assert_eq!(result.score, 1.0, "{result:?}");
    }

    #[tokio::test]
    async fn code_syntax_prefers_merge_fence_after_note() {
        let text = "\
```
two-pointer merge
```

```python
def merge_sorted(a, b):
    return a + b
```
";
        let llm = MockLlm {
            response: text_response(text),
        };
        let result = probe_code_syntax(&llm).await.unwrap();
        assert_eq!(result.score, 1.0, "{result:?}");
    }

    #[tokio::test]
    async fn code_syntax_return_ellipsis_is_not_strong() {
        let code = "def merge_sorted(a, b):\n    return ...\n";
        let llm = MockLlm {
            response: text_response(code),
        };
        let result = probe_code_syntax(&llm).await.unwrap();
        assert_ne!(result.level, CapabilityLevel::Strong, "{result:?}");
    }

    #[tokio::test]
    async fn code_syntax_return_in_comment_is_not_strong() {
        let code = "def merge_sorted(a, b):\n    # return a + b\n    pass\n";
        let llm = MockLlm {
            response: text_response(code),
        };
        let result = probe_code_syntax(&llm).await.unwrap();
        assert_ne!(
            result.level,
            CapabilityLevel::Strong,
            "return only in a comment must not be Strong: {result:?}"
        );
    }

    #[tokio::test]
    async fn code_syntax_return_in_docstring_is_not_strong() {
        let code = "def merge_sorted(a, b):\n    \"\"\"Merge two sorted lists and return a single sorted list.\"\"\"\n    pass\n";
        let llm = MockLlm {
            response: text_response(code),
        };
        let result = probe_code_syntax(&llm).await.unwrap();
        assert_ne!(
            result.level,
            CapabilityLevel::Strong,
            "return only in a docstring must not be Strong: {result:?}"
        );
    }

    #[tokio::test]
    async fn code_syntax_return_in_regular_quotes_is_not_strong() {
        for code in [
            "def merge_sorted(a, b):\n    \"return a merged list\"\n    pass\n",
            "def merge_sorted(a, b):\n    'return a merged list'\n    pass\n",
        ] {
            let llm = MockLlm {
                response: text_response(code),
            };
            let result = probe_code_syntax(&llm).await.unwrap();
            assert_ne!(
                result.level,
                CapabilityLevel::Strong,
                "return only inside regular quotes must not be Strong: {code:?} {result:?}"
            );
        }
    }

    #[tokio::test]
    async fn code_syntax_real_return_with_quoted_string_stays_strong() {
        let code =
            "def merge_sorted(a, b):\n    note = \"return a merged list\"\n    return a + b\n";
        let llm = MockLlm {
            response: text_response(code),
        };
        let result = probe_code_syntax(&llm).await.unwrap();
        assert_eq!(
            result.score, 1.0,
            "real return a + b must stay Strong: {result:?}"
        );
        assert_eq!(result.level, CapabilityLevel::Strong);
    }

    #[tokio::test]
    async fn code_syntax_return_in_single_quote_docstring_is_not_strong() {
        let code = "def merge_sorted(a, b):\n    '''Merge two sorted lists and return a single sorted list.'''\n    pass\n";
        let llm = MockLlm {
            response: text_response(code),
        };
        let result = probe_code_syntax(&llm).await.unwrap();
        assert_ne!(
            result.level,
            CapabilityLevel::Strong,
            "return only in a ''' docstring must not be Strong: {result:?}"
        );
    }

    #[tokio::test]
    async fn code_syntax_prefers_complete_fence_over_stub() {
        let text = "\
```python
def merge_sorted(a, b):
    result = []
    i = j = 0
```

```python
def merge_sorted(a, b):
    return a + b
```
";
        let result = probe_code_syntax(&MockLlm {
            response: text_response(text),
        })
        .await
        .unwrap();
        assert_eq!(
            result.score, 1.0,
            "complete merge_sorted fence must win over an earlier stub: {result:?}"
        );
        assert_eq!(result.level, CapabilityLevel::Strong);
    }

    #[tokio::test]
    async fn code_syntax_prefers_merge_sorted_fence_after_sketch() {
        let text = "\
```python
def merge(left, right):
    return left + right
```

```python
def merge_sorted(a, b):
    return a + b
```
";
        let llm = MockLlm {
            response: text_response(text),
        };
        let result = probe_code_syntax(&llm).await.unwrap();
        assert_eq!(
            result.score, 1.0,
            "later def merge_sorted fence must win over a def merge sketch: {result:?}"
        );
    }

    #[tokio::test]
    async fn code_syntax_def_merge_without_sorted_is_not_strong() {
        let code = "def merge(a, b):\n    return a + b\n";
        let llm = MockLlm {
            response: text_response(code),
        };
        let result = probe_code_syntax(&llm).await.unwrap();
        assert_ne!(
            result.level,
            CapabilityLevel::Strong,
            "def merge without merge_sorted must not be Strong: {result:?}"
        );
    }

    #[tokio::test]
    async fn code_syntax_strong_for_return_paren() {
        let code = "def merge_sorted(a, b):\n    return(sorted(a + b))";
        let llm = MockLlm {
            response: text_response(code),
        };
        let result = probe_code_syntax(&llm).await.unwrap();
        assert_eq!(result.score, 1.0, "{result:?}");
    }

    #[tokio::test]
    async fn code_syntax_helper_return_is_not_strong() {
        let code = "\
def merge_sorted(a, b):
    result = []
    i = j = 0

return merge_sorted([1, 3], [2, 4])
";
        let result = probe_code_syntax(&MockLlm {
            response: text_response(code),
        })
        .await
        .unwrap();
        assert_ne!(
            result.score, 1.0,
            "return outside merge_sorted body must not be Strong: {result:?}"
        );
        assert_ne!(result.level, CapabilityLevel::Strong);
    }

    #[tokio::test]
    async fn code_syntax_medium_for_missing_return() {
        let code = "def merge_sorted(a, b):\n    result = a + b\n    result.sort()";
        let llm = MockLlm {
            response: text_response(code),
        };
        let result = probe_code_syntax(&llm).await.unwrap();
        assert_eq!(result.score, 0.5);
    }

    #[tokio::test]
    async fn code_syntax_weak_for_prose() {
        let llm = MockLlm {
            response: text_response(
                "To merge two sorted lists, you can use a two-pointer approach.",
            ),
        };
        let result = probe_code_syntax(&llm).await.unwrap();
        assert_eq!(result.score, 0.0);
        assert_eq!(result.level, CapabilityLevel::Weak);
    }

    #[tokio::test]
    async fn code_syntax_fenced_sentence_naming_def_is_not_strong() {
        let text = "\
```
I would write a function def merge_sorted that takes two lists \
and return a single sorted list.
```";
        let result = probe_code_syntax(&MockLlm {
            response: text_response(text),
        })
        .await
        .unwrap();
        assert_ne!(
            result.level,
            CapabilityLevel::Strong,
            "fenced sentence that only names def merge_sorted and return must not be Strong: {result:?}"
        );
        assert_eq!(
            result.score, 0.0,
            "name-only fenced sentence is not a function: {result:?}"
        );
    }

    #[tokio::test]
    async fn code_syntax_fenced_sentence_with_english_colon_is_not_strong() {
        let text = "\
```
I would write def merge_sorted that takes two lists: a and b and return a list
```";
        let result = probe_code_syntax(&MockLlm {
            response: text_response(text),
        })
        .await
        .unwrap();
        assert_ne!(
            result.level,
            CapabilityLevel::Strong,
            "fenced English colon after def merge_sorted must not be Strong: {result:?}"
        );
        assert_eq!(
            result.score, 0.0,
            "English colon name-drop is not a function: {result:?}"
        );
        assert_eq!(result.level, CapabilityLevel::Weak);
    }

    #[tokio::test]
    async fn code_syntax_prefers_def_paren_fence_after_english_colon_mention() {
        let text = "\
```
I would write def merge_sorted that takes two lists: a and b and return a list
```

```python
def merge_sorted(a, b):
    return a + b
```
";
        let code = extract_code_block(text).unwrap();
        assert!(
            code.contains("def merge_sorted("),
            "must prefer the fence with def merge_sorted(: {code:?}"
        );
        assert!(
            !code.contains("I would write"),
            "must not pick the English-colon name-drop fence: {code:?}"
        );
        let result = probe_code_syntax(&MockLlm {
            response: text_response(text),
        })
        .await
        .unwrap();
        assert_eq!(
            result.score, 1.0,
            "later def merge_sorted( fence must win over an English-colon mention: {result:?}"
        );
        assert_eq!(result.level, CapabilityLevel::Strong);
    }

    #[tokio::test]
    async fn code_syntax_prefers_def_paren_fence_after_name_mention() {
        let text = "\
```
I would write def merge_sorted and return a list
```

```python
def merge_sorted(a, b):
    return a + b
```
";
        let result = probe_code_syntax(&MockLlm {
            response: text_response(text),
        })
        .await
        .unwrap();
        assert_eq!(
            result.score, 1.0,
            "later def merge_sorted( fence must win over a name-only mention: {result:?}"
        );
        assert_eq!(result.level, CapabilityLevel::Strong);
    }

    #[tokio::test]
    async fn code_syntax_unfenced_prose_tokens_are_not_strong() {
        let llm = MockLlm {
            response: text_response(
                "I would write a function def merge_sorted that takes two lists \
                 and return a single sorted list.",
            ),
        };
        let result = probe_code_syntax(&llm).await.unwrap();
        assert_ne!(
            result.level,
            CapabilityLevel::Strong,
            "unfenced prose that only names def/return tokens must not be Strong: {result:?}"
        );
        assert_eq!(
            result.score, 0.0,
            "tokens in a sentence are not a function: {result:?}"
        );
        assert_eq!(result.level, CapabilityLevel::Weak);
    }

    #[tokio::test]
    async fn code_syntax_comment_then_real_unfenced_function_is_strong() {
        let code = "# def merge_sorted merges lists\ndef merge_sorted(a, b):\n    return a + b\n";
        let result = probe_code_syntax(&MockLlm {
            response: text_response(code),
        })
        .await
        .unwrap();
        assert_eq!(
            result.score, 1.0,
            "comment naming the token must not hide a real function: {result:?}"
        );
    }

    #[tokio::test]
    async fn code_syntax_sentence_with_paren_signature_is_not_strong() {
        for text in [
            "I would write def merge_sorted(a, b) and return a single sorted list.",
            "```\nI would write def merge_sorted(a, b) and return a single sorted list.\n```",
        ] {
            let result = probe_code_syntax(&MockLlm {
                response: text_response(text),
            })
            .await
            .unwrap();
            assert_eq!(
                result.score, 0.0,
                "sentence with def merge_sorted( plus return must not be Strong: {text:?} {result:?}"
            );
            assert_eq!(result.level, CapabilityLevel::Weak, "{text:?}");
        }
    }

    #[tokio::test]
    async fn code_syntax_english_paren_contents_not_strong() {
        let code = "def merge_sorted (two lists): and return a merged list";
        let result = probe_code_syntax(&MockLlm {
            response: text_response(code),
        })
        .await
        .unwrap();
        assert_eq!(
            result.score, 0.0,
            "English inside parens is not a parameter list: {result:?}"
        );
        assert_eq!(result.level, CapabilityLevel::Weak);
    }

    #[tokio::test]
    async fn code_syntax_english_same_line_body_not_strong() {
        let code = "def merge_sorted a, b: you should return one list";
        let result = probe_code_syntax(&MockLlm {
            response: text_response(code),
        })
        .await
        .unwrap();
        assert_eq!(
            result.score, 0.0,
            "English after a no-paren signature colon is not a body: {result:?}"
        );
        assert_eq!(result.level, CapabilityLevel::Weak);
    }

    #[tokio::test]
    async fn code_syntax_lecture_line_with_return_is_not_strong() {
        let code = "\
def merge_sorted(a, b):
    Use two pointers then return a + b
";
        let result = probe_code_syntax(&MockLlm {
            response: text_response(code),
        })
        .await
        .unwrap();
        assert_eq!(
            result.score, 0.0,
            "lecture line that only mentions return must be Weak: {result:?}"
        );
        assert_eq!(result.level, CapabilityLevel::Weak);
    }

    #[tokio::test]
    async fn code_syntax_english_return_phrase_is_not_strong() {
        for text in [
            "def merge_sorted(a, b): return a single sorted list",
            "```\ndef merge_sorted(a, b): return a single sorted list\n```",
            "def merge_sorted(a, b):\n    return a single sorted list\n",
        ] {
            let result = probe_code_syntax(&MockLlm {
                response: text_response(text),
            })
            .await
            .unwrap();
            assert_eq!(
                result.score, 0.0,
                "English return phrase is not a body: {text:?} {result:?}"
            );
            assert_eq!(result.level, CapabilityLevel::Weak, "{text:?}");
        }
    }

    #[tokio::test]
    async fn code_syntax_sentence_colon_return_phrase_is_not_strong() {
        let text = "I would write def merge_sorted(a, b): return a single sorted list.";
        let result = probe_code_syntax(&MockLlm {
            response: text_response(text),
        })
        .await
        .unwrap();
        assert_eq!(
            result.score, 0.0,
            "sentence with colon plus English return phrase must not be Strong: {result:?}"
        );
        assert_eq!(result.level, CapabilityLevel::Weak);
    }

    #[tokio::test]
    async fn code_syntax_unfenced_real_fn_after_name_fence_is_strong() {
        let text = "\
```
I would write def merge_sorted
```
def merge_sorted(a, b):
    return a + b
";
        let result = probe_code_syntax(&MockLlm {
            response: text_response(text),
        })
        .await
        .unwrap();
        assert_eq!(
            result.score, 1.0,
            "name-drop fence must not hide a later unfenced real function: {result:?}"
        );
        assert_eq!(result.level, CapabilityLevel::Strong);
    }

    #[tokio::test]
    async fn code_syntax_one_line_function_is_strong() {
        let code = "def merge_sorted(a, b): return a + b\n";
        let result = probe_code_syntax(&MockLlm {
            response: text_response(code),
        })
        .await
        .unwrap();
        assert_eq!(
            result.score, 1.0,
            "one-line def merge_sorted must stay Strong: {result:?}"
        );
    }

    #[tokio::test]
    async fn code_syntax_typed_signature_is_strong() {
        for code in [
            "def merge_sorted(a: list[int], b: list[int]) -> list[int]:\n    return a + b\n",
            "def merge_sorted(a: list, b: list):\n    return a + b\n",
        ] {
            let result = probe_code_syntax(&MockLlm {
                response: text_response(code),
            })
            .await
            .unwrap();
            assert_eq!(
                result.score, 1.0,
                "typed merge_sorted signature must be Strong: {code:?} {result:?}"
            );
            assert_eq!(result.level, CapabilityLevel::Strong, "{code:?}");
        }
    }

    #[tokio::test]
    async fn code_syntax_wrapped_typed_signature_is_strong() {
        let code = "\
def merge_sorted(
    a: list[int],
    b: list[int],
) -> list[int]:
    return a + b
";
        let result = probe_code_syntax(&MockLlm {
            response: text_response(code),
        })
        .await
        .unwrap();
        assert_eq!(
            result.score, 1.0,
            "wrapped typed merge_sorted must be Strong: {result:?}"
        );
        assert_eq!(result.level, CapabilityLevel::Strong);
    }

    #[tokio::test]
    async fn code_syntax_wrapped_params_with_hash_comments_is_strong() {
        let code = "\
def merge_sorted(
    a: list[int],  # already sorted
    b: list[int],  # already sorted
) -> list[int]:
    return a + b
";
        let result = probe_code_syntax(&MockLlm {
            response: text_response(code),
        })
        .await
        .unwrap();
        assert_eq!(
            result.score, 1.0,
            "wrapped typed params with # comments must be Strong: {result:?}"
        );
        assert_eq!(result.level, CapabilityLevel::Strong);
    }

    #[tokio::test]
    async fn code_syntax_trailing_comma_signature_is_strong() {
        let code =
            "def merge_sorted(a: list[int], b: list[int],) -> list[int]:\n    return a + b\n";
        let result = probe_code_syntax(&MockLlm {
            response: text_response(code),
        })
        .await
        .unwrap();
        assert_eq!(
            result.score, 1.0,
            "trailing-comma typed merge_sorted must be Strong: {result:?}"
        );
        assert_eq!(result.level, CapabilityLevel::Strong);
    }

    #[tokio::test]
    async fn code_syntax_star_args_signature_is_strong() {
        let code = "def merge_sorted(*lists):\n    return list(lists)\n";
        let result = probe_code_syntax(&MockLlm {
            response: text_response(code),
        })
        .await
        .unwrap();
        assert_eq!(
            result.score, 1.0,
            "*lists merge_sorted must be Strong: {result:?}"
        );
        assert_eq!(result.level, CapabilityLevel::Strong);
    }

    #[tokio::test]
    async fn code_syntax_ellipsis_assignment_is_not_strong() {
        let code = "def merge_sorted(a, b):\n    result = ...\n    return result\n";
        let result = probe_code_syntax(&MockLlm {
            response: text_response(code),
        })
        .await
        .unwrap();
        assert_ne!(
            result.score, 1.0,
            "ellipsis assignment stub must not be Strong: {result:?}"
        );
        assert_ne!(result.level, CapabilityLevel::Strong);
    }

    #[tokio::test]
    async fn code_syntax_default_arg_is_strong() {
        let code = "def merge_sorted(a, b=None):\n    return a + b\n";
        let result = probe_code_syntax(&MockLlm {
            response: text_response(code),
        })
        .await
        .unwrap();
        assert_eq!(
            result.score, 1.0,
            "default-arg merge_sorted must be Strong: {result:?}"
        );
        assert_eq!(result.level, CapabilityLevel::Strong);
    }

    #[tokio::test]
    async fn code_syntax_indented_no_paren_signature_is_strong() {
        let code = "def merge_sorted a, b:\n    return a + b\n";
        let result = probe_code_syntax(&MockLlm {
            response: text_response(code),
        })
        .await
        .unwrap();
        assert_eq!(
            result.score, 1.0,
            "no-paren comma params plus indented body must stay Strong: {result:?}"
        );
        assert_eq!(result.level, CapabilityLevel::Strong);
    }

    #[tokio::test]
    async fn length_empty_is_transient() {
        let llm = MockLlm {
            response: length_text_response(""),
        };
        let err = probe_code_syntax(&llm).await.expect_err("must refuse");
        assert!(
            matches!(&err, ProbeError::Transient(msg) if msg.contains("truncated")),
            "{err:?}"
        );
    }

    #[tokio::test]
    async fn length_incomplete_function_is_transient() {
        let llm = MockLlm {
            response: length_text_response("def merge_sorted(a, b):\n    result = ["),
        };
        let err = probe_code_syntax(&llm).await.expect_err("must refuse");
        assert!(
            matches!(&err, ProbeError::Transient(msg) if msg.contains("truncated")),
            "{err:?}"
        );
    }

    #[tokio::test]
    async fn length_complete_function_stays_strong() {
        let code = "\
```python
def merge_sorted(a, b):
    return a + b
```";
        let llm = MockLlm {
            response: length_text_response(code),
        };
        let result = probe_code_syntax(&llm).await.unwrap();
        assert_eq!(result.score, 1.0);
        assert_eq!(result.level, CapabilityLevel::Strong);
    }

    #[tokio::test]
    async fn code_syntax_weak_for_empty() {
        let llm = MockLlm {
            response: text_response(""),
        };
        let result = probe_code_syntax(&llm).await.unwrap();
        assert_eq!(result.score, 0.0);
    }

    #[test]
    fn extract_code_block_prefers_def_paren_over_name_mention() {
        let text = "\
```
I would write def merge_sorted
```

```python
def merge_sorted(a, b):
    return a + b
```
";
        let code = extract_code_block(text).unwrap();
        assert!(
            code.contains("def merge_sorted("),
            "must prefer the fence with def merge_sorted(: {code:?}"
        );
        assert!(
            !code.contains("I would write"),
            "must not pick the first name-mention fence: {code:?}"
        );
    }

    #[test]
    fn extract_code_block_python() {
        let text = "```python\ndef foo():\n    return 42\n```";
        assert!(
            extract_code_block(text).is_none(),
            "a fence that is not a real merge_sorted must fall back to the full text"
        );
    }

    #[test]
    fn extract_code_block_bare() {
        let text = "```\nprint(1)\n```";
        assert!(
            extract_code_block(text).is_none(),
            "a name-less fence must fall back to the full text"
        );
    }

    #[test]
    fn count_char_works() {
        assert_eq!(count_char("((()))", '('), 3);
        assert_eq!(count_char("((()))", ')'), 3);
        assert_eq!(count_char("abc", '('), 0);
    }
}