switchyard-libsy 0.3.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
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Trajectory-judge components for the escalation router — the judge, its verdict policy, and
//! the transcript condenser they read.
//!
//! [`build_judge`] is the whole surface; the confirmation policy that consumes its verdicts
//! lives with the assembled algorithm in [`crate::algorithms::escalation`].

use serde::Deserialize;
use serde_json::Value;
use switchyard_protocol::{Category, ContentBlock, InstructionBlock, Message, Role};

use super::classifier_contract::{ClassifierContract, ClassifierContractConfig};
use super::llm_judge::{
    ClassifierInput, JudgeClassifier, JudgePolicy, JudgeRuntimeConfig, SerdeDecoder,
    StructuredJudge,
};
use crate::core::algorithm::Driver;
use crate::core::classifier::{Classification, Score};
use crate::core::state::State;
use crate::{LibsyError, Result};
use switchyard_protocol::Request;

const PROMPT_TEMPLATE: &str = include_str!("../../prompts/escalation/prompt.md");
const SCHEMA_TEMPLATE: &str = include_str!("../../prompts/escalation/schema.json");

/// Separator marking where [`truncate_middle`] dropped a message's interior.
const TRIM_MARKER: &str = " ...[trimmed] ";

/// Suffix marking a transcript cut off by [`MAX_REQUEST_CHARS`].
const TRUNCATION_SUFFIX: &str = "...<truncated>";

/// Per-message cap for system and developer anchors, which carry no trajectory signal but
/// which coding-agent harnesses make very large.
const SYSTEM_CHARS: usize = 1_000;

/// Per-message cap for task-framing user messages — every user message that precedes the first
/// assistant reply. Coding-agent harnesses often send environment boilerplate as the first user
/// message and the task itself as the second, so anchoring only the first would pin the
/// boilerplate and let the task scroll out of the window. Feature specifications run to several
/// thousand characters, so this gets the widest anchor budget.
const TASK_CHARS: usize = 4_000;

/// Backstop on the assembled transcript; the per-message caps normally bind first.
const MAX_REQUEST_CHARS: usize = 18_000;

/// The tuning surface for the trajectory judge.
///
/// The routing settings retain their benchmarked defaults. Everything else is a fixed invariant
/// (the constants above).
#[derive(Clone, Debug, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct EscalationJudgeConfig {
    /// Consecutive escalate verdicts required before a turn moves to the capable tier, which
    /// is also the turn that latches the session. Any decline clears the streak.
    /// `1` escalates on the first verdict; the router's main cost dial.
    /// `2` or higher needs a session id, since the streak is retained per session.
    pub confirmations: u32,
    /// Trailing messages shown on top of the anchors. A loop longer than this is invisible.
    pub recent_turn_window: usize,
    /// Per-message cap inside the trailing window.
    pub window_message_chars: usize,
}

impl EscalationJudgeConfig {
    /// Rejects settings that would leave the judge with nothing useful to read.
    fn validate(&self) -> Result<()> {
        let reject = |message: String| Err(LibsyError::AlgorithmError { message });
        if self.confirmations == 0 {
            return reject("confirmations must be at least 1".to_string());
        }
        if self.recent_turn_window == 0 {
            return reject("recent_turn_window must be at least 1".to_string());
        }
        if self.window_message_chars < 50 {
            return reject(format!(
                "window_message_chars must be at least 50, got {}",
                self.window_message_chars
            ));
        }
        Ok(())
    }
}

impl Default for EscalationJudgeConfig {
    fn default() -> Self {
        Self {
            confirmations: 2,
            recent_turn_window: 28,
            window_message_chars: 500,
        }
    }
}

/// The judge's verdict. The schema also requires a `reason`, which makes the judge state its
/// case and measurably sharpens the verdict. Routing reads only the boolean; the reason is
/// kept solely so an operator can see why the judge held or escalated when the
/// `switchyard_libsy::algorithms::util::escalation` target is enabled at `debug`.
#[derive(Deserialize)]
pub(crate) struct EscalationVerdict {
    escalate: bool,
    #[serde(default)]
    reason: String,
}

/// Builds the condensed trajectory presented to the escalation judge.
pub(crate) struct EscalationInput {
    config: EscalationJudgeConfig,
}

impl ClassifierInput for EscalationInput {
    fn build_messages(&self, _state: &State, request: &Request) -> Vec<Message> {
        let summary = summarize_for_judge(
            &request.llm_request.instructions,
            &request.llm_request.messages,
            conversation_turn(request),
            &self.config,
        );
        vec![Message::text(Role::User, summary)]
    }
}

/// Structured trajectory judge with a typed escalation verdict.
pub(crate) type EscalationJudge = StructuredJudge<EscalationInput, SerdeDecoder<EscalationVerdict>>;

/// Maps the judge's verdict to a classification. A verdict names the tier to serve — capable
/// on escalate, efficient on decline — so the caller reads it straight off the winning score.
/// [`Classification::Ambiguous`] carries the unavailable case, which names no tier: both a
/// decline and an outage stay efficient, but only a decline is evidence, so only a decline
/// clears the streak.
pub(crate) struct EscalationPolicy;

impl JudgePolicy for EscalationPolicy {
    type Verdict = EscalationVerdict;

    fn to_classification(
        &self,
        verdict: Option<&EscalationVerdict>,
        driver: &Driver,
    ) -> Result<Classification> {
        if let Some(verdict) = verdict {
            tracing::debug!(
                escalate = verdict.escalate,
                reason = %verdict.reason,
                "escalation judge verdict"
            );
        }
        match verdict {
            Some(verdict) if verdict.escalate => Ok(Classification::Scores(vec![Score {
                target: driver.first_model_for(&Category::Capable)?.clone(),
                confidence: 1.0,
                category: Some(Category::Capable),
            }])),
            Some(_) => Ok(Classification::Scores(vec![Score {
                target: driver.first_model_for(&Category::Efficient)?.clone(),
                confidence: 1.0,
                category: Some(Category::Efficient),
            }])),
            None => Ok(Classification::Ambiguous(Vec::new())),
        }
    }
}

/// Maps present verdicts to stable `escalate` or `continue` values; absent verdicts add nothing.
fn escalation_evidence(
    _policy: &EscalationPolicy,
    verdict: Option<&EscalationVerdict>,
) -> Option<Value> {
    verdict.map(|verdict| {
        serde_json::json!({
            "source": "escalation",
            "verdict": if verdict.escalate { "escalate" } else { "continue" },
        })
    })
}

/// Builds the trajectory judge, scoring the runtime capable category when it escalates.
///
/// Loads the packaged prompt and schema, so an unusable asset or an unusable `config` value
/// fails here rather than on the first request.
pub(crate) fn build_judge(
    contract_config: &ClassifierContractConfig,
    config: EscalationJudgeConfig,
    max_output_tokens: u64,
) -> Result<JudgeClassifier<EscalationJudge, EscalationPolicy>> {
    config.validate()?;
    let contract =
        ClassifierContract::from_config(contract_config, PROMPT_TEMPLATE, SCHEMA_TEMPLATE)?;
    Ok(JudgeClassifier::new(
        StructuredJudge::new(
            EscalationInput { config },
            contract,
            SerdeDecoder::new(),
            JudgeRuntimeConfig::new(max_output_tokens)?,
        ),
        EscalationPolicy,
    )
    .with_evidence(escalation_evidence))
}

/// The 1-indexed model invocation the transcript ends on: one per assistant reply.
///
/// The judge reads the turn *including* the reply it is judging, so the newest assistant
/// message is this turn — no `+ 1`. Counting the caller's request instead would report the
/// turn after the one under judgement.
///
/// Messages are already normalized by `switchyard-protocol`, so this needs no
/// per-format branching.
pub(crate) fn conversation_turn(request: &Request) -> usize {
    request
        .llm_request
        .messages
        .iter()
        .filter(|message| message.role == Role::Assistant)
        .count()
}

/// Flattens a message to plain text, tool calls and tool results included.
///
/// [`Message::text_content`] is deliberately not used here: it keeps only text and refusal
/// blocks, which would erase exactly the repeated-command signal the judge's loop detection
/// relies on.
fn message_text(message: &Message) -> String {
    let mut parts = Vec::new();
    collect_text(&message.content, &mut parts);
    parts.join(" ")
}

/// Appends the judge-relevant text of each block, descending into tool results.
fn collect_text(content: &[ContentBlock], parts: &mut Vec<String>) {
    for block in content {
        match block {
            ContentBlock::Text { text } | ContentBlock::Refusal { text } => {
                parts.push(text.clone());
            }
            ContentBlock::ToolCall(call) => {
                parts.push(format!("tool_call {}({})", call.name, call.arguments));
            }
            ContentBlock::ToolResult(result) => collect_text(&result.content, parts),
            _ => {}
        }
    }
}

/// Keeps the head and tail of `text` within `limit` characters.
///
/// The head gets two thirds of the surviving budget: for a trajectory judge the command or
/// error signature that opens a message carries more signal than its trailing output.
fn truncate_middle(text: &str, limit: usize) -> String {
    let chars: Vec<char> = text.chars().collect();
    if chars.len() <= limit {
        return text.to_string();
    }
    let keep = limit
        .saturating_sub(TRIM_MARKER.chars().count())
        .max(20)
        .min(chars.len());
    let head = keep * 2 / 3;
    let tail = keep - head;
    let mut out: String = chars[..head].iter().collect();
    out.push_str(TRIM_MARKER);
    out.extend(chars[chars.len() - tail..].iter());
    out
}

/// Renders a compact role-labelled transcript for the judge.
///
/// Task-framing user messages are capped individually. System/developer instructions share
/// the remaining budget after reserving space for task framing and the newest window entry.
/// The trailing window carries recent activity. A coverage header states how much history is
/// not shown, so the judge can reason about pace rather than assuming it sees everything.
///
/// When the assembled text still exceeds `max_request_chars`, the oldest window lines go
/// first: for a trajectory judge the newest evidence is strictly the most valuable.
fn summarize_for_judge(
    instructions: &[InstructionBlock],
    messages: &[Message],
    turn: usize,
    config: &EscalationJudgeConfig,
) -> String {
    let mut instruction_anchors: Vec<String> = Vec::new();
    let mut anchors: Vec<String> = Vec::new();
    let mut window: Vec<String> = Vec::new();
    let mut assistant_seen = false;

    for instruction in instructions {
        let mut parts = Vec::new();
        collect_text(&instruction.content, &mut parts);
        instruction_anchors.push(format!(
            "[{}] {}",
            role_label(instruction.role),
            truncate_middle(&parts.join(" "), SYSTEM_CHARS)
        ));
    }

    for message in messages {
        let text = message_text(message);
        match message.role {
            Role::System | Role::Developer => instruction_anchors.push(format!(
                "[{}] {}",
                role_label(message.role),
                truncate_middle(&text, SYSTEM_CHARS)
            )),
            // Everything the user said before the agent first replied is task framing.
            Role::User if !assistant_seen => {
                anchors.push(format!(
                    "[user (task)] {}",
                    truncate_middle(&text, TASK_CHARS)
                ));
            }
            role => {
                if role == Role::Assistant {
                    assistant_seen = true;
                }
                window.push(format!(
                    "[{}] {}",
                    role_label(role),
                    truncate_middle(&text, config.window_message_chars)
                ));
            }
        }
    }

    if window.len() > config.recent_turn_window {
        window.drain(..window.len() - config.recent_turn_window);
    }

    let assemble = |instructions: Option<&str>, window: &[String]| {
        let header = format!(
            "Conversation turn {turn}; showing the last {} of {} messages after the task framing.",
            window.len(),
            messages.len(),
        );
        std::iter::once(header)
            .chain(instructions.map(str::to_owned))
            .chain(anchors.iter().cloned())
            .chain(window.iter().cloned())
            .collect::<Vec<_>>()
            .join("\n")
    };

    let reserved = assemble(None, &window[window.len().saturating_sub(1)..])
        .chars()
        .count();
    let instruction_budget = MAX_REQUEST_CHARS.saturating_sub(reserved + 1);
    // The remaining budget may be smaller than truncate_middle's minimum retained span.
    let instruction_text = truncate_middle(&instruction_anchors.join("\n"), instruction_budget)
        .chars()
        .take(instruction_budget)
        .collect::<String>();
    let instructions = (!instruction_text.is_empty()).then_some(instruction_text.as_str());
    let mut text = assemble(instructions, &window);
    while text.chars().count() > MAX_REQUEST_CHARS && !window.is_empty() {
        window.remove(0);
        text = assemble(instructions, &window);
    }
    if text.chars().count() > MAX_REQUEST_CHARS {
        let keep = MAX_REQUEST_CHARS.saturating_sub(TRUNCATION_SUFFIX.chars().count() + 1);
        text = text.chars().take(keep).collect::<String>() + TRUNCATION_SUFFIX;
    }
    text
}

/// The transcript label for a role.
fn role_label(role: Role) -> &'static str {
    match role {
        Role::System => "system",
        Role::Developer => "developer",
        Role::User => "user",
        Role::Assistant => "assistant",
        Role::Tool => "tool",
    }
}

/// A request whose conversation sits at `turn`: `turn - 1` prior assistant replies, each
/// answered by a further user message.
///
/// Shared with the assembled router's tests, which drive the same conversation shape.
#[cfg(test)]
pub(crate) fn request_at_turn(session_id: Option<&str>, turn: usize) -> Request {
    use switchyard_protocol::{LlmRequest, Metadata};

    let mut messages = vec![Message::text(Role::User, "What is 2+2?")];
    for attempt in 1..turn {
        messages.push(Message::text(Role::Assistant, format!("attempt {attempt}")));
        messages.push(Message::text(Role::User, format!("still wrong {attempt}")));
    }
    Request {
        llm_request: LlmRequest {
            model: Some("auto".to_string()),
            messages,
            ..LlmRequest::default()
        },
        raw_request: None,
        metadata: session_id.map(|id| Metadata {
            session_id: Some(id.to_string()),
            ..Metadata::default()
        }),
    }
}

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

    use super::*;
    use crate::algorithms::util::llm_judge::Judge;

    fn escalation_judge(max_output_tokens: u64) -> Result<EscalationJudge> {
        Ok(StructuredJudge::new(
            EscalationInput {
                config: EscalationJudgeConfig::default(),
            },
            ClassifierContract::from_config(
                &ClassifierContractConfig::default(),
                PROMPT_TEMPLATE,
                SCHEMA_TEMPLATE,
            )?,
            SerdeDecoder::new(),
            JudgeRuntimeConfig::new(max_output_tokens)?,
        ))
    }

    #[test]
    fn judge_request_is_rubric_plus_summary_under_a_completion_cap() -> Result<()> {
        let judge = escalation_judge(super::super::DEFAULT_JUDGE_MAX_OUTPUT_TOKENS)?;

        // As the classifier calls it: the turn's reply is already on the transcript.
        let mut judged = request_at_turn(None, 4);
        judged.llm_request.instructions = [
            (Role::System, "system constraint"),
            (Role::Developer, "developer constraint"),
        ]
        .into_iter()
        .map(|(role, text)| InstructionBlock {
            role,
            content: Message::text(role, text).content,
        })
        .collect();
        judged
            .llm_request
            .messages
            .push(Message::text(Role::Assistant, "this turn's reply"));
        let built = judge.build_request(&State::default(), &judged);

        // Rubric in instructions, condensed trajectory as the sole user message.
        assert_eq!(built.llm_request.instructions.len(), 1);
        assert_eq!(built.llm_request.instructions[0].role, Role::System);
        assert_eq!(built.llm_request.messages.len(), 1);
        assert_eq!(built.llm_request.messages[0].role, Role::User);
        let summary = built.llm_request.messages[0]
            .text_content("")
            .expect("summary");
        assert!(summary.contains("Conversation turn 4"));
        assert!(summary.contains(
            "[system] system constraint\n[developer] developer constraint\n[user (task)] What is 2+2?"
        ));
        assert!(summary.contains("[assistant] this turn's reply"));
        // Bounded output, so a reasoning judge cannot run away mid-verdict.
        assert_eq!(
            built.llm_request.output.max_output_tokens,
            Some(super::super::DEFAULT_JUDGE_MAX_OUTPUT_TOKENS)
        );
        assert!(built.llm_request.output.response_format.is_some());

        judged.llm_request.instructions.extend(vec![
            InstructionBlock {
                role: Role::Developer,
                content: Message::text(Role::Developer, "x".repeat(SYSTEM_CHARS)).content,
            };
            MAX_REQUEST_CHARS / SYSTEM_CHARS + 1
        ]);
        let built = judge.build_request(&State::default(), &judged);
        let summary = built.llm_request.messages[0]
            .text_content("")
            .expect("summary");
        assert!(summary.chars().count() <= MAX_REQUEST_CHARS);
        assert!(summary.contains(TRIM_MARKER));
        assert!(summary.contains("[system] system constraint"));
        assert!(summary.contains("[developer] developer constraint"));
        assert!(summary.contains("[user (task)] What is 2+2?"));
        assert!(summary.contains("[assistant] this turn's reply"));
        Ok(())
    }

    #[test]
    fn judge_request_uses_the_configured_completion_cap() -> Result<()> {
        let judge = escalation_judge(512)?;

        let built = judge.build_request(&State::default(), &request_at_turn(None, 1));

        assert_eq!(built.llm_request.output.max_output_tokens, Some(512));
        Ok(())
    }

    #[test]
    fn conversation_turn_counts_assistant_replies() {
        // The judge is handed the transcript with this turn's reply already appended, which
        // is the shape asserted here: a request entering turn N plus its reply *is* turn N.
        for turn in [1, 5] {
            let mut judged = request_at_turn(None, turn);
            judged
                .llm_request
                .messages
                .push(Message::text(Role::Assistant, "this turn's reply"));
            assert_eq!(conversation_turn(&judged), turn);
        }
    }

    #[test]
    fn message_text_keeps_tool_calls_and_results() {
        let call = Message {
            role: Role::Assistant,
            content: vec![
                ContentBlock::Text {
                    text: "running it".to_string(),
                },
                ContentBlock::ToolCall(ToolCall {
                    id: "call-1".to_string(),
                    name: "bash".to_string(),
                    arguments: json!({"cmd": "ls"}),
                }),
            ],
        };
        let text = message_text(&call);
        assert!(text.contains("running it"), "{text}");
        assert!(text.contains(r#"tool_call bash({"cmd":"ls"})"#), "{text}");

        let result = Message {
            role: Role::Tool,
            content: vec![ContentBlock::ToolResult(ToolResult {
                tool_call_id: "call-1".to_string(),
                content: vec![ContentBlock::Text {
                    text: "no such file".to_string(),
                }],
                is_error: Some(true),
            })],
        };
        assert_eq!(message_text(&result), "no such file");
    }

    #[test]
    fn truncate_middle_keeps_head_and_tail() {
        let text = "a".repeat(40) + &"z".repeat(40);
        let trimmed = truncate_middle(&text, 50);
        assert!(trimmed.chars().count() <= 50, "{trimmed}");
        assert!(trimmed.starts_with('a'));
        assert!(trimmed.ends_with('z'));
        assert!(trimmed.contains("[trimmed]"));

        // Under the limit the text is returned untouched.
        assert_eq!(truncate_middle("short", 50), "short");
    }

    #[test]
    fn summary_keeps_anchors_and_the_recent_window() {
        let mut messages = vec![
            Message::text(Role::System, "you are a coding agent"),
            Message::text(Role::User, "fix the failing test"),
        ];
        for i in 0..10 {
            messages.push(Message::text(Role::Assistant, format!("step {i}")));
        }
        let config = EscalationJudgeConfig {
            recent_turn_window: 3,
            ..EscalationJudgeConfig::default()
        };

        let summary = summarize_for_judge(&[], &messages, 11, &config);

        assert!(
            summary.contains("[system] you are a coding agent"),
            "{summary}"
        );
        assert!(
            summary.contains("[user (task)] fix the failing test"),
            "{summary}"
        );
        assert!(summary.contains("Conversation turn 11; showing the last 3 of 12 messages"));
        // Only the newest window entries survive.
        assert!(summary.contains("step 9"), "{summary}");
        assert!(summary.contains("step 7"), "{summary}");
        assert!(!summary.contains("step 6"), "{summary}");
    }

    #[test]
    fn summary_anchors_every_user_message_before_the_first_reply() {
        // Codex sends environment boilerplate as the first user message and the task as the
        // second. Both are framing; the task must stay visible after the window has moved on.
        let mut messages = vec![
            Message::text(
                Role::Developer,
                "<skills_instructions>...</skills_instructions>",
            ),
            Message::text(
                Role::User,
                "<environment_context><cwd>/app</cwd></environment_context>",
            ),
            Message::text(Role::User, "Implement RFC 5545 timezone interop in rrule."),
        ];
        for i in 0..40 {
            messages.push(Message::text(Role::Assistant, format!("step {i}")));
            messages.push(Message::text(Role::User, format!("later user note {i}")));
        }
        let config = EscalationJudgeConfig {
            recent_turn_window: 3,
            ..EscalationJudgeConfig::default()
        };

        let summary = summarize_for_judge(&[], &messages, 40, &config);

        assert!(
            summary.contains("[user (task)] <environment_context>"),
            "{summary}"
        );
        assert!(
            summary.contains("[user (task)] Implement RFC 5545 timezone interop in rrule."),
            "{summary}"
        );
        // User messages after the first reply are ordinary window entries, not anchors.
        assert!(
            !summary.contains("[user (task)] later user note"),
            "{summary}"
        );
        assert!(summary.contains("[user] later user note 39"), "{summary}");
        assert!(!summary.contains("later user note 0\n"), "{summary}");
    }

    #[test]
    fn summary_drops_oldest_window_lines_under_the_char_cap() {
        // MAX_REQUEST_CHARS is a backstop, not a dial: at default settings the window caps
        // bind first (28 x 500 plus anchors sits under it), so reaching it takes an unusually
        // wide per-message cap. That is the point — it only fires on pathological input.
        let mut messages = vec![
            Message::text(Role::System, "framing"),
            Message::text(Role::User, "task"),
        ];
        for i in 0..20 {
            messages.push(Message::text(
                Role::Assistant,
                format!("{i} {}", "x".repeat(2_000)),
            ));
        }
        let config = EscalationJudgeConfig {
            window_message_chars: 2_000,
            ..EscalationJudgeConfig::default()
        };

        let summary = summarize_for_judge(&[], &messages, 21, &config);

        assert!(
            summary.chars().count() <= MAX_REQUEST_CHARS,
            "{}",
            summary.chars().count()
        );
        // Anchors are never dropped, and the newest activity outlives the oldest.
        assert!(summary.contains("[system] framing"), "{summary}");
        assert!(summary.contains("[user (task)] task"), "{summary}");
        assert!(summary.contains("19 xxx"), "{summary}");
        assert!(!summary.contains("0 xxx"), "{summary}");
    }
}