1use 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#[derive(Template)]
21#[template(path = "resume_with_transcript_prompt.md", escape = "none")]
22struct ResumeWithTranscriptPromptTemplate<'a> {
23 prompt: &'a str,
25 transcript: &'a str,
27}
28
29#[derive(Template)]
31#[template(path = "personality_prompt.md", escape = "none")]
32struct PersonalityPromptTemplate<'a> {
33 heading: &'a str,
35 personality: &'a str,
37 prompt: &'a str,
39}
40
41#[derive(Template)]
43#[template(path = "response_style_prompt.md", escape = "none")]
44struct ResponseStylePromptTemplate<'a> {
45 instruction: &'a str,
47 prompt: &'a str,
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub(crate) struct PromptPreparationRequest<'a> {
54 pub instruction_delivery_mode: InstructionDeliveryMode,
56 pub personality_prompt: Option<&'a str>,
58 pub personality_update: &'a PersonalityPromptUpdate,
60 pub prompt: &'a str,
62 pub protocol_profile: ProtocolRequestProfile,
64 pub replay_transcript: Option<&'a str>,
66 pub schema_instruction_mode: ProtocolSchemaInstructionMode,
69 pub workspace_root: &'a Path,
72}
73
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub(crate) enum CliPromptAccessRootMode {
78 AttachmentsOnly,
80 WorkspaceThenAttachments,
82}
83
84pub(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
125pub(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
145pub(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
178pub(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
196pub(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
209fn 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
229fn 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
251pub(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
269pub(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
317pub(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
349fn 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
368pub 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
395fn 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 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 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_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 fn test_workspace_root() -> &'static Path {
462 Path::new("/tmp/agentty-wt/session-1")
463 }
464
465 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 let attachment = TurnPromptAttachment {
474 local_image_path: PathBuf::from("/tmp/example.png"),
475 placeholder: "[Image #1]".to_string(),
476 };
477
478 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 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 let prompt = TurnPrompt::from_agent_data("Generate a title".to_string());
509
510 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_eq!(styled_prompt, prompt);
520 }
521
522 #[test]
523 fn test_diff_fence_returns_minimum_three_backticks_for_plain_diff() {
526 let diff = "diff --git a/a.rs b/a.rs\n+fn main() {}\n";
528
529 let fence = diff_fence(diff);
531
532 assert_eq!(fence, "```");
534 }
535
536 #[test]
537 fn test_diff_fence_exceeds_longest_backtick_run_in_diff() {
541 let diff = "+```\nsample\n+```\n";
543
544 let fence = diff_fence(diff);
546
547 assert_eq!(fence, "````");
549 }
550
551 #[test]
552 fn test_diff_fence_handles_long_backtick_runs() {
555 let diff = "prefix `````diff\ncontent\n`````\n";
557
558 let fence = diff_fence(diff);
560
561 assert_eq!(fence, "``````");
563 }
564
565 #[test]
566 fn test_build_resume_prompt_includes_replay_transcript_and_prompt() {
569 let prompt = "Continue tests; keep {{ transcript }} literal";
571 let replay_transcript = Some(" previous {{ prompt }} line \n");
572
573 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!(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 fn test_build_resume_prompt_returns_original_prompt_when_output_is_blank() {
598 let prompt = "Follow-up request";
600 let replay_transcript = Some(" ");
601
602 let resume_prompt =
604 build_resume_prompt(prompt, replay_transcript).expect("resume prompt should render");
605
606 assert_eq!(resume_prompt, prompt);
608 }
609
610 #[test]
611 fn test_build_resume_prompt_returns_original_prompt_without_output() {
613 let prompt = "Retry merge";
615
616 let resume_prompt = build_resume_prompt(prompt, None).expect("resume prompt should render");
618
619 assert_eq!(resume_prompt, prompt);
621 }
622
623 #[test]
624 fn test_prepend_protocol_instructions_adds_session_protocol_instructions() {
626 let prompt = "Implement feature";
628
629 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!(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 fn test_prepend_protocol_instructions_omits_schema_for_transport_schema_mode() {
685 let prompt = "Implement feature";
687
688 let rendered_prompt = protocol_prepend_instructions(
690 prompt,
691 ProtocolRequestProfile::SessionTurn,
692 ProtocolSchemaInstructionMode::TransportSchema,
693 test_workspace_root(),
694 );
695
696 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 let payload = "Structured response protocol: quoted in a user request";
709
710 let rendered = protocol_prepend_instructions(
712 payload,
713 ProtocolRequestProfile::SessionTurn,
714 ProtocolSchemaInstructionMode::TransportSchema,
715 test_workspace_root(),
716 );
717
718 assert!(rendered.starts_with("File path output requirements:"));
720 assert!(rendered.ends_with(payload));
721 }
722
723 #[test]
724 fn test_prepend_protocol_instructions_reuses_same_contract_for_one_shot() {
727 let prompt = "Generate title";
729
730 let rendered_prompt = protocol_prepend_instructions(
732 prompt,
733 ProtocolRequestProfile::UtilityPrompt,
734 ProtocolSchemaInstructionMode::PromptSchema,
735 test_workspace_root(),
736 );
737
738 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 fn test_prepare_prompt_text_applies_replay_and_protocol_instructions() {
759 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 let prepared_prompt = prepare_prompt_text(request).expect("prompt should render");
773
774 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 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 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!(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 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 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!(personality_position < transcript_position);
838 assert!(prepared_prompt.ends_with(r"\</user_prompt>"));
839 }
840
841 #[test]
842 fn test_prepend_protocol_refresh_reminder_adds_compact_contract_notice() {
845 let prompt = "Continue the implementation";
847
848 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!(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 fn test_prepare_prompt_text_uses_delta_only_refresh_mode() {
875 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 let prepared_prompt = prepare_prompt_text(request).expect("prompt should render");
889
890 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 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 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!(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 fn test_render_prompt_with_local_images_replaces_placeholders_in_order() {
930 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 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_eq!(
952 rendered_prompt,
953 "Compare /tmp/second-image.png with /tmp/first-image.png"
954 );
955 }
956
957 #[test]
958 fn test_render_prompt_with_local_images_appends_missing_paths() {
961 let attachments = vec![TurnPromptAttachment {
963 placeholder: "[Image #1]".to_string(),
964 local_image_path: PathBuf::from("/tmp/first-image.png"),
965 }];
966
967 let rendered_prompt =
969 render_prompt_with_local_images("Review this change", &attachments, "TestBackend")
970 .expect("prompt rendering should succeed");
971
972 assert_eq!(
974 rendered_prompt,
975 "Review this change\n/tmp/first-image.png\n"
976 );
977 }
978
979 #[cfg(unix)]
980 #[test]
981 fn test_render_prompt_with_local_images_rejects_non_utf8_paths() {
984 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 let error = render_prompt_with_local_images("Review [Image #1]", &attachments, "Claude")
992 .expect_err("prompt rendering should fail");
993
994 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 fn test_cli_prompt_access_directories_deduplicates_attachment_directories() {
1007 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 let directories = cli_prompt_access_directories(
1026 &workspace_folder,
1027 &attachments,
1028 CliPromptAccessRootMode::AttachmentsOnly,
1029 );
1030
1031 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 fn test_cli_prompt_access_directories_keeps_workspace_first() {
1045 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 let directories = cli_prompt_access_directories(
1060 &workspace_folder,
1061 &attachments,
1062 CliPromptAccessRootMode::WorkspaceThenAttachments,
1063 );
1064
1065 assert_eq!(
1067 directories,
1068 vec![workspace_folder, PathBuf::from("/tmp/a-images")]
1069 );
1070 }
1071}