Skip to main content

ag_protocol/
envelope.rs

1//! Protocol-owned prompt envelopes for agent-facing instruction text.
2
3use std::path::Path;
4
5use askama::Template;
6
7use super::model::ProtocolRequestProfile;
8use super::schema::protocol_json_schema_json;
9
10const PROTOCOL_INSTRUCTIONS_MARKER: &str = "Structured response protocol:";
11const PROTOCOL_REFRESH_REMINDER_MARKER: &str = "Protocol refresh reminder:";
12const REPAIR_RESPONSE_PREVIEW_MAX_CHARS: usize = 500;
13
14/// Controls whether bootstrap prompt instructions include the full protocol
15/// JSON Schema text.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum ProtocolSchemaInstructionMode {
18    /// Include the full self-descriptive JSON Schema in the prompt because
19    /// the provider does not enforce Agentty's response schema natively.
20    PromptSchema,
21    /// Omit the full schema text because the provider enforces the same
22    /// response schema through its transport-level structured output API.
23    TransportSchema,
24}
25
26impl ProtocolSchemaInstructionMode {
27    /// Returns whether bootstrap instructions should embed the full JSON
28    /// Schema text in the prompt body.
29    fn includes_response_json_schema(self) -> bool {
30        matches!(self, Self::PromptSchema)
31    }
32}
33
34/// Prepends structured response protocol instructions to a prompt.
35///
36/// Tells agents to emit one top-level JSON object that matches Agentty's
37/// structured protocol while selecting the cheapest safe schema guidance for
38/// the current provider. Providers without native structured output receive
39/// the full JSON Schema in the prompt; providers with native enforcement get
40/// policy and field-routing instructions only. `workspace_root` names the
41/// only writable directory for the turn. If the prompt already contains the
42/// protocol marker, this function returns the prompt unchanged to avoid
43/// duplicated guidance.
44#[must_use]
45pub fn prepend_protocol_instructions(
46    prompt: &str,
47    profile: ProtocolRequestProfile,
48    schema_instruction_mode: ProtocolSchemaInstructionMode,
49    workspace_root: &Path,
50) -> String {
51    if prompt.contains(PROTOCOL_INSTRUCTIONS_MARKER) {
52        return prompt.to_string();
53    }
54
55    let protocol_usage_instructions = render_protocol_usage_instructions(profile);
56    let workspace_root = workspace_root.display().to_string();
57    if !schema_instruction_mode.includes_response_json_schema() {
58        let template = ProtocolInstructionPolicyPromptTemplate {
59            prompt,
60            protocol_usage_instructions: &protocol_usage_instructions,
61            workspace_root: &workspace_root,
62        };
63
64        return render_template("protocol_instruction_policy_prompt.md", &template);
65    }
66
67    let response_json_schema = protocol_json_schema_json(profile);
68    let template = ProtocolInstructionPromptTemplate {
69        prompt,
70        protocol_usage_instructions: &protocol_usage_instructions,
71        response_json_schema: &response_json_schema,
72        workspace_root: &workspace_root,
73    };
74
75    render_template("protocol_instruction_prompt.md", &template)
76}
77
78/// Prepends a compact refresh reminder for providers that already received
79/// the full instruction contract in the active context.
80///
81/// The reminder repeats the workspace-isolation boundary for
82/// `workspace_root` so long-lived provider contexts keep the rule even after
83/// provider-side context compaction.
84#[must_use]
85pub fn prepend_protocol_refresh_reminder(
86    prompt: &str,
87    profile: ProtocolRequestProfile,
88    workspace_root: &Path,
89) -> String {
90    if prompt.contains(PROTOCOL_INSTRUCTIONS_MARKER)
91        || prompt.contains(PROTOCOL_REFRESH_REMINDER_MARKER)
92    {
93        return prompt.to_string();
94    }
95
96    let protocol_refresh_instructions = render_protocol_refresh_instructions(profile);
97    let workspace_root = workspace_root.display().to_string();
98    let template = ProtocolRefreshPromptTemplate {
99        prompt,
100        protocol_refresh_instructions: &protocol_refresh_instructions,
101        workspace_root: &workspace_root,
102    };
103
104    render_template("protocol_refresh_prompt.md", &template)
105}
106
107/// Builds the protocol repair prompt text for one failed parse attempt.
108///
109/// The returned prompt is self-contained: it includes the full JSON schema
110/// and the `Structured response protocol:` marker so it can be submitted
111/// through the standard prompt pipeline without being double-wrapped.
112#[must_use]
113pub fn build_protocol_repair_prompt(parse_error: &str, malformed_response: &str) -> String {
114    build_protocol_repair_prompt_for_profile(
115        ProtocolRequestProfile::UtilityPrompt,
116        parse_error,
117        malformed_response,
118    )
119}
120
121/// Builds a repair prompt for the schema selected by `profile`.
122#[must_use]
123pub fn build_protocol_repair_prompt_for_profile(
124    profile: ProtocolRequestProfile,
125    parse_error: &str,
126    malformed_response: &str,
127) -> String {
128    let response_json_schema = protocol_json_schema_json(profile);
129    let response_preview = truncate_preview(malformed_response, REPAIR_RESPONSE_PREVIEW_MAX_CHARS);
130    let template = ProtocolRepairPromptTemplate {
131        parse_error,
132        response_json_schema: &response_json_schema,
133        response_preview: &response_preview,
134    };
135
136    render_template("protocol_repair_prompt.md", &template)
137}
138
139/// Askama view model for protocol instructions when the transport enforces
140/// the response schema.
141#[derive(Template)]
142#[template(path = "protocol_instruction_policy_prompt.md", escape = "none")]
143struct ProtocolInstructionPolicyPromptTemplate<'a> {
144    prompt: &'a str,
145    protocol_usage_instructions: &'a str,
146    workspace_root: &'a str,
147}
148
149/// Askama view model for full protocol instructions with prompt-side schema.
150#[derive(Template)]
151#[template(path = "protocol_instruction_prompt.md", escape = "none")]
152struct ProtocolInstructionPromptTemplate<'a> {
153    prompt: &'a str,
154    protocol_usage_instructions: &'a str,
155    response_json_schema: &'a str,
156    workspace_root: &'a str,
157}
158
159/// Askama view model for compact refresh reminders.
160#[derive(Template)]
161#[template(path = "protocol_refresh_prompt.md", escape = "none")]
162struct ProtocolRefreshPromptTemplate<'a> {
163    prompt: &'a str,
164    protocol_refresh_instructions: &'a str,
165    workspace_root: &'a str,
166}
167
168/// Askama view model for repair prompts after protocol parse failures.
169#[derive(Template)]
170#[template(path = "protocol_repair_prompt.md", escape = "none")]
171struct ProtocolRepairPromptTemplate<'a> {
172    parse_error: &'a str,
173    response_json_schema: &'a str,
174    response_preview: &'a str,
175}
176
177/// Askama view model for session-turn protocol usage instructions.
178#[derive(Template)]
179#[template(path = "protocol_instruction_session_turn_usage.md", escape = "none")]
180struct ProtocolInstructionSessionTurnUsageTemplate;
181
182/// Askama view model for one-shot protocol usage instructions.
183#[derive(Template)]
184#[template(path = "protocol_instruction_utility_prompt_usage.md", escape = "none")]
185struct ProtocolInstructionUtilityPromptUsageTemplate;
186
187/// Askama view model for direct focused-review protocol usage instructions.
188#[derive(Template)]
189#[template(path = "protocol_instruction_focused_review_usage.md", escape = "none")]
190struct ProtocolInstructionFocusedReviewUsageTemplate;
191
192/// Askama view model for session-turn refresh instructions.
193#[derive(Template)]
194#[template(path = "protocol_refresh_session_turn_instruction.md", escape = "none")]
195struct ProtocolRefreshSessionTurnInstructionTemplate;
196
197/// Askama view model for one-shot refresh instructions.
198#[derive(Template)]
199#[template(
200    path = "protocol_refresh_utility_prompt_instruction.md",
201    escape = "none"
202)]
203struct ProtocolRefreshUtilityPromptInstructionTemplate;
204
205/// Renders the protocol usage instructions for one request profile.
206fn render_protocol_usage_instructions(profile: ProtocolRequestProfile) -> String {
207    if matches!(profile, ProtocolRequestProfile::FocusedReview) {
208        return render_template(
209            "protocol_instruction_focused_review_usage.md",
210            &ProtocolInstructionFocusedReviewUsageTemplate,
211        );
212    }
213
214    if matches!(profile, ProtocolRequestProfile::SessionTurn) {
215        return render_template(
216            "protocol_instruction_session_turn_usage.md",
217            &ProtocolInstructionSessionTurnUsageTemplate,
218        );
219    }
220
221    render_template(
222        "protocol_instruction_utility_prompt_usage.md",
223        &ProtocolInstructionUtilityPromptUsageTemplate,
224    )
225}
226
227/// Renders the compact protocol refresh instructions for one request profile.
228fn render_protocol_refresh_instructions(profile: ProtocolRequestProfile) -> String {
229    if matches!(profile, ProtocolRequestProfile::FocusedReview) {
230        return render_template(
231            "protocol_instruction_focused_review_usage.md",
232            &ProtocolInstructionFocusedReviewUsageTemplate,
233        );
234    }
235
236    if matches!(profile, ProtocolRequestProfile::SessionTurn) {
237        return render_template(
238            "protocol_refresh_session_turn_instruction.md",
239            &ProtocolRefreshSessionTurnInstructionTemplate,
240        );
241    }
242
243    render_template(
244        "protocol_refresh_utility_prompt_instruction.md",
245        &ProtocolRefreshUtilityPromptInstructionTemplate,
246    )
247}
248
249/// Renders one Askama template and removes trailing whitespace.
250fn render_template(template_name: &str, template: &impl Template) -> String {
251    let rendered = match template.render() {
252        Ok(rendered) => rendered,
253        Err(error) => format!("Failed to render `{template_name}`: {error}"),
254    };
255
256    rendered.trim_end().to_string()
257}
258
259/// Truncates one malformed response preview to a character-count limit.
260fn truncate_preview(raw: &str, max_chars: usize) -> String {
261    let preview: String = raw.chars().take(max_chars).collect();
262    let total_chars = raw.chars().count();
263
264    if total_chars <= max_chars {
265        return preview;
266    }
267
268    format!("{preview}\n... [{} more chars]", total_chars - max_chars)
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274
275    /// Returns the workspace root used by envelope rendering tests.
276    fn test_workspace_root() -> &'static Path {
277        Path::new("/tmp/agentty-wt/session-1")
278    }
279
280    /// Collapses rendered prompt whitespace for semantic assertions.
281    fn normalize_prompt(prompt: &str) -> String {
282        prompt.split_whitespace().collect::<Vec<_>>().join(" ")
283    }
284
285    #[test]
286    /// Ensures session prompts include the critical protocol contract markers.
287    fn test_prepend_protocol_instructions_adds_session_protocol_instructions() {
288        // Arrange
289        let prompt = "Implement feature";
290
291        // Act
292        let rendered_prompt = prepend_protocol_instructions(
293            prompt,
294            ProtocolRequestProfile::SessionTurn,
295            ProtocolSchemaInstructionMode::PromptSchema,
296            test_workspace_root(),
297        );
298
299        let normalized_prompt = normalize_prompt(&rendered_prompt);
300        let protocol_position = rendered_prompt
301            .find("Structured response protocol:")
302            .expect("protocol marker should be present");
303        let schema_position = rendered_prompt
304            .find("Authoritative JSON Schema:")
305            .expect("schema should be present");
306        let user_prompt_position = rendered_prompt
307            .rfind(prompt)
308            .expect("user prompt should be present");
309
310        // Assert
311        assert!(rendered_prompt.contains("File path output requirements:"));
312        assert!(rendered_prompt.contains("Workspace isolation requirements:"));
313        assert!(protocol_position < schema_position);
314        assert!(schema_position < user_prompt_position);
315        assert!(rendered_prompt.contains("`/tmp/agentty-wt/session-1`"));
316        assert!(normalized_prompt.contains("process working directory"));
317        assert!(normalized_prompt.contains("everything outside it is read-only"));
318        assert!(rendered_prompt.contains("repository-root-relative POSIX paths"));
319        assert!(rendered_prompt.contains("`path:line:column`"));
320        assert!(normalized_prompt.contains("absolute paths, `file://` URIs, or `../` prefixes"));
321        assert!(normalized_prompt.contains("Git commands must be read-only"));
322        assert!(normalized_prompt.contains("Never run mutating commands"));
323        assert!(rendered_prompt.contains("`git worktree remove`"));
324        assert!(rendered_prompt.contains("`cd`, `git -C`"));
325        assert!(rendered_prompt.contains("Quality check requirements:"));
326        assert!(rendered_prompt.contains("repository-defined checks"));
327        assert!(normalized_prompt.contains("affected dependencies and dependents"));
328        assert!(normalized_prompt.contains("full repository test/check suite"));
329        assert!(normalized_prompt.contains("session-created temporary scripts and files"));
330        assert!(rendered_prompt.contains("Structured response protocol:"));
331        assert!(normalized_prompt.contains("exactly one JSON object"));
332        assert!(normalized_prompt.contains("without markdown fences or surrounding prose"));
333        assert!(normalized_prompt.contains("Follow this JSON Schema exactly"));
334        assert!(normalized_prompt.contains("titles and descriptions are authoritative"));
335        assert!(rendered_prompt.contains("Authoritative JSON Schema:"));
336        assert!(
337            rendered_prompt
338                .contains("______________________________________________________________________")
339        );
340        assert!(!rendered_prompt.contains("{# task separator #}"));
341        assert!(rendered_prompt.contains("For this session turn:"));
342        assert!(rendered_prompt.contains("```mermaid"));
343        assert!(normalized_prompt.contains("diagram only in `answer`"));
344        assert!(normalized_prompt.contains("opening fence starts in column 1"));
345        assert!(normalized_prompt.contains("exactly three backticks"));
346        assert!(
347            normalized_prompt.contains("Other fences, indented blocks, and plain-text Mermaid")
348        );
349        assert!(normalized_prompt.contains("`graph`/`flowchart` with `TD`, `TB`, or `LR`"));
350        assert!(normalized_prompt.contains("32 plain-ASCII characters"));
351        assert!(normalized_prompt.contains("at most 16 nodes and 24 edges"));
352        assert!(normalized_prompt.contains("at most 4 sequence participants"));
353        assert!(normalized_prompt.contains("double-width glyphs suppress the preview"));
354        assert!(normalized_prompt.contains("feedback edge as a separate return row"));
355        assert!(normalized_prompt.contains("fall back to plain fenced code"));
356        assert!(normalized_prompt.contains("Do not create commits; do not suggest creating them"));
357        assert!(normalized_prompt.contains("Leave `subtasks` empty unless"));
358        assert!(normalized_prompt.contains("Emit `review_comment_outcomes` only"));
359        assert!(normalized_prompt.contains("otherwise use an empty array"));
360        assert!(rendered_prompt.contains("\"answer\""));
361        assert!(rendered_prompt.contains("\"questions\""));
362        assert!(rendered_prompt.contains("\"title\""));
363        assert!(rendered_prompt.contains("\"description\""));
364        assert!(rendered_prompt.ends_with(prompt));
365    }
366
367    #[test]
368    /// Ensures schema-enforcing transports get protocol policy without the
369    /// large prompt-side JSON Schema body.
370    fn test_prepend_protocol_instructions_omits_schema_for_transport_schema_mode() {
371        // Arrange
372        let prompt = "Implement feature";
373
374        // Act
375        let rendered_prompt = prepend_protocol_instructions(
376            prompt,
377            ProtocolRequestProfile::SessionTurn,
378            ProtocolSchemaInstructionMode::TransportSchema,
379            test_workspace_root(),
380        );
381
382        let normalized_prompt = normalize_prompt(&rendered_prompt);
383
384        // Assert
385        assert!(rendered_prompt.contains("Structured response protocol:"));
386        assert!(rendered_prompt.contains("Workspace isolation requirements:"));
387        assert!(rendered_prompt.contains("`/tmp/agentty-wt/session-1`"));
388        assert!(normalized_prompt.contains("everything outside it is read-only"));
389        assert!(rendered_prompt.contains("provider enforces the response JSON schema"));
390        assert!(normalized_prompt.contains("exactly one JSON object"));
391        assert!(!rendered_prompt.contains("Follow this JSON Schema exactly."));
392        assert!(!rendered_prompt.contains("Authoritative JSON Schema:"));
393        assert!(rendered_prompt.ends_with(prompt));
394    }
395
396    #[test]
397    /// Ensures protocol instructions are not duplicated when already present.
398    fn test_prepend_protocol_instructions_is_idempotent() {
399        // Arrange
400        let prompt = prepend_protocol_instructions(
401            "Implement feature",
402            ProtocolRequestProfile::SessionTurn,
403            ProtocolSchemaInstructionMode::PromptSchema,
404            test_workspace_root(),
405        );
406
407        // Act
408        let rendered_prompt = prepend_protocol_instructions(
409            &prompt,
410            ProtocolRequestProfile::UtilityPrompt,
411            ProtocolSchemaInstructionMode::TransportSchema,
412            test_workspace_root(),
413        );
414
415        // Assert
416        assert_eq!(rendered_prompt, prompt);
417    }
418
419    #[test]
420    /// Ensures one-shot prompts reuse the shared full-schema protocol
421    /// instructions.
422    fn test_prepend_protocol_instructions_reuses_same_contract_for_one_shot() {
423        // Arrange
424        let prompt = "Generate title";
425
426        // Act
427        let rendered_prompt = prepend_protocol_instructions(
428            prompt,
429            ProtocolRequestProfile::UtilityPrompt,
430            ProtocolSchemaInstructionMode::PromptSchema,
431            test_workspace_root(),
432        );
433
434        // Assert
435        assert!(rendered_prompt.contains("Structured response protocol:"));
436        assert!(
437            rendered_prompt
438                .contains("______________________________________________________________________")
439        );
440        assert!(rendered_prompt.contains("For this one-shot utility prompt"));
441        assert!(!rendered_prompt.contains("For this session turn:"));
442        assert!(!rendered_prompt.contains("mermaid"));
443        assert!(
444            rendered_prompt
445                .contains(r#"{"answer":"...","questions":[],"review_comment_outcomes":[]}"#)
446        );
447        assert!(rendered_prompt.contains("\"review_comment_outcomes\""));
448        assert!(!rendered_prompt.contains("\"summary\""));
449        assert!(rendered_prompt.ends_with(prompt));
450    }
451
452    #[test]
453    /// Ensures user prompt text is inserted after generated protocol
454    /// placeholders so prompt content cannot trigger recursive expansion.
455    fn test_prepend_protocol_instructions_preserves_prompt_placeholders() {
456        // Arrange
457        let prompt = "Keep these literal: {{ response_json_schema }} {{ \
458                      protocol_usage_instructions }} {{ workspace_root }}";
459
460        // Act
461        let rendered_prompt = prepend_protocol_instructions(
462            prompt,
463            ProtocolRequestProfile::UtilityPrompt,
464            ProtocolSchemaInstructionMode::PromptSchema,
465            test_workspace_root(),
466        );
467
468        // Assert
469        assert!(rendered_prompt.ends_with(prompt));
470    }
471
472    #[test]
473    /// Ensures compact refresh reminders omit the full schema while keeping
474    /// the contract reminder and task body.
475    fn test_prepend_protocol_refresh_reminder_adds_compact_contract_notice() {
476        // Arrange
477        let prompt = "Continue the implementation";
478
479        // Act
480        let rendered_prompt = prepend_protocol_refresh_reminder(
481            prompt,
482            ProtocolRequestProfile::SessionTurn,
483            test_workspace_root(),
484        );
485        let normalized_prompt = normalize_prompt(&rendered_prompt);
486
487        // Assert
488        assert!(rendered_prompt.contains("Protocol refresh reminder:"));
489        assert!(rendered_prompt.contains("repository-root-relative POSIX"));
490        assert!(normalized_prompt.contains("only read-only git commands; never mutating ones"));
491        assert!(rendered_prompt.contains("inside `/tmp/agentty-wt/session-1`"));
492        assert!(normalized_prompt.contains("everything outside this workspace root is read-only"));
493        assert!(normalized_prompt.contains("Keep Mermaid in `answer`"));
494        assert!(normalized_prompt.contains("fences lacking the `mermaid` info string"));
495        assert!(
496            rendered_prompt
497                .contains("______________________________________________________________________")
498        );
499        assert!(!rendered_prompt.contains("Authoritative JSON Schema:"));
500        assert!(rendered_prompt.ends_with(prompt));
501    }
502
503    #[test]
504    /// Ensures refresh prompt text is inserted after generated reminder
505    /// placeholders so prompt content cannot trigger recursive expansion.
506    fn test_prepend_protocol_refresh_reminder_preserves_prompt_placeholders() {
507        // Arrange
508        let prompt = "Keep this literal: {{ protocol_refresh_instructions }} {{ workspace_root }}";
509
510        // Act
511        let rendered_prompt = prepend_protocol_refresh_reminder(
512            prompt,
513            ProtocolRequestProfile::SessionTurn,
514            test_workspace_root(),
515        );
516
517        // Assert
518        assert!(rendered_prompt.ends_with(prompt));
519    }
520
521    #[test]
522    /// Ensures utility refreshes retain their one-shot profile without
523    /// session-only field or Mermaid guidance.
524    fn test_prepend_protocol_refresh_reminder_uses_utility_profile() {
525        // Arrange
526        let prompt = "Generate another title";
527
528        // Act
529        let rendered_prompt = prepend_protocol_refresh_reminder(
530            prompt,
531            ProtocolRequestProfile::UtilityPrompt,
532            test_workspace_root(),
533        );
534
535        // Assert
536        assert!(rendered_prompt.contains("bootstrapped one-shot JSON object shape"));
537        assert!(!rendered_prompt.contains("`review_comment_outcomes`"));
538        assert!(!rendered_prompt.contains("```mermaid"));
539        assert!(rendered_prompt.ends_with(prompt));
540    }
541
542    #[test]
543    fn test_prepend_protocol_refresh_reminder_uses_focused_review_profile() {
544        // Arrange
545        let prompt = "Repair the focused review";
546
547        // Act
548        let rendered_prompt = prepend_protocol_refresh_reminder(
549            prompt,
550            ProtocolRequestProfile::FocusedReview,
551            test_workspace_root(),
552        );
553        let normalized_prompt = normalize_prompt(&rendered_prompt);
554
555        // Assert
556        assert!(rendered_prompt.contains("return the review object directly"));
557        assert!(normalized_prompt.contains("do not wrap the object in `answer`"));
558        assert!(rendered_prompt.ends_with(prompt));
559    }
560
561    #[test]
562    /// Repair prompt renders with the parse error and a response preview.
563    fn test_build_protocol_repair_prompt_includes_error_and_preview() {
564        // Arrange
565        let parse_error = "response is not valid protocol JSON: invalid JSON";
566        let malformed_response = "plain text response";
567
568        // Act
569        let repair_prompt = build_protocol_repair_prompt(parse_error, malformed_response);
570
571        // Assert
572        assert!(repair_prompt.contains(parse_error));
573        assert!(repair_prompt.contains("plain text response"));
574        assert!(repair_prompt.contains("Structured response protocol:"));
575        assert!(repair_prompt.contains("Authoritative JSON Schema:"));
576        assert!(repair_prompt.contains("\"answer\""));
577    }
578
579    #[test]
580    fn focused_review_repair_prompt_uses_direct_review_schema() {
581        // Arrange
582        let malformed_response = r#"{"project_impact":[],"suggestions":[]} trailing"#;
583
584        // Act
585        let repair_prompt = build_protocol_repair_prompt_for_profile(
586            ProtocolRequestProfile::FocusedReview,
587            "trailing characters",
588            malformed_response,
589        );
590
591        // Assert
592        assert!(repair_prompt.contains("\"title\": \"FocusedReview\""));
593        assert!(repair_prompt.contains("\"project_impact\""));
594        assert!(!repair_prompt.contains("\"answer\""));
595    }
596
597    #[test]
598    /// Ensures malformed response previews are inserted after generated
599    /// schema placeholders so agent output cannot trigger recursive expansion.
600    fn test_build_protocol_repair_prompt_preserves_response_preview_placeholders() {
601        // Arrange
602        let malformed_response = "Keep this literal: {{ response_json_schema }}";
603
604        // Act
605        let repair_prompt =
606            build_protocol_repair_prompt("schema validation failed", malformed_response);
607
608        // Assert
609        assert!(repair_prompt.contains(malformed_response));
610    }
611
612    #[test]
613    /// Repair prompt truncates long malformed responses to the preview limit.
614    fn test_build_protocol_repair_prompt_truncates_long_response() {
615        // Arrange
616        let parse_error = "schema validation failed";
617        let malformed_response = "x".repeat(1000);
618
619        // Act
620        let repair_prompt = build_protocol_repair_prompt(parse_error, &malformed_response);
621
622        // Assert
623        assert!(repair_prompt.contains("500 more chars"));
624        assert!(!repair_prompt.contains(&malformed_response));
625    }
626
627    #[test]
628    /// Repair prompt includes the protocol marker to prevent double-wrapping.
629    fn test_build_protocol_repair_prompt_contains_protocol_marker() {
630        // Arrange / Act
631        let repair_prompt = build_protocol_repair_prompt("error", "response");
632
633        // Assert
634        assert!(repair_prompt.contains("Structured response protocol:"));
635    }
636
637    #[test]
638    /// Short responses are not truncated.
639    fn test_truncate_preview_keeps_short_responses_intact() {
640        // Arrange / Act
641        let preview = truncate_preview("short", 500);
642
643        // Assert
644        assert_eq!(preview, "short");
645    }
646
647    #[test]
648    /// Long responses are truncated with a character count suffix.
649    fn test_truncate_preview_truncates_long_responses() {
650        // Arrange
651        let long_response = "a".repeat(600);
652
653        // Act
654        let preview = truncate_preview(&long_response, 500);
655
656        // Assert
657        assert!(preview.starts_with(&"a".repeat(500)));
658        assert!(preview.contains("100 more chars"));
659    }
660}