Skip to main content

ag_agent/agent/
prompt.rs

1//! Shared prompt-shaping helpers for agent-facing markdown prompts.
2
3use std::path::{Path, PathBuf};
4use std::process::Command;
5
6use ag_protocol::{
7    ProtocolRequestProfile, ProtocolSchemaInstructionMode, TurnPrompt, TurnPromptAttachment,
8    TurnPromptContentPart, prepend_protocol_instructions as protocol_prepend_instructions,
9    prepend_protocol_refresh_reminder as protocol_prepend_refresh_reminder,
10    split_turn_prompt_content,
11};
12use askama::Template;
13
14use super::backend::{AgentBackendError, BuildCommandRequest};
15use super::instruction::InstructionDeliveryMode;
16use crate::channel::PersonalityPromptUpdate;
17use crate::model::session::ResponseStyle;
18
19/// Askama view model for rendering resume prompts with prior transcript text.
20#[derive(Template)]
21#[template(path = "resume_with_transcript_prompt.md", escape = "none")]
22struct ResumeWithTranscriptPromptTemplate<'a> {
23    /// New prompt content appended after the replayed transcript.
24    prompt: &'a str,
25    /// Prior transcript text replayed into the follow-up prompt.
26    transcript: &'a str,
27}
28
29/// Askama view model for placing personality instructions before a turn.
30#[derive(Template)]
31#[template(path = "personality_prompt.md", escape = "none")]
32struct PersonalityPromptTemplate<'a> {
33    /// Markdown heading describing a bootstrap or delta update.
34    heading: &'a str,
35    /// Personality instructions or clearing guidance.
36    personality: &'a str,
37    /// Remaining turn prompt content.
38    prompt: &'a str,
39}
40
41/// Askama view model for placing response-style guidance before a turn.
42#[derive(Template)]
43#[template(path = "response_style_prompt.md", escape = "none")]
44struct ResponseStylePromptTemplate<'a> {
45    /// Guidance corresponding to the selected response style.
46    instruction: &'a str,
47    /// Remaining turn prompt content.
48    prompt: &'a str,
49}
50
51/// Shared prompt preparation input for one transport turn.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub(crate) struct PromptPreparationRequest<'a> {
54    /// Delivery mode selected for the current provider attempt.
55    pub instruction_delivery_mode: InstructionDeliveryMode,
56    /// Current personality body used for full instruction bootstraps.
57    pub personality_prompt: Option<&'a str>,
58    /// Personality change used only for delta delivery.
59    pub personality_update: &'a PersonalityPromptUpdate,
60    /// Base user prompt before replay wrapping and protocol instructions.
61    pub prompt: &'a str,
62    /// Protocol family that determines the rendered instruction envelope.
63    pub protocol_profile: ProtocolRequestProfile,
64    /// Prior transcript text available for replay.
65    pub replay_transcript: Option<&'a str>,
66    /// Schema guidance mode selected from the provider's structured-output
67    /// capability.
68    pub schema_instruction_mode: ProtocolSchemaInstructionMode,
69    /// Workspace folder rendered into the isolation contract as the only
70    /// writable root for the turn.
71    pub workspace_root: &'a Path,
72}
73
74/// Controls which directories CLI prompt transports expose as filesystem access
75/// roots.
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub(crate) enum CliPromptAccessRootMode {
78    /// Expose only attachment parent directories.
79    AttachmentsOnly,
80    /// Expose the workspace folder first, then attachment parent directories.
81    WorkspaceThenAttachments,
82}
83
84/// Applies transcript replay and protocol instructions to one prompt.
85///
86/// # Errors
87/// Returns an error when replay or instruction templates fail to render.
88pub(crate) fn prepare_prompt_text(
89    request: PromptPreparationRequest<'_>,
90) -> Result<String, AgentBackendError> {
91    match request.instruction_delivery_mode {
92        InstructionDeliveryMode::BootstrapFull => {
93            let prompt = prepend_personality_prompt(request.prompt, request.personality_prompt)?;
94
95            Ok(protocol_prepend_instructions(
96                &prompt,
97                request.protocol_profile,
98                request.schema_instruction_mode,
99                request.workspace_root,
100            ))
101        }
102        InstructionDeliveryMode::DeltaOnly => {
103            let prompt = prepend_personality_update(request.prompt, request.personality_update)?;
104
105            Ok(protocol_prepend_refresh_reminder(
106                &prompt,
107                request.protocol_profile,
108                request.workspace_root,
109            ))
110        }
111        InstructionDeliveryMode::BootstrapWithReplay => {
112            let prompt = build_resume_prompt(request.prompt, request.replay_transcript)?;
113            let prompt = prepend_personality_prompt(&prompt, request.personality_prompt)?;
114
115            Ok(protocol_prepend_instructions(
116                &prompt,
117                request.protocol_profile,
118                request.schema_instruction_mode,
119                request.workspace_root,
120            ))
121        }
122    }
123}
124
125/// Builds a resume prompt that optionally prepends previous transcript text.
126///
127/// # Errors
128/// Returns an error if Askama template rendering fails.
129pub(crate) fn build_resume_prompt(
130    prompt: &str,
131    replay_transcript: Option<&str>,
132) -> Result<String, AgentBackendError> {
133    let Some(transcript) = replay_transcript
134        .map(str::trim)
135        .filter(|value| !value.is_empty())
136    else {
137        return Ok(prompt.to_string());
138    };
139
140    let template = ResumeWithTranscriptPromptTemplate { prompt, transcript };
141
142    render_template("resume_with_transcript_prompt.md", &template)
143}
144
145/// Builds the full prompt text for a CLI provider.
146///
147/// This shared helper keeps attachment placeholder rendering and provider
148/// protocol preparation in one place for both argv and stdin transports while
149/// preserving backend-specific error labels.
150///
151/// # Errors
152/// Returns an error when attachment path rendering, resume wrapping, or
153/// protocol prompt rendering fails.
154pub(crate) fn build_cli_prompt_text(
155    request: BuildCommandRequest<'_>,
156    schema_instruction_mode: ProtocolSchemaInstructionMode,
157    backend_display_name: &str,
158) -> Result<String, AgentBackendError> {
159    let prompt =
160        render_prompt_with_local_images(request.prompt, request.attachments, backend_display_name)?;
161
162    prepare_prompt_text(PromptPreparationRequest {
163        instruction_delivery_mode: if request.request_kind.is_resume() {
164            InstructionDeliveryMode::BootstrapWithReplay
165        } else {
166            InstructionDeliveryMode::BootstrapFull
167        },
168        personality_prompt: request.personality_prompt,
169        personality_update: &PersonalityPromptUpdate::Unchanged,
170        prompt: &prompt,
171        protocol_profile: request.request_kind.protocol_profile(),
172        replay_transcript: request.replay_transcript,
173        schema_instruction_mode,
174        workspace_root: request.folder,
175    })
176}
177
178/// Prepends response-style guidance to interactive session turns.
179pub(crate) fn apply_response_style_prompt(
180    mut prompt: TurnPrompt,
181    protocol_profile: ProtocolRequestProfile,
182    response_style: ResponseStyle,
183) -> Result<TurnPrompt, AgentBackendError> {
184    if protocol_profile == ProtocolRequestProfile::SessionTurn {
185        let prompt_text = prompt.agent_text();
186        let template = ResponseStylePromptTemplate {
187            instruction: response_style.prompt_instruction(),
188            prompt: &prompt_text,
189        };
190        prompt.text = render_template("response_style_prompt.md", &template)?;
191    }
192
193    Ok(prompt)
194}
195
196/// Builds a full prompt payload to stream over stdin for CLI providers.
197///
198/// # Errors
199/// Returns an error when the shared CLI prompt text cannot be rendered.
200pub(crate) fn build_prompt_stdin_payload(
201    request: BuildCommandRequest<'_>,
202    schema_instruction_mode: ProtocolSchemaInstructionMode,
203    backend_display_name: &str,
204) -> Result<Vec<u8>, AgentBackendError> {
205    build_cli_prompt_text(request, schema_instruction_mode, backend_display_name)
206        .map(String::into_bytes)
207}
208
209/// Prepends current personality instructions to one full bootstrap prompt.
210fn prepend_personality_prompt(
211    prompt: &str,
212    personality_prompt: Option<&str>,
213) -> Result<String, AgentBackendError> {
214    let Some(personality) = personality_prompt
215        .map(str::trim)
216        .filter(|personality| !personality.is_empty())
217    else {
218        return Ok(prompt.to_string());
219    };
220    let template = PersonalityPromptTemplate {
221        heading: "# Personality",
222        personality,
223        prompt,
224    };
225
226    render_template("personality_prompt.md", &template)
227}
228
229/// Prepends one changed or cleared personality instruction for delta mode.
230fn prepend_personality_update(
231    prompt: &str,
232    personality_update: &PersonalityPromptUpdate,
233) -> Result<String, AgentBackendError> {
234    let personality = match personality_update {
235        PersonalityPromptUpdate::Clear => {
236            "The session personality has been cleared. Continue without the previous personality \
237             instructions."
238        }
239        PersonalityPromptUpdate::Set(personality) => personality.trim(),
240        PersonalityPromptUpdate::Unchanged => return Ok(prompt.to_string()),
241    };
242    let template = PersonalityPromptTemplate {
243        heading: "# Personality Update",
244        personality,
245        prompt,
246    };
247
248    render_template("personality_prompt.md", &template)
249}
250
251/// Appends CLI prompt filesystem access roots as `--add-dir` arguments.
252///
253/// Claude only needs pasted-image parent directories because its process
254/// working directory is already the session workspace. Antigravity derives its
255/// editable workspace from ordered `--add-dir` roots, so it uses
256/// [`CliPromptAccessRootMode::WorkspaceThenAttachments`] to keep the workspace
257/// root first.
258pub(crate) fn append_cli_prompt_access_directories(
259    command: &mut Command,
260    workspace_folder: &Path,
261    attachments: &[TurnPromptAttachment],
262    root_mode: CliPromptAccessRootMode,
263) {
264    for directory in cli_prompt_access_directories(workspace_folder, attachments, root_mode) {
265        command.arg("--add-dir").arg(directory);
266    }
267}
268
269/// Replaces inline image placeholders with provider-usable local image paths.
270///
271/// The function preserves attachment ordering through prompt content parsing
272/// and appends any orphaned attachments that no longer have a placeholder in
273/// the prompt text.
274///
275/// # Errors
276/// Returns an error when any local image path is not valid UTF-8.
277pub(crate) fn render_prompt_with_local_images(
278    prompt: &str,
279    attachments: &[TurnPromptAttachment],
280    backend_display_name: &str,
281) -> Result<String, AgentBackendError> {
282    if attachments.is_empty() {
283        return Ok(prompt.to_string());
284    }
285
286    let mut rendered_prompt = String::new();
287
288    for content_part in split_turn_prompt_content(prompt, attachments) {
289        match content_part {
290            TurnPromptContentPart::Text(text) => rendered_prompt.push_str(text),
291            TurnPromptContentPart::Attachment(attachment) => {
292                let attachment_path = attachment_path_for_prompt(backend_display_name, attachment)?;
293                rendered_prompt.push_str(&attachment_path);
294            }
295            TurnPromptContentPart::OrphanAttachment(attachment) => {
296                if !rendered_prompt.is_empty()
297                    && rendered_prompt
298                        .chars()
299                        .last()
300                        .is_some_and(|character| !character.is_whitespace())
301                {
302                    rendered_prompt.push('\n');
303                }
304
305                rendered_prompt.push_str(&attachment_path_for_prompt(
306                    backend_display_name,
307                    attachment,
308                )?);
309                rendered_prompt.push('\n');
310            }
311        }
312    }
313
314    Ok(rendered_prompt)
315}
316
317/// Returns ordered filesystem access roots for CLI prompt image access.
318///
319/// Directory paths are deduplicated and sorted for deterministic subprocess
320/// argument ordering. When `root_mode` requests the workspace, the session
321/// folder appears before attachment directories and is never duplicated.
322pub(crate) fn cli_prompt_access_directories(
323    workspace_folder: &Path,
324    attachments: &[TurnPromptAttachment],
325    root_mode: CliPromptAccessRootMode,
326) -> Vec<PathBuf> {
327    let mut attachment_directories = attachments
328        .iter()
329        .filter_map(|attachment| attachment.local_image_path.parent())
330        .map(ToOwned::to_owned)
331        .collect::<Vec<_>>();
332    attachment_directories.sort();
333    attachment_directories.dedup();
334
335    if matches!(root_mode, CliPromptAccessRootMode::AttachmentsOnly) {
336        return attachment_directories;
337    }
338
339    attachment_directories
340        .retain(|attachment_directory| attachment_directory.as_path() != workspace_folder);
341
342    let mut workspace_directories = Vec::with_capacity(attachment_directories.len() + 1);
343    workspace_directories.push(workspace_folder.to_path_buf());
344    workspace_directories.extend(attachment_directories);
345
346    workspace_directories
347}
348
349/// Returns one attachment path for prompt injection as strict UTF-8 text.
350///
351/// # Errors
352/// Returns an error when the attachment path cannot be represented as UTF-8.
353fn attachment_path_for_prompt(
354    backend_display_name: &str,
355    attachment: &TurnPromptAttachment,
356) -> Result<String, AgentBackendError> {
357    attachment
358        .local_image_path
359        .to_str()
360        .map(ToOwned::to_owned)
361        .ok_or_else(|| {
362            AgentBackendError::CommandBuild(format!(
363                "{backend_display_name} prompt image path is not valid UTF-8"
364            ))
365        })
366}
367
368/// Builds a Markdown code-fence delimiter long enough to safely wrap an
369/// arbitrary prompt payload.
370///
371/// Returns a string of backticks whose length exceeds the longest run of
372/// consecutive backticks found anywhere in `content`, with a minimum length
373/// of three. This prevents a triple-backtick fence from being terminated
374/// prematurely when the payload itself contains Markdown fences (for example,
375/// when reviewing changes to Markdown or prompt-template files).
376pub fn diff_fence(content: &str) -> String {
377    let mut max_run = 0usize;
378    let mut current_run = 0usize;
379    for character in content.chars() {
380        if character == '`' {
381            current_run += 1;
382            if current_run > max_run {
383                max_run = current_run;
384            }
385        } else {
386            current_run = 0;
387        }
388    }
389
390    let fence_length = std::cmp::max(3, max_run + 1);
391
392    "`".repeat(fence_length)
393}
394
395/// Renders one Askama markdown template and trims the trailing newline added
396/// by file-based templates.
397fn render_template(
398    template_name: &str,
399    template: &impl Template,
400) -> Result<String, AgentBackendError> {
401    let rendered = template.render().map_err(|error| {
402        AgentBackendError::CommandBuild(format!("Failed to render `{template_name}`: {error}"))
403    })?;
404
405    Ok(rendered.trim_end().to_string())
406}
407
408#[cfg(test)]
409mod tests {
410    #[cfg(unix)]
411    use std::ffi::OsString;
412    #[cfg(unix)]
413    use std::os::unix::ffi::OsStringExt;
414    use std::path::PathBuf;
415
416    use super::*;
417
418    #[test]
419    fn repair_bootstrap_applies_schema_once_for_each_provider_and_profile() {
420        // Arrange
421        let repair = ag_protocol::build_protocol_repair_prompt("bad JSON", "original response")
422            .expect("repair body");
423        for kind in [
424            crate::model::agent::AgentKind::Gemini,
425            crate::model::agent::AgentKind::Codex,
426            crate::model::agent::AgentKind::Claude,
427            crate::model::agent::AgentKind::Antigravity,
428        ] {
429            for profile in [
430                ProtocolRequestProfile::SessionTurn,
431                ProtocolRequestProfile::UtilityPrompt,
432                ProtocolRequestProfile::FocusedReview,
433            ] {
434                let schema_mode = super::super::protocol_schema_instruction_mode(kind);
435
436                // Act
437                let prompt = prepare_prompt_text(PromptPreparationRequest {
438                    instruction_delivery_mode: InstructionDeliveryMode::BootstrapFull,
439                    personality_prompt: None,
440                    personality_update: &PersonalityPromptUpdate::Unchanged,
441                    prompt: &repair,
442                    protocol_profile: profile,
443                    replay_transcript: None,
444                    schema_instruction_mode: schema_mode,
445                    workspace_root: test_workspace_root(),
446                })
447                .expect("prepared repair");
448
449                // Assert
450                assert_eq!(
451                    prompt.matches("Authoritative JSON Schema:").count(),
452                    usize::from(schema_mode == ProtocolSchemaInstructionMode::PromptSchema)
453                );
454                assert!(prompt.starts_with("File path output requirements:"));
455                assert!(prompt.ends_with(&repair));
456            }
457        }
458    }
459
460    /// Returns the workspace root used by prompt preparation tests.
461    fn test_workspace_root() -> &'static Path {
462        Path::new("/tmp/agentty-wt/session-1")
463    }
464
465    /// Collapses rendered prompt whitespace for semantic assertions.
466    fn normalize_prompt(prompt: &str) -> String {
467        prompt.split_whitespace().collect::<Vec<_>>().join(" ")
468    }
469
470    #[test]
471    fn response_style_prompt_wraps_session_turns_and_preserves_attachments() {
472        // Arrange
473        let attachment = TurnPromptAttachment {
474            local_image_path: PathBuf::from("/tmp/example.png"),
475            placeholder: "[Image #1]".to_string(),
476        };
477
478        // Act
479        let prompts = ResponseStyle::ALL.map(|response_style| {
480            apply_response_style_prompt(
481                TurnPrompt {
482                    attachments: vec![attachment.clone()],
483                    text: "Explain [Image #1]".to_string(),
484                    text_source: ag_protocol::TurnPromptTextSource::UserPrompt,
485                },
486                ProtocolRequestProfile::SessionTurn,
487                response_style,
488            )
489            .expect("response style prompt should render")
490        });
491
492        // Assert
493        for (prompt, response_style) in prompts.iter().zip(ResponseStyle::ALL) {
494            assert!(prompt.text.starts_with("# Response Style\n\n"));
495            assert!(prompt.text.contains(response_style.prompt_instruction()));
496            assert!(prompt.text.ends_with("Explain [Image #1]"));
497            assert_eq!(prompt.attachments, vec![attachment.clone()]);
498            assert_eq!(
499                prompt.text_source,
500                ag_protocol::TurnPromptTextSource::UserPrompt
501            );
502        }
503    }
504
505    #[test]
506    fn response_style_prompt_leaves_utility_prompts_unchanged() {
507        // Arrange
508        let prompt = TurnPrompt::from_agent_data("Generate a title".to_string());
509
510        // Act
511        let styled_prompt = apply_response_style_prompt(
512            prompt.clone(),
513            ProtocolRequestProfile::UtilityPrompt,
514            ResponseStyle::Detailed,
515        )
516        .expect("utility prompt should remain valid");
517
518        // Assert
519        assert_eq!(styled_prompt, prompt);
520    }
521
522    #[test]
523    /// Ensures the diff fence falls back to three backticks when the content
524    /// contains no backtick runs.
525    fn test_diff_fence_returns_minimum_three_backticks_for_plain_diff() {
526        // Arrange
527        let diff = "diff --git a/a.rs b/a.rs\n+fn main() {}\n";
528
529        // Act
530        let fence = diff_fence(diff);
531
532        // Assert
533        assert_eq!(fence, "```");
534    }
535
536    #[test]
537    /// Ensures the diff fence grows to exceed the longest backtick run in the
538    /// diff so a Markdown triple-backtick fence inside the diff cannot
539    /// terminate the outer wrapper fence.
540    fn test_diff_fence_exceeds_longest_backtick_run_in_diff() {
541        // Arrange
542        let diff = "+```\nsample\n+```\n";
543
544        // Act
545        let fence = diff_fence(diff);
546
547        // Assert
548        assert_eq!(fence, "````");
549    }
550
551    #[test]
552    /// Ensures longer backtick runs keep producing a strictly longer fence so
553    /// nested or unusually long code fences in the diff stay contained.
554    fn test_diff_fence_handles_long_backtick_runs() {
555        // Arrange
556        let diff = "prefix `````diff\ncontent\n`````\n";
557
558        // Act
559        let fence = diff_fence(diff);
560
561        // Assert
562        assert_eq!(fence, "``````");
563    }
564
565    #[test]
566    /// Ensures resume prompt rendering includes trimmed transcript text and
567    /// the new user prompt.
568    fn test_build_resume_prompt_includes_replay_transcript_and_prompt() {
569        // Arrange
570        let prompt = "Continue tests; keep {{ transcript }} literal";
571        let replay_transcript = Some("  previous {{ prompt }} line  \n");
572
573        // Act
574        let resume_prompt =
575            build_resume_prompt(prompt, replay_transcript).expect("resume prompt should render");
576
577        let normalized_resume_prompt = normalize_prompt(&resume_prompt);
578        let transcript_position = resume_prompt
579            .find(r"\<session_transcript> previous {{ prompt }} line")
580            .expect("transcript boundary should be present");
581        let prompt_position = resume_prompt
582            .find(r"\<user_prompt> Continue tests; keep {{ transcript }} literal")
583            .expect("user prompt boundary should be present");
584
585        // Assert
586        assert!(transcript_position < prompt_position);
587        assert!(normalized_resume_prompt.contains("new user prompt as a follow-up"));
588        assert!(normalized_resume_prompt.contains("changes made during this session"));
589        assert!(normalized_resume_prompt.contains("preserve unrelated pre-existing work"));
590        assert!(normalized_resume_prompt.contains("resume unfinished work"));
591        assert!(resume_prompt.ends_with(r"\</user_prompt>"));
592    }
593
594    #[test]
595    /// Ensures whitespace-only transcript text does not trigger transcript
596    /// wrapping and returns the original prompt.
597    fn test_build_resume_prompt_returns_original_prompt_when_output_is_blank() {
598        // Arrange
599        let prompt = "Follow-up request";
600        let replay_transcript = Some("   ");
601
602        // Act
603        let resume_prompt =
604            build_resume_prompt(prompt, replay_transcript).expect("resume prompt should render");
605
606        // Assert
607        assert_eq!(resume_prompt, prompt);
608    }
609
610    #[test]
611    /// Ensures absent transcript text keeps resume prompt formatting unchanged.
612    fn test_build_resume_prompt_returns_original_prompt_without_output() {
613        // Arrange
614        let prompt = "Retry merge";
615
616        // Act
617        let resume_prompt = build_resume_prompt(prompt, None).expect("resume prompt should render");
618
619        // Assert
620        assert_eq!(resume_prompt, prompt);
621    }
622
623    #[test]
624    /// Ensures session prompts include the critical protocol contract markers.
625    fn test_prepend_protocol_instructions_adds_session_protocol_instructions() {
626        // Arrange
627        let prompt = "Implement feature";
628
629        // Act
630        let rendered_prompt = protocol_prepend_instructions(
631            prompt,
632            ProtocolRequestProfile::SessionTurn,
633            ProtocolSchemaInstructionMode::PromptSchema,
634            test_workspace_root(),
635        );
636
637        let normalized_prompt = normalize_prompt(&rendered_prompt);
638        let protocol_position = rendered_prompt
639            .find("Structured response protocol:")
640            .expect("protocol marker should be present");
641        let schema_position = rendered_prompt
642            .find("Authoritative JSON Schema:")
643            .expect("schema should be present");
644        let user_prompt_position = rendered_prompt
645            .rfind(prompt)
646            .expect("user prompt should be present");
647
648        // Assert
649        assert!(rendered_prompt.contains("File path output requirements:"));
650        assert!(rendered_prompt.contains("Workspace isolation requirements:"));
651        assert!(protocol_position < schema_position);
652        assert!(schema_position < user_prompt_position);
653        assert!(rendered_prompt.contains("`/tmp/agentty-wt/session-1`"));
654        assert!(normalized_prompt.contains("everything outside it is read-only"));
655        assert!(rendered_prompt.contains("repository-root-relative POSIX paths"));
656        assert!(normalized_prompt.contains("Git commands must be read-only"));
657        assert!(normalized_prompt.contains("Never run mutating commands"));
658        assert!(rendered_prompt.contains("Quality check requirements:"));
659        assert!(rendered_prompt.contains("repository-defined checks"));
660        assert!(normalized_prompt.contains("affected dependencies and dependents"));
661        assert!(normalized_prompt.contains("full repository test/check suite"));
662        assert!(rendered_prompt.contains("Structured response protocol:"));
663        assert!(normalized_prompt.contains("exactly one JSON object"));
664        assert!(normalized_prompt.contains("Follow this JSON Schema exactly"));
665        assert!(rendered_prompt.contains("Authoritative JSON Schema:"));
666        assert!(
667            rendered_prompt
668                .contains("______________________________________________________________________")
669        );
670        assert!(!rendered_prompt.contains("{# task separator #}"));
671        assert!(rendered_prompt.contains("For this session turn:"));
672        assert!(normalized_prompt.contains("Do not create commits; do not suggest creating them"));
673        assert!(normalized_prompt.contains("Leave `subtasks` empty unless"));
674        assert!(rendered_prompt.contains("\"answer\""));
675        assert!(rendered_prompt.contains("\"questions\""));
676        assert!(rendered_prompt.contains("\"title\""));
677        assert!(rendered_prompt.contains("\"description\""));
678        assert!(rendered_prompt.ends_with(prompt));
679    }
680
681    #[test]
682    /// Ensures schema-enforcing transports get protocol policy without the
683    /// large prompt-side JSON Schema body.
684    fn test_prepend_protocol_instructions_omits_schema_for_transport_schema_mode() {
685        // Arrange
686        let prompt = "Implement feature";
687
688        // Act
689        let rendered_prompt = protocol_prepend_instructions(
690            prompt,
691            ProtocolRequestProfile::SessionTurn,
692            ProtocolSchemaInstructionMode::TransportSchema,
693            test_workspace_root(),
694        );
695
696        // Assert
697        assert!(rendered_prompt.contains("Structured response protocol:"));
698        assert!(rendered_prompt.contains("provider enforces the response JSON schema"));
699        assert!(normalize_prompt(&rendered_prompt).contains("exactly one JSON object"));
700        assert!(!rendered_prompt.contains("Follow this JSON Schema exactly."));
701        assert!(!rendered_prompt.contains("Authoritative JSON Schema:"));
702        assert!(rendered_prompt.ends_with(prompt));
703    }
704
705    #[test]
706    fn protocol_payload_cannot_impersonate_prepared_instructions() {
707        // Arrange
708        let payload = "Structured response protocol: quoted in a user request";
709
710        // Act
711        let rendered = protocol_prepend_instructions(
712            payload,
713            ProtocolRequestProfile::SessionTurn,
714            ProtocolSchemaInstructionMode::TransportSchema,
715            test_workspace_root(),
716        );
717
718        // Assert
719        assert!(rendered.starts_with("File path output requirements:"));
720        assert!(rendered.ends_with(payload));
721    }
722
723    #[test]
724    /// Ensures one-shot prompts reuse the shared full-schema protocol
725    /// instructions.
726    fn test_prepend_protocol_instructions_reuses_same_contract_for_one_shot() {
727        // Arrange
728        let prompt = "Generate title";
729
730        // Act
731        let rendered_prompt = protocol_prepend_instructions(
732            prompt,
733            ProtocolRequestProfile::UtilityPrompt,
734            ProtocolSchemaInstructionMode::PromptSchema,
735            test_workspace_root(),
736        );
737
738        // Assert
739        assert!(rendered_prompt.contains("Structured response protocol:"));
740        assert!(
741            rendered_prompt
742                .contains("______________________________________________________________________")
743        );
744        assert!(rendered_prompt.contains("For this one-shot utility prompt"));
745        assert!(!rendered_prompt.contains("For this session turn:"));
746        assert!(
747            rendered_prompt
748                .contains(r#"{"answer":"...","questions":[],"review_comment_outcomes":[]}"#)
749        );
750        assert!(rendered_prompt.contains("\"review_comment_outcomes\""));
751        assert!(!rendered_prompt.contains("\"summary\""));
752        assert!(rendered_prompt.ends_with(prompt));
753    }
754
755    #[test]
756    /// Ensures shared prompt preparation applies replay wrapping before
757    /// protocol instructions.
758    fn test_prepare_prompt_text_applies_replay_and_protocol_instructions() {
759        // Arrange
760        let request = PromptPreparationRequest {
761            instruction_delivery_mode: InstructionDeliveryMode::BootstrapWithReplay,
762            personality_prompt: None,
763            personality_update: &PersonalityPromptUpdate::Unchanged,
764            prompt: "Continue edits",
765            protocol_profile: ProtocolRequestProfile::SessionTurn,
766            replay_transcript: Some("previous transcript"),
767            schema_instruction_mode: ProtocolSchemaInstructionMode::PromptSchema,
768            workspace_root: test_workspace_root(),
769        };
770
771        // Act
772        let prepared_prompt = prepare_prompt_text(request).expect("prompt should render");
773
774        // Assert
775        assert!(prepared_prompt.contains("Structured response protocol:"));
776        assert!(prepared_prompt.contains("Workspace isolation requirements:"));
777        assert!(prepared_prompt.contains("previous transcript"));
778        assert!(prepared_prompt.contains(r"\<user_prompt> Continue edits \</user_prompt>"));
779        assert!(prepared_prompt.ends_with(r"\</user_prompt>"));
780    }
781
782    #[test]
783    fn test_prepare_prompt_text_bootstraps_personality_before_user_prompt() {
784        // Arrange
785        let request = PromptPreparationRequest {
786            instruction_delivery_mode: InstructionDeliveryMode::BootstrapFull,
787            personality_prompt: Some("Review every change for correctness."),
788            personality_update: &PersonalityPromptUpdate::Unchanged,
789            prompt: "Inspect the patch.",
790            protocol_profile: ProtocolRequestProfile::SessionTurn,
791            replay_transcript: None,
792            schema_instruction_mode: ProtocolSchemaInstructionMode::PromptSchema,
793            workspace_root: test_workspace_root(),
794        };
795
796        // Act
797        let prepared_prompt = prepare_prompt_text(request).expect("prompt should render");
798        let protocol_position = prepared_prompt
799            .find("Structured response protocol:")
800            .expect("protocol preamble should be present");
801        let personality_position = prepared_prompt
802            .find("# Personality\n\nReview every change for correctness.")
803            .expect("personality should be present");
804        let user_prompt_position = prepared_prompt
805            .find("Inspect the patch.")
806            .expect("user prompt should be present");
807
808        // Assert
809        assert!(protocol_position < personality_position);
810        assert!(personality_position < user_prompt_position);
811    }
812
813    #[test]
814    fn test_prepare_prompt_text_replays_with_current_personality() {
815        // Arrange
816        let request = PromptPreparationRequest {
817            instruction_delivery_mode: InstructionDeliveryMode::BootstrapWithReplay,
818            personality_prompt: Some("Plan before editing."),
819            personality_update: &PersonalityPromptUpdate::Unchanged,
820            prompt: "Continue.",
821            protocol_profile: ProtocolRequestProfile::SessionTurn,
822            replay_transcript: Some("assistant: prior work"),
823            schema_instruction_mode: ProtocolSchemaInstructionMode::PromptSchema,
824            workspace_root: test_workspace_root(),
825        };
826
827        // Act
828        let prepared_prompt = prepare_prompt_text(request).expect("prompt should render");
829        let personality_position = prepared_prompt
830            .find("# Personality\n\nPlan before editing.")
831            .expect("personality should be present");
832        let transcript_position = prepared_prompt
833            .find(r"\<session_transcript> assistant: prior work")
834            .expect("transcript should be present");
835
836        // Assert
837        assert!(personality_position < transcript_position);
838        assert!(prepared_prompt.ends_with(r"\</user_prompt>"));
839    }
840
841    #[test]
842    /// Ensures compact refresh reminders omit the full schema while keeping
843    /// the contract reminder and task body.
844    fn test_prepend_protocol_refresh_reminder_adds_compact_contract_notice() {
845        // Arrange
846        let prompt = "Continue the implementation";
847
848        // Act
849        let rendered_prompt = protocol_prepend_refresh_reminder(
850            prompt,
851            ProtocolRequestProfile::SessionTurn,
852            test_workspace_root(),
853        );
854
855        let normalized_prompt = normalize_prompt(&rendered_prompt);
856
857        // Assert
858        assert!(rendered_prompt.contains("Protocol refresh reminder:"));
859        assert!(rendered_prompt.contains("repository-root-relative POSIX"));
860        assert!(normalized_prompt.contains("only read-only git commands; never mutating ones"));
861        assert!(rendered_prompt.contains("inside `/tmp/agentty-wt/session-1`"));
862        assert!(normalized_prompt.contains("everything outside this workspace root is read-only"));
863        assert!(
864            rendered_prompt
865                .contains("______________________________________________________________________")
866        );
867        assert!(!rendered_prompt.contains("Authoritative JSON Schema:"));
868        assert!(rendered_prompt.ends_with(prompt));
869    }
870
871    #[test]
872    /// Ensures prompt preparation can emit the compact app-server reminder
873    /// instead of the full bootstrap wrapper.
874    fn test_prepare_prompt_text_uses_delta_only_refresh_mode() {
875        // Arrange
876        let request = PromptPreparationRequest {
877            instruction_delivery_mode: InstructionDeliveryMode::DeltaOnly,
878            personality_prompt: None,
879            personality_update: &PersonalityPromptUpdate::Unchanged,
880            prompt: "Continue edits",
881            protocol_profile: ProtocolRequestProfile::SessionTurn,
882            replay_transcript: Some("previous transcript"),
883            schema_instruction_mode: ProtocolSchemaInstructionMode::PromptSchema,
884            workspace_root: test_workspace_root(),
885        };
886
887        // Act
888        let prepared_prompt = prepare_prompt_text(request).expect("prompt should render");
889
890        // Assert
891        assert!(prepared_prompt.contains("Protocol refresh reminder:"));
892        assert!(!prepared_prompt.contains("Authoritative JSON Schema:"));
893        assert!(!prepared_prompt.contains("previous transcript"));
894        assert!(prepared_prompt.ends_with("Continue edits"));
895    }
896
897    #[test]
898    fn test_prepare_prompt_text_delta_mode_sends_personality_update_and_clear() {
899        // Arrange
900        let updated = PromptPreparationRequest {
901            instruction_delivery_mode: InstructionDeliveryMode::DeltaOnly,
902            personality_prompt: Some("Ignored current body."),
903            personality_update: &PersonalityPromptUpdate::Set("Be concise.".to_string()),
904            prompt: "Continue edits",
905            protocol_profile: ProtocolRequestProfile::SessionTurn,
906            replay_transcript: None,
907            schema_instruction_mode: ProtocolSchemaInstructionMode::PromptSchema,
908            workspace_root: test_workspace_root(),
909        };
910        let cleared = PromptPreparationRequest {
911            personality_update: &PersonalityPromptUpdate::Clear,
912            ..updated
913        };
914
915        // Act
916        let updated_prompt = prepare_prompt_text(updated).expect("update should render");
917        let cleared_prompt = prepare_prompt_text(cleared).expect("clear should render");
918
919        // Assert
920        assert!(updated_prompt.contains("# Personality Update\n\nBe concise."));
921        assert!(updated_prompt.ends_with("Continue edits"));
922        assert!(cleared_prompt.contains("The session personality has been cleared."));
923        assert!(cleared_prompt.ends_with("Continue edits"));
924    }
925
926    #[test]
927    /// Ensures CLI prompt rendering replaces image placeholders with local
928    /// file paths in placeholder order.
929    fn test_render_prompt_with_local_images_replaces_placeholders_in_order() {
930        // Arrange
931        let attachments = vec![
932            TurnPromptAttachment {
933                placeholder: "[Image #1]".to_string(),
934                local_image_path: PathBuf::from("/tmp/first-image.png"),
935            },
936            TurnPromptAttachment {
937                placeholder: "[Image #2]".to_string(),
938                local_image_path: PathBuf::from("/tmp/second-image.png"),
939            },
940        ];
941
942        // Act
943        let rendered_prompt = render_prompt_with_local_images(
944            "Compare [Image #2] with [Image #1]",
945            &attachments,
946            "TestBackend",
947        )
948        .expect("prompt rendering should succeed");
949
950        // Assert
951        assert_eq!(
952            rendered_prompt,
953            "Compare /tmp/second-image.png with /tmp/first-image.png"
954        );
955    }
956
957    #[test]
958    /// Ensures CLI prompt rendering appends local image paths when attachment
959    /// metadata survives without a placeholder match.
960    fn test_render_prompt_with_local_images_appends_missing_paths() {
961        // Arrange
962        let attachments = vec![TurnPromptAttachment {
963            placeholder: "[Image #1]".to_string(),
964            local_image_path: PathBuf::from("/tmp/first-image.png"),
965        }];
966
967        // Act
968        let rendered_prompt =
969            render_prompt_with_local_images("Review this change", &attachments, "TestBackend")
970                .expect("prompt rendering should succeed");
971
972        // Assert
973        assert_eq!(
974            rendered_prompt,
975            "Review this change\n/tmp/first-image.png\n"
976        );
977    }
978
979    #[cfg(unix)]
980    #[test]
981    /// Ensures CLI prompt rendering fails fast with the provider label when an
982    /// attachment path is not valid UTF-8.
983    fn test_render_prompt_with_local_images_rejects_non_utf8_paths() {
984        // Arrange
985        let attachments = vec![TurnPromptAttachment {
986            placeholder: "[Image #1]".to_string(),
987            local_image_path: PathBuf::from(OsString::from_vec(vec![0x66, 0x80, 0x6f])),
988        }];
989
990        // Act
991        let error = render_prompt_with_local_images("Review [Image #1]", &attachments, "Claude")
992            .expect_err("prompt rendering should fail");
993
994        // Assert
995        assert_eq!(
996            error,
997            AgentBackendError::CommandBuild(
998                "Claude prompt image path is not valid UTF-8".to_string()
999            )
1000        );
1001    }
1002
1003    #[test]
1004    /// Ensures CLI prompt access roots deduplicate sorted attachment
1005    /// directories when the provider only needs attachment parents.
1006    fn test_cli_prompt_access_directories_deduplicates_attachment_directories() {
1007        // Arrange
1008        let workspace_folder = PathBuf::from("/tmp/session");
1009        let attachments = vec![
1010            TurnPromptAttachment {
1011                placeholder: "[Image #1]".to_string(),
1012                local_image_path: PathBuf::from("/tmp/images-b/two.png"),
1013            },
1014            TurnPromptAttachment {
1015                placeholder: "[Image #2]".to_string(),
1016                local_image_path: PathBuf::from("/tmp/images-a/one.png"),
1017            },
1018            TurnPromptAttachment {
1019                placeholder: "[Image #3]".to_string(),
1020                local_image_path: PathBuf::from("/tmp/images-a/three.png"),
1021            },
1022        ];
1023
1024        // Act
1025        let directories = cli_prompt_access_directories(
1026            &workspace_folder,
1027            &attachments,
1028            CliPromptAccessRootMode::AttachmentsOnly,
1029        );
1030
1031        // Assert
1032        assert_eq!(
1033            directories,
1034            vec![
1035                PathBuf::from("/tmp/images-a"),
1036                PathBuf::from("/tmp/images-b")
1037            ]
1038        );
1039    }
1040
1041    #[test]
1042    /// Ensures Antigravity-style access roots keep the workspace first and do
1043    /// not duplicate it when an attachment also lives under that directory.
1044    fn test_cli_prompt_access_directories_keeps_workspace_first() {
1045        // Arrange
1046        let workspace_folder = PathBuf::from("/tmp/z-session");
1047        let attachments = vec![
1048            TurnPromptAttachment {
1049                placeholder: "[Image #1]".to_string(),
1050                local_image_path: PathBuf::from("/tmp/z-session/one.png"),
1051            },
1052            TurnPromptAttachment {
1053                placeholder: "[Image #2]".to_string(),
1054                local_image_path: PathBuf::from("/tmp/a-images/two.png"),
1055            },
1056        ];
1057
1058        // Act
1059        let directories = cli_prompt_access_directories(
1060            &workspace_folder,
1061            &attachments,
1062            CliPromptAccessRootMode::WorkspaceThenAttachments,
1063        );
1064
1065        // Assert
1066        assert_eq!(
1067            directories,
1068            vec![workspace_folder, PathBuf::from("/tmp/a-images")]
1069        );
1070    }
1071}