switchyard-libsy 0.2.0

Provider-neutral multi-LLM routing and orchestration for Switchyard
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
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Tool-result context signals extracted from the conversation history.
//!
//! The extractor walks normalized messages, finds tool calls and results,
//! pattern-matches their text against a curated error table, and aggregates
//! conversation-history metrics used by [`crate::StageRouter`].
//!
//! All logic is pure and deterministic — no I/O, no shared state.

#![allow(dead_code)]

use async_trait::async_trait;
use serde_json::Value;
use switchyard_protocol::{ContentBlock, Request};

use crate::Result;

use crate::core::processor::{Event, Processor};
use crate::core::state::State;

// ─── severity constants ───────────────────────────────────────────────────────

const SOFT: f32 = 0.3;
const HARD: f32 = 0.7;
const CRITICAL: f32 = 1.0;

// ─── pattern table ────────────────────────────────────────────────────────────

/// (name, severity, lower-cased substrings — any hit fires the pattern)
static ERROR_PATTERNS: &[(&str, f32, &[&str])] = &[
    (
        "oom",
        CRITICAL,
        &["out of memory", "memoryerror", "cannot allocate memory"],
    ),
    (
        "connection_refused",
        CRITICAL,
        &[
            "connection refused",
            "connectionrefusederror",
            "econnrefused",
        ],
    ),
    ("traceback", HARD, &["traceback (most recent call last)"]),
    (
        "import_error",
        HARD,
        &["modulenotfounderror:", "importerror:", "no module named "],
    ),
    (
        "cmd_not_found",
        HARD,
        &["command not found", "not found\n", "/usr/bin/env: "],
    ),
    ("assertion", HARD, &["assertionerror"]),
    ("value_error", HARD, &["valueerror:"]),
    ("syntax_error", HARD, &["syntaxerror:"]),
    (
        "timeout",
        HARD,
        &[
            "timed out",
            "timeouterror",
            "timeout expired",
            "deadline exceeded",
        ],
    ),
    (
        "no_such_file",
        HARD,
        &[
            "filenotfounderror:",
            "no such file or directory",
            // Claude Code Read-tool miss. Anchored as "file does not exist" (not a
            // bare "does not exist", which fires on `ls` output and prose) — trace-
            // mined across 1006 local trajectories at 22 true / 2 false positives.
            "file does not exist",
        ],
    ),
    // SOFT: plain non-zero exit without a recognisable exception traceback.
    (
        "exit_nonzero",
        SOFT,
        &[
            "exit code 1",
            "exit code 2",
            "exit status 1",
            "returned non-zero",
            "exited with code",
        ],
    ),
];

static EDIT_TOOL_NAMES: &[&str] = &[
    "edit",
    "multiedit",
    "notebookedit",
    "str_replace",
    "str_replace_based_edit_tool",
    "text_editor",
    "patch", // hermes's str_replace-style edit tool
];

static WRITE_TOOL_NAMES: &[&str] = &["write", "create_file", "new_file", "write_file"];

// Bash subcommand patterns. Lowercased; callers must lowercase the command
// before matching. Bucketed into write_count / edit_count alongside the
// dedicated `Write` / `Edit` tools.
static BASH_WRITE_PATTERNS: &[&str] = &[
    "cat >",
    "cat >>",
    "echo >",
    "echo >>",
    "tee ",
    "printf >",
    "printf >>",
    "> /",
    ">> /",
    "<< 'eof'",
    "<<eof",
    "<<'eof'",
    "<< eof",
];

static BASH_EDIT_PATTERNS: &[&str] = &[
    "sed -i",
    "sed --in-place",
    "awk -i inplace",
    "awk 'inplace=1'",
    "patch ",
    "patch -p",
    "perl -i",
    "perl -p -i",
    "perl -pi",
];

// Read-like Bash inspections. Match only when none of the write/edit patterns
// fire (redirection / in-place edit trumps the read intent of the command).
static BASH_READ_PATTERNS: &[&str] = &[
    "cat /", "cat ./", "cat ../", "grep ", "ls ", "ls -", "find ", "head ", "tail ", "wc ",
    "diff ", "which ", "ps ", "df ", "du ", "stat ", "file ", "less ", "more ",
];

static READ_TOOL_NAMES: &[&str] = &["read", "view", "read_file", "search_files"];

// Planning / scratchpad tool calls — investigative (non-producing) activity.
// `update_plan` is codex's equivalent of `todowrite`.
static PLAN_TOOL_NAMES: &[&str] = &["todowrite", "todo_write", "todo", "update_plan"];

// Tool names that route through Bash-command pattern matching. `bash` is
// claude-code's name; `shell_command` is codex's; `shell` / `local_shell_call`
// are seen on some OpenAI-derived harnesses; `terminal` is hermes's (it carries
// a `command` arg like the others, so its intent comes from the pattern match).
static BASH_TOOL_NAMES: &[&str] = &[
    "bash",
    "shell_command",
    "shell",
    "local_shell_call",
    "terminal",
];

// Prefer false negatives: tests_passed routes the picker to EFFICIENT, so a false
// positive would drop tier on an unfinished task.
static TEST_PASS_PHRASES: &[&str] = &[
    " passed",
    "passed in",
    "tests passed",
    "all tests passed",
    "test ok",
    "test result: ok",
    "passed.\n",
    "tests pass",
    "\nok ", // go test; newline-anchored to avoid "...lookup..." mid-text
    "",
];

// Literal failure phrases that cannot appear inside a clean run. Substring
// matched as-is. Patterns that pair with a count (e.g. "failed", "errors")
// are handled separately by `has_nonzero_failure_count` so "0 failed" /
// "0 errors" do not trigger a false negative.
static TEST_FAILURE_LITERAL: &[&str] = &["", "fatal:", "assertionerror", "error:"];

// Count-prefixed failure keywords. Trip only when a nonzero integer precedes
// the keyword (modulo whitespace), so cargo's "0 failed" and go's
// "0 errors" summaries on a clean run are not misread as failures.
static NUMERIC_FAILURE_KEYWORDS: &[&str] = &["failed", "failure", "failures", "errors", "error"];

/// Default sliding-window size for `recent_*` counts and windowed severity.
///
/// A short horizon captures "what is the agent doing right now" while keeping
/// signals sticky — an error or stall persists a few recovery turns instead of
/// flickering off the moment one clean result lands. Override per request by
/// passing a window to [`ToolSignals::from_request`].
pub const DEFAULT_RECENT_WINDOW: usize = 3;

// ─── output type ─────────────────────────────────────────────────────────────

/// Tool-execution signals extracted from a normalized [`Request`].
///
/// A request-side processor stores these signals in [`State`](crate::State) for
/// [`crate::StageRouter`] and its classifier to consume.
#[derive(Clone, Debug, Default)]
pub struct ToolSignals {
    /// Max severity across the recent window (last `recent_window` tool results):
    /// `0.0` clean · `0.3` soft (exit_nonzero) · `0.7` hard · `1.0` critical.
    /// Windowed so an error persists through the recovery turns instead of clearing
    /// the instant the next result is clean.
    pub severity: f32,
    /// Consecutive clean tool results back from the most recent. `0` if the last failed.
    pub no_error_streak: u32,
    /// Total edit-style tool calls in the request.
    pub edit_count: u32,
    /// Total write-style tool calls in the request.
    pub write_count: u32,
    /// Read-type calls (Read tool + read-like Bash). Used by the build-pit gate.
    pub read_count: u32,
    /// TodoWrite / planning tool calls. Investigative (non-producing) activity —
    /// recent todowrites distinguish `exploring` from `spinning` in the scorer.
    pub todowrite_count: u32,
    /// Edit-type calls within the configured recent window (default: [`DEFAULT_RECENT_WINDOW`]).
    pub recent_edit_count: u32,
    /// Write-type calls within the configured recent window (default: [`DEFAULT_RECENT_WINDOW`]).
    pub recent_write_count: u32,
    /// Read-type calls within the configured recent window (default: [`DEFAULT_RECENT_WINDOW`]).
    pub recent_read_count: u32,
    /// TodoWrite calls within the configured recent window (default: [`DEFAULT_RECENT_WINDOW`]).
    pub recent_todowrite_count: u32,
    /// Consecutive trailing tool calls in the `Other` category (no Write/Edit/Read/
    /// Plan match). Surfaced in the classifier state summary; not scored directly.
    pub pure_bash_streak: u32,
    /// At least one of the last three tool results matched a test-pass pattern.
    pub tests_passed: bool,
    /// Message-count proxy for turn depth. Wire-format dependent (Anthropic batches
    /// tool results into fewer messages than OpenAI-chat), so gates keyed on it are
    /// approximate across request origins.
    pub turn_depth: u32,
    /// The request carries a context-compaction summary (the agent's context was
    /// summarised after overflowing). Compaction resets the router's accumulated
    /// signals, so a task that was on the strong tier de-escalates back to weak — the
    /// picker uses this to force + hold the strong tier. Self-latching: the summary
    /// stays in the context prefix on every subsequent turn.
    pub compacted: bool,
}

impl ToolSignals {
    /// Extracts tool and progress signals from `request`.
    ///
    /// `window_size` limits recent counters to the newest tool results. `None`
    /// uses [`DEFAULT_RECENT_WINDOW`].
    pub fn from_request(request: &Request, window_size: Option<usize>) -> Self {
        extract_tool_signals_with_window(request, window_size.unwrap_or(DEFAULT_RECENT_WINDOW))
    }
}

// `command` is the lowercased Bash command line; None for non-Bash tools.
#[derive(Debug, Clone)]
struct ObservedToolCall {
    name: String,
    command: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ToolCategory {
    Write,
    Edit,
    Read,
    Plan,
    Other,
}

/// Request-side processor that extracts tool-result signals from each request
/// and stores them on the request `State` for downstream routing.
#[derive(Debug, Clone)]
pub struct ToolSignalProcessor {
    /// Number of trailing tool results the `recent_*` counts and windowed
    /// severity are computed over.
    pub recent_window: usize,
}

impl Default for ToolSignalProcessor {
    fn default() -> Self {
        Self {
            recent_window: DEFAULT_RECENT_WINDOW,
        }
    }
}

#[async_trait]
impl Processor<State> for ToolSignalProcessor {
    async fn process(&self, state: &mut State, event: Event<'_>) -> Result<()> {
        if let Event::Request(req) = event {
            let tool_signal = ToolSignals::from_request(req, Some(self.recent_window));
            state.tool_signals = Some(tool_signal);
        }
        Ok(())
    }
}

fn classify_tool_call(name: &str, command: Option<&str>) -> ToolCategory {
    let lower = name.to_lowercase();
    if WRITE_TOOL_NAMES.contains(&lower.as_str()) {
        return ToolCategory::Write;
    }
    if EDIT_TOOL_NAMES.contains(&lower.as_str()) {
        return ToolCategory::Edit;
    }
    if READ_TOOL_NAMES.contains(&lower.as_str()) {
        return ToolCategory::Read;
    }
    if PLAN_TOOL_NAMES.contains(&lower.as_str()) {
        return ToolCategory::Plan;
    }
    if BASH_TOOL_NAMES.contains(&lower.as_str())
        && let Some(cmd) = command
    {
        // Write/edit redirection trumps read-like operands.
        if BASH_WRITE_PATTERNS.iter().any(|p| cmd.contains(p)) {
            return ToolCategory::Write;
        }
        if BASH_EDIT_PATTERNS.iter().any(|p| cmd.contains(p)) {
            return ToolCategory::Edit;
        }
        if BASH_READ_PATTERNS.iter().any(|p| cmd.contains(p)) {
            return ToolCategory::Read;
        }
    }
    ToolCategory::Other
}

// ─── extraction entry point ───────────────────────────────────────────────────

/// Extract all tool-execution signals from a normalized [`Request`].
///
/// Returns [`ToolSignals::default()`] when the message history contains no tool
/// activity, so callers can always inspect the signal fields.
fn extract_tool_signals_with_window(request: &Request, recent_window: usize) -> ToolSignals {
    // Read the decoded conversation, not the raw body: every inbound format lands
    // in the same shape here, so the signals do not depend on knowing which one it
    // arrived as.
    let messages = &request.llm_request.messages;
    let mut tool_texts: Vec<String> = Vec::new();
    let mut tool_calls: Vec<ObservedToolCall> = Vec::new();
    let mut compacted = false;

    for message in messages {
        for block in &message.content {
            match block {
                ContentBlock::ToolCall(call) => {
                    tool_calls.push(ObservedToolCall {
                        name: call.name.clone(),
                        command: command_of(&call.arguments),
                    });
                }
                ContentBlock::ToolResult(result) => {
                    let text = result
                        .content
                        .iter()
                        .filter_map(text_of)
                        .collect::<Vec<_>>()
                        .join("\n");
                    if !text.is_empty() {
                        tool_texts.push(text);
                    }
                }
                // Compaction is detected anywhere in the conversation: the summary
                // stays in the prefix on every later turn, so this self-latches
                // once it fires.
                ContentBlock::Text { text } => {
                    compacted |= text.to_lowercase().contains(COMPACTION_MARKER);
                }
                _ => {}
            }
        }
    }

    let mut signal = build_signal(tool_texts, tool_calls, messages.len() as u32, recent_window);
    signal.compacted = compacted;
    signal
}

/// Distinctive preamble Claude Code injects as a user message when it compacts an
/// overflowed context. Matched case-insensitively; normal task text never contains it.
const COMPACTION_MARKER: &str = "session is being continued";

/// The shell command a tool call carries, when it has one. Harnesses name the
/// field `command`; anything else is a tool whose category comes from its name.
fn command_of(arguments: &Value) -> Option<String> {
    arguments
        .get("command")
        .and_then(Value::as_str)
        .map(str::to_lowercase)
}

/// Text carried by a content block, ignoring the non-textual kinds.
fn text_of(block: &ContentBlock) -> Option<&str> {
    match block {
        ContentBlock::Text { text } | ContentBlock::Refusal { text } => Some(text.as_str()),
        _ => None,
    }
}

fn build_signal(
    tool_texts: Vec<String>,
    tool_calls: Vec<ObservedToolCall>,
    turn_depth: u32,
    recent_window: usize,
) -> ToolSignals {
    // Windowed severity: take the MAX severity across the last `recent_window` tool
    // results rather than only the last one. An error's severity then persists for
    // the recent window and decays out of it — parallel to the windowed `recent_*`
    // counts — so a fix written a couple of turns after an error still routes on the
    // error signal instead of the router flapping straight back to the weak tier.
    let sev_start = tool_texts.len().saturating_sub(recent_window.max(1));
    let mut severity = 0.0f32;
    for text in &tool_texts[sev_start..] {
        let (sev, _patterns) = classify_text(text);
        if sev > severity {
            severity = sev;
        }
    }

    let no_error_streak = compute_no_error_streak(&tool_texts);

    // Single pass: cumulative + sliding-window counters together. Also tracks
    // the trailing pure-bash streak (consecutive `Other`-category calls back
    // from the end) — the build-pit proxy.
    let recent_start = tool_calls.len().saturating_sub(recent_window);
    let mut write_count = 0u32;
    let mut edit_count = 0u32;
    let mut read_count = 0u32;
    let mut todowrite_count = 0u32;
    let mut recent_write_count = 0u32;
    let mut recent_edit_count = 0u32;
    let mut recent_read_count = 0u32;
    let mut recent_todowrite_count = 0u32;
    let mut pure_bash_streak = 0u32;
    let mut streak_open = true;
    for (i, tc) in tool_calls.iter().enumerate().rev() {
        let cat = classify_tool_call(&tc.name, tc.command.as_deref());
        if streak_open {
            if matches!(cat, ToolCategory::Other) {
                pure_bash_streak += 1;
            } else {
                streak_open = false;
            }
        }
        match cat {
            ToolCategory::Write => {
                write_count += 1;
                if i >= recent_start {
                    recent_write_count += 1;
                }
            }
            ToolCategory::Edit => {
                edit_count += 1;
                if i >= recent_start {
                    recent_edit_count += 1;
                }
            }
            ToolCategory::Read => {
                read_count += 1;
                if i >= recent_start {
                    recent_read_count += 1;
                }
            }
            ToolCategory::Plan => {
                todowrite_count += 1;
                if i >= recent_start {
                    recent_todowrite_count += 1;
                }
            }
            ToolCategory::Other => {}
        }
    }

    let tests_passed = detect_tests_passed(&tool_texts, recent_window);

    ToolSignals {
        severity,
        no_error_streak,
        edit_count,
        write_count,
        read_count,
        todowrite_count,
        recent_edit_count,
        recent_write_count,
        recent_read_count,
        recent_todowrite_count,
        pure_bash_streak,
        tests_passed,
        turn_depth,
        // Set by extract_tool_signals_with_window after the format-specific extract,
        // which scans all message contents for the compaction marker.
        compacted: false,
    }
}

// ─── pure helpers ─────────────────────────────────────────────────────────────

/// Normalise a JSON tool-result content value to a plain string.
fn content_to_text(content: Option<&Value>) -> Option<String> {
    match content? {
        Value::String(s) => Some(s.clone()),
        Value::Array(blocks) => {
            let parts: Vec<&str> = blocks
                .iter()
                .filter_map(|b| {
                    b.as_object()
                        .filter(|o| o.get("type").and_then(Value::as_str) == Some("text"))
                        .and_then(|o| o.get("text"))
                        .and_then(Value::as_str)
                })
                .collect();
            if parts.is_empty() {
                None
            } else {
                Some(parts.join("\n"))
            }
        }
        _ => None,
    }
}

/// Match `text` against the error pattern table.
///
/// Returns `(max_severity, matched_pattern_names)`.
pub(crate) fn classify_text(text: &str) -> (f32, Vec<String>) {
    let lower = text.to_lowercase();
    let mut patterns = Vec::new();
    let mut severity: f32 = 0.0;
    for (name, sev, substrings) in ERROR_PATTERNS {
        if substrings.iter().any(|sub| lower.contains(sub)) {
            patterns.push(name.to_string());
            severity = severity.max(*sev);
        }
    }
    (severity, patterns)
}

fn compute_no_error_streak(tool_texts: &[String]) -> u32 {
    let mut streak = 0u32;
    for text in tool_texts.iter().rev() {
        let (sev, _) = classify_text(text);
        if sev > 0.0 {
            break;
        }
        streak += 1;
    }
    streak
}

fn detect_tests_passed(tool_texts: &[String], recent_window: usize) -> bool {
    let start = tool_texts.len().saturating_sub(recent_window.max(1));
    tool_texts[start..].iter().any(|text| {
        let lower = text.to_lowercase();
        TEST_PASS_PHRASES.iter().any(|p| lower.contains(p))
            && !TEST_FAILURE_LITERAL.iter().any(|p| lower.contains(p))
            && !has_nonzero_failure_count(&lower)
    })
}

// True iff `lower` contains a `NUMERIC_FAILURE_KEYWORDS` token preceded
// (modulo whitespace) by a nonzero integer. The "modulo whitespace" lets
// "1 failed", "1\nfailed", and "1  failed" all trip; the nonzero guard
// keeps cargo's "0 failed" / go's "0 errors" / pytest's "0 errors in"
// summaries from being misread as failures on a clean run.
fn has_nonzero_failure_count(lower: &str) -> bool {
    for kw in NUMERIC_FAILURE_KEYWORDS {
        let mut cursor = 0usize;
        while let Some(rel) = lower[cursor..].find(kw) {
            let kw_start = cursor + rel;
            let kw_end = kw_start + kw.len();
            // Word boundary AFTER the keyword — "errors" mid-word (e.g.
            // "errored") shouldn't count as a failure-count site.
            let boundary_after = lower[kw_end..]
                .chars()
                .next()
                .is_none_or(|c| !c.is_ascii_alphanumeric());
            if boundary_after {
                let prefix = &lower[..kw_start];
                let trimmed = prefix.trim_end_matches(|c: char| c.is_whitespace());
                let digits_rev: String = trimmed
                    .chars()
                    .rev()
                    .take_while(|c| c.is_ascii_digit())
                    .collect();
                if !digits_rev.is_empty() && digits_rev.chars().any(|d| d != '0') {
                    return true;
                }
            }
            cursor = kw_start + kw.len();
        }
    }
    false
}

// ─── tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use switchyard_protocol::{ContentBlock, LlmRequest, Message, Role, ToolCall, ToolResult};

    fn with_messages(messages: Vec<Message>) -> Request {
        Request {
            llm_request: LlmRequest {
                messages,
                ..LlmRequest::default()
            },
            raw_request: None,
            metadata: None,
        }
    }

    // assistant message with a single named tool call
    fn tc(name: &str) -> Message {
        Message {
            role: Role::Assistant,
            content: vec![ContentBlock::ToolCall(ToolCall {
                id: String::new(),
                name: name.to_string(),
                arguments: json!({}),
            })],
        }
    }

    // assistant Bash message carrying `command`
    fn bash(command: &str) -> Message {
        Message {
            role: Role::Assistant,
            content: vec![ContentBlock::ToolCall(ToolCall {
                id: String::new(),
                name: "Bash".to_string(),
                arguments: json!({"command": command}),
            })],
        }
    }

    // a tool result message (goes in a user-role message, as in Anthropic's normalised form)
    fn tr(text: &str) -> Message {
        Message {
            role: Role::User,
            content: vec![ContentBlock::ToolResult(ToolResult {
                tool_call_id: String::new(),
                content: vec![ContentBlock::Text {
                    text: text.to_string(),
                }],
                is_error: None,
            })],
        }
    }

    #[test]
    fn clean_text_has_zero_severity() {
        let (sev, patterns) = classify_text("everything went fine");
        assert_eq!(sev, 0.0);
        assert!(patterns.is_empty());
    }

    #[test]
    fn traceback_is_hard() {
        let (sev, patterns) = classify_text("Traceback (most recent call last):\n  ValueError");
        assert_eq!(sev, HARD);
        assert!(patterns.contains(&"traceback".to_string()));
    }

    #[test]
    fn oom_is_critical() {
        let (sev, _) = classify_text("Out of memory: kill process 1234");
        assert_eq!(sev, CRITICAL);
    }

    #[test]
    fn severity_is_max_across_patterns() {
        // exit_nonzero (SOFT) + traceback (HARD) → HARD.
        let (sev, _) = classify_text("exit code 1\nTraceback (most recent call last):");
        assert_eq!(sev, HARD);
    }

    #[test]
    fn file_does_not_exist_is_hard() {
        // Claude Code Read-tool miss. Trace-mined addition (22 true / 2 false positives).
        let (sev, patterns) =
            classify_text("Error: File does not exist. Note: current working directory is /app.");
        assert_eq!(sev, HARD);
        assert!(patterns.contains(&"no_such_file".to_string()));
    }

    #[test]
    fn bare_does_not_exist_stays_clean() {
        // Precision guard: only the anchored "file does not exist" fires, so a bare
        // "does not exist" in prose or directory output must not trip a false error.
        let (sev, _) = classify_text("The directory does not exist yet, creating it now.");
        assert_eq!(sev, 0.0);
    }

    #[test]
    fn no_error_streak_all_clean() {
        let texts = vec!["ok".to_string(), "all good".to_string()];
        assert_eq!(compute_no_error_streak(&texts), 2);
    }

    #[test]
    fn no_error_streak_stops_at_error() {
        let texts = vec![
            "Traceback (most recent call last):".to_string(),
            "ok".to_string(),
            "ok".to_string(),
        ];
        assert_eq!(compute_no_error_streak(&texts), 2);
    }

    #[test]
    fn tests_passed_detects_pytest_output() {
        assert!(detect_tests_passed(
            &["====== 5 passed in 0.12s ======".to_string()],
            DEFAULT_RECENT_WINDOW
        ));
    }

    #[test]
    fn tests_passed_ignores_partial_failures() {
        assert!(!detect_tests_passed(
            &["2 failed, 5 passed in 0.56s".to_string()],
            DEFAULT_RECENT_WINDOW
        ));
    }

    #[test]
    fn severity_is_windowed_over_recent_results() {
        // An error two results back, then two clean results.
        let request = with_messages(vec![
            tr("Traceback (most recent call last):\n  ValueError"),
            tr("ok"),
            tr("ok"),
        ]);
        // window covers the error → severity persists (max over the window)
        assert_eq!(extract_tool_signals_with_window(&request, 3).severity, HARD);
        // window of 1 sees only the last (clean) result → severity has decayed out
        assert_eq!(extract_tool_signals_with_window(&request, 1).severity, 0.0);
    }

    #[test]
    fn extract_openai_chat_tool_results() {
        let request = with_messages(vec![
            Message::text(Role::User, "do something"),
            tc("Edit"),
            tr("Traceback (most recent call last):\n  ValueError"),
        ]);
        let sig = ToolSignals::from_request(&request, None);
        assert_eq!(sig.severity, HARD);
        assert_eq!(sig.edit_count, 1);
        assert_eq!(sig.turn_depth, 3);
    }

    #[test]
    fn extract_anthropic_tool_results() {
        let request = with_messages(vec![tr("Traceback (most recent call last):\n  ValueError")]);
        let sig = ToolSignals::from_request(&request, None);
        assert_eq!(sig.severity, HARD);
    }

    #[test]
    fn extract_responses_api_tool_results() {
        let request = with_messages(vec![tc("Write"), tr("file written successfully")]);
        let sig = ToolSignals::from_request(&request, None);
        assert_eq!(sig.severity, 0.0);
        assert_eq!(sig.write_count, 1);
    }

    #[test]
    fn recent_window_counts_only_last_default_window_tool_calls() {
        // 5 writes + 1 edit at the end → the default window (3) should see
        // the last 3 calls: 1 edit + 2 writes (not all 6 calls).
        let request = with_messages(vec![
            tc("Write"),
            tr("ok"),
            tc("Write"),
            tr("ok"),
            tc("Write"),
            tr("ok"),
            tc("Write"),
            tr("ok"),
            tc("Write"),
            tr("ok"),
            tc("Edit"),
            tr("ok"),
        ]);
        let sig = ToolSignals::from_request(&request, None);
        assert_eq!(sig.write_count, 5);
        assert_eq!(sig.edit_count, 1);
        assert_eq!(sig.recent_write_count, 2);
        assert_eq!(sig.recent_edit_count, 1);
    }

    #[test]
    fn recent_window_size_is_caller_overridable() {
        // Same six tool calls (1 edit at the end, 5 writes before).
        // With recent_window=3 → recent_writes=2, recent_edits=1.
        // With recent_window=6 → recent_writes=5, recent_edits=1 (all calls).
        let request = with_messages(vec![
            tc("Write"),
            tr("ok"),
            tc("Write"),
            tr("ok"),
            tc("Write"),
            tr("ok"),
            tc("Write"),
            tr("ok"),
            tc("Write"),
            tr("ok"),
            tc("Edit"),
            tr("ok"),
        ]);
        let narrow = extract_tool_signals_with_window(&request, 3);
        assert_eq!(narrow.recent_write_count, 2);
        assert_eq!(narrow.recent_edit_count, 1);

        let wide = extract_tool_signals_with_window(&request, 6);
        assert_eq!(wide.recent_write_count, 5);
        assert_eq!(wide.recent_edit_count, 1);
    }

    #[test]
    fn compaction_marker_sets_compacted() {
        // The compaction summary is a user message carrying Claude Code's preamble.
        let request = with_messages(vec![
            Message::text(
                Role::User,
                "This session is being continued from a previous conversation that ran out of context.",
            ),
            bash("ls"),
        ]);
        assert!(ToolSignals::from_request(&request, None).compacted);
    }

    #[test]
    fn no_compaction_marker_stays_uncompacted() {
        let request = with_messages(vec![
            Message::text(Role::User, "Write a script that parses the log file."),
            bash("ls"),
        ]);
        assert!(!ToolSignals::from_request(&request, None).compacted);
    }

    #[test]
    fn bash_heredoc_counts_as_write() {
        // Claude Code's pattern on TB 2.0 — write a scratch file via heredoc.
        let request = with_messages(vec![bash("cat > /tmp/test.py <<'EOF'\nprint(1)\nEOF")]);
        let sig = ToolSignals::from_request(&request, None);
        assert_eq!(
            sig.write_count, 1,
            "Bash heredoc should bucket into write_count"
        );
        assert_eq!(sig.edit_count, 0);
    }

    #[test]
    fn bash_sed_inplace_counts_as_edit() {
        let request = with_messages(vec![bash("sed -i 's/foo/bar/g' /app/file.py")]);
        let sig = ToolSignals::from_request(&request, None);
        assert_eq!(
            sig.edit_count, 1,
            "Bash sed -i should bucket into edit_count"
        );
        assert_eq!(sig.write_count, 0);
    }

    #[test]
    fn bash_non_mutating_does_not_count() {
        // ls, cat, grep — should not increment either counter.
        let request = with_messages(vec![bash("ls -la /app"), bash("cat /app/main.py")]);
        let sig = ToolSignals::from_request(&request, None);
        assert_eq!(sig.write_count, 0);
        assert_eq!(sig.edit_count, 0);
    }

    #[test]
    fn tests_passed_detects_pytest_with_failure_block() {
        // Mixed pytest run: 2 failed + 5 passed → NOT considered tests_passed.
        assert!(!detect_tests_passed(
            &["2 failed, 5 passed in 0.56s".to_string()],
            DEFAULT_RECENT_WINDOW
        ));
    }

    #[test]
    fn tests_passed_accepts_cargo_clean_summary() {
        // Cargo's clean-run summary contains "0 failed" — must not trip the
        // failure list (regression: previously substring-matched "failed").
        assert!(detect_tests_passed(
            &["running 3 tests\ntest result: ok. 3 passed; 0 failed; 0 ignored".to_string()],
            DEFAULT_RECENT_WINDOW
        ));
    }

    #[test]
    fn tests_passed_rejects_cargo_real_failure() {
        // Cargo's actual-failure summary: nonzero count before "failed".
        assert!(!detect_tests_passed(
            &["running 3 tests\ntest result: FAILED. 2 passed; 1 failed; 0 ignored".to_string()],
            DEFAULT_RECENT_WINDOW
        ));
    }

    #[test]
    fn tests_passed_accepts_go_clean_summary() {
        // Go test's clean-run "0 errors" must not trip (regression).
        assert!(detect_tests_passed(
            &["ok  github.com/foo/bar\t0.012s (5 passed, 0 errors)".to_string()],
            DEFAULT_RECENT_WINDOW
        ));
    }

    #[test]
    fn tests_passed_accepts_pytest_zero_errors() {
        // Pytest long-form: "0 errors in 0.3s" on a clean run.
        assert!(detect_tests_passed(
            &["5 passed, 0 errors in 0.30s".to_string()],
            DEFAULT_RECENT_WINDOW
        ));
    }

    #[test]
    fn tests_passed_detects_diy_checkmark() {
        assert!(detect_tests_passed(
            &["✓ all checks passed".to_string()],
            DEFAULT_RECENT_WINDOW
        ));
    }

    #[test]
    fn anthropic_bash_heredoc_extracts_command() {
        // Anthropic format: tool_use.input is an object, not a JSON string.
        let request = with_messages(vec![bash("cat > /tmp/foo.txt << 'EOF'\nhi\nEOF")]);
        let sig = ToolSignals::from_request(&request, None);
        assert_eq!(
            sig.write_count, 1,
            "Anthropic Bash heredoc must also be detected"
        );
    }

    #[test]
    fn recent_window_falls_back_to_full_history_when_short() {
        let request = with_messages(vec![tc("Write")]);
        let sig = ToolSignals::from_request(&request, None);
        assert_eq!(sig.recent_write_count, 1);
        assert_eq!(sig.recent_edit_count, 0);
    }

    #[test]
    fn clean_tool_result_has_zero_severity_and_non_empty_streak() {
        let request = with_messages(vec![tr("output ok"), tr("another ok")]);
        let sig = ToolSignals::from_request(&request, None);
        assert_eq!(sig.severity, 0.0);
        assert_eq!(sig.no_error_streak, 2);
    }

    // ─── asymmetric-signal extensions ────────────────────────────────────

    #[test]
    fn todowrite_classifies_as_plan() {
        assert_eq!(classify_tool_call("TodoWrite", None), ToolCategory::Plan);
        assert_eq!(classify_tool_call("todo_write", None), ToolCategory::Plan);
    }

    #[test]
    fn codex_update_plan_classifies_as_plan() {
        assert_eq!(classify_tool_call("update_plan", None), ToolCategory::Plan);
    }

    #[test]
    fn codex_shell_command_runs_bash_pattern_match() {
        // shell_command + heredoc -> Write.
        assert_eq!(
            classify_tool_call("shell_command", Some("cat > /app/foo.py <<'eof'\nx=1\neof")),
            ToolCategory::Write,
        );
        // shell_command + read-like inspection -> Read.
        assert_eq!(
            classify_tool_call("shell_command", Some("ls /app")),
            ToolCategory::Read,
        );
        // shell_command without matching patterns -> Other.
        assert_eq!(
            classify_tool_call("shell_command", Some("./run_tests.sh")),
            ToolCategory::Other,
        );
    }

    #[test]
    fn read_tool_classifies_as_read() {
        assert_eq!(classify_tool_call("Read", None), ToolCategory::Read);
        assert_eq!(classify_tool_call("View", None), ToolCategory::Read);
    }

    #[test]
    fn hermes_tool_names_classify() {
        // Hermes (NousResearch) file tools route by name.
        assert_eq!(classify_tool_call("write_file", None), ToolCategory::Write);
        assert_eq!(classify_tool_call("patch", None), ToolCategory::Edit);
        assert_eq!(classify_tool_call("read_file", None), ToolCategory::Read);
        assert_eq!(classify_tool_call("search_files", None), ToolCategory::Read);
        // Hermes runs shell through `terminal`, which carries a `command` arg,
        // so its intent comes from the Bash-pattern match like codex's shell_command.
        assert_eq!(
            classify_tool_call("terminal", Some("sed -i 's/a/b/' /app/x.py")),
            ToolCategory::Edit,
        );
        assert_eq!(
            classify_tool_call("terminal", Some("grep foo /app")),
            ToolCategory::Read,
        );
        assert_eq!(
            classify_tool_call("terminal", Some("./run_tests.sh")),
            ToolCategory::Other,
        );
    }

    #[test]
    fn bash_read_patterns_classify_as_read() {
        let cases = [
            "cat /etc/passwd",
            "grep foo bar.txt",
            "ls /app",
            "find . -name '*.py'",
        ];
        for cmd in cases {
            assert_eq!(
                classify_tool_call("Bash", Some(cmd)),
                ToolCategory::Read,
                "expected Read for {cmd}"
            );
        }
    }

    #[test]
    fn bash_write_precedence_over_read() {
        // `cat /file > out` contains both `cat /` (read) and ` > ` (write);
        // write redirection must win.
        assert_eq!(
            classify_tool_call("Bash", Some("cat /etc/hosts > /tmp/out")),
            ToolCategory::Write,
        );
    }

    #[test]
    fn pure_bash_streak_counts_trailing_other() {
        // 5 trailing non-classified Bash calls → streak == 5.
        let request = with_messages(vec![
            bash("make"),
            tr("ok"),
            bash("./configure"),
            tr("ok"),
            bash("make install"),
            tr("ok"),
            bash("./run.sh"),
            tr("ok"),
            bash("./test"),
            tr("ok"),
        ]);
        let sig = ToolSignals::from_request(&request, None);
        assert_eq!(sig.pure_bash_streak, 5);
        assert_eq!(sig.write_count, 0);
        assert_eq!(sig.read_count, 0);
    }

    #[test]
    fn pure_bash_streak_resets_on_write() {
        let request = with_messages(vec![bash("make"), tr("ok"), tc("Write"), tr("ok")]);
        let sig = ToolSignals::from_request(&request, None);
        assert_eq!(sig.pure_bash_streak, 0);
        assert_eq!(sig.write_count, 1);
    }

    #[test]
    fn recent_window_tracks_todowrite_and_read() {
        // Final 3 tool calls: TodoWrite, Read, TodoWrite.
        let request = with_messages(vec![
            bash("make"),
            tr("ok"),
            tc("TodoWrite"),
            tr("ok"),
            tc("Read"),
            tr("ok"),
            tc("TodoWrite"),
            tr("ok"),
        ]);
        let sig = ToolSignals::from_request(&request, None);
        assert_eq!(sig.todowrite_count, 2);
        assert_eq!(sig.recent_todowrite_count, 2);
        assert_eq!(sig.read_count, 1);
        assert_eq!(sig.recent_read_count, 1);
    }
}