1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum ProtocolSchemaInstructionMode {
18 PromptSchema,
21 TransportSchema,
24}
25
26impl ProtocolSchemaInstructionMode {
27 fn includes_response_json_schema(self) -> bool {
30 matches!(self, Self::PromptSchema)
31 }
32}
33
34#[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#[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#[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#[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#[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#[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#[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#[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#[derive(Template)]
179#[template(path = "protocol_instruction_session_turn_usage.md", escape = "none")]
180struct ProtocolInstructionSessionTurnUsageTemplate;
181
182#[derive(Template)]
184#[template(path = "protocol_instruction_utility_prompt_usage.md", escape = "none")]
185struct ProtocolInstructionUtilityPromptUsageTemplate;
186
187#[derive(Template)]
189#[template(path = "protocol_instruction_focused_review_usage.md", escape = "none")]
190struct ProtocolInstructionFocusedReviewUsageTemplate;
191
192#[derive(Template)]
194#[template(path = "protocol_refresh_session_turn_instruction.md", escape = "none")]
195struct ProtocolRefreshSessionTurnInstructionTemplate;
196
197#[derive(Template)]
199#[template(
200 path = "protocol_refresh_utility_prompt_instruction.md",
201 escape = "none"
202)]
203struct ProtocolRefreshUtilityPromptInstructionTemplate;
204
205fn 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
227fn 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
249fn 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
259fn 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 fn test_workspace_root() -> &'static Path {
277 Path::new("/tmp/agentty-wt/session-1")
278 }
279
280 fn normalize_prompt(prompt: &str) -> String {
282 prompt.split_whitespace().collect::<Vec<_>>().join(" ")
283 }
284
285 #[test]
286 fn test_prepend_protocol_instructions_adds_session_protocol_instructions() {
288 let prompt = "Implement feature";
290
291 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!(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 fn test_prepend_protocol_instructions_omits_schema_for_transport_schema_mode() {
371 let prompt = "Implement feature";
373
374 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!(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 fn test_prepend_protocol_instructions_is_idempotent() {
399 let prompt = prepend_protocol_instructions(
401 "Implement feature",
402 ProtocolRequestProfile::SessionTurn,
403 ProtocolSchemaInstructionMode::PromptSchema,
404 test_workspace_root(),
405 );
406
407 let rendered_prompt = prepend_protocol_instructions(
409 &prompt,
410 ProtocolRequestProfile::UtilityPrompt,
411 ProtocolSchemaInstructionMode::TransportSchema,
412 test_workspace_root(),
413 );
414
415 assert_eq!(rendered_prompt, prompt);
417 }
418
419 #[test]
420 fn test_prepend_protocol_instructions_reuses_same_contract_for_one_shot() {
423 let prompt = "Generate title";
425
426 let rendered_prompt = prepend_protocol_instructions(
428 prompt,
429 ProtocolRequestProfile::UtilityPrompt,
430 ProtocolSchemaInstructionMode::PromptSchema,
431 test_workspace_root(),
432 );
433
434 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 fn test_prepend_protocol_instructions_preserves_prompt_placeholders() {
456 let prompt = "Keep these literal: {{ response_json_schema }} {{ \
458 protocol_usage_instructions }} {{ workspace_root }}";
459
460 let rendered_prompt = prepend_protocol_instructions(
462 prompt,
463 ProtocolRequestProfile::UtilityPrompt,
464 ProtocolSchemaInstructionMode::PromptSchema,
465 test_workspace_root(),
466 );
467
468 assert!(rendered_prompt.ends_with(prompt));
470 }
471
472 #[test]
473 fn test_prepend_protocol_refresh_reminder_adds_compact_contract_notice() {
476 let prompt = "Continue the implementation";
478
479 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!(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 fn test_prepend_protocol_refresh_reminder_preserves_prompt_placeholders() {
507 let prompt = "Keep this literal: {{ protocol_refresh_instructions }} {{ workspace_root }}";
509
510 let rendered_prompt = prepend_protocol_refresh_reminder(
512 prompt,
513 ProtocolRequestProfile::SessionTurn,
514 test_workspace_root(),
515 );
516
517 assert!(rendered_prompt.ends_with(prompt));
519 }
520
521 #[test]
522 fn test_prepend_protocol_refresh_reminder_uses_utility_profile() {
525 let prompt = "Generate another title";
527
528 let rendered_prompt = prepend_protocol_refresh_reminder(
530 prompt,
531 ProtocolRequestProfile::UtilityPrompt,
532 test_workspace_root(),
533 );
534
535 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 let prompt = "Repair the focused review";
546
547 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!(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 fn test_build_protocol_repair_prompt_includes_error_and_preview() {
564 let parse_error = "response is not valid protocol JSON: invalid JSON";
566 let malformed_response = "plain text response";
567
568 let repair_prompt = build_protocol_repair_prompt(parse_error, malformed_response);
570
571 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 let malformed_response = r#"{"project_impact":[],"suggestions":[]} trailing"#;
583
584 let repair_prompt = build_protocol_repair_prompt_for_profile(
586 ProtocolRequestProfile::FocusedReview,
587 "trailing characters",
588 malformed_response,
589 );
590
591 assert!(repair_prompt.contains("\"title\": \"FocusedReview\""));
593 assert!(repair_prompt.contains("\"project_impact\""));
594 assert!(!repair_prompt.contains("\"answer\""));
595 }
596
597 #[test]
598 fn test_build_protocol_repair_prompt_preserves_response_preview_placeholders() {
601 let malformed_response = "Keep this literal: {{ response_json_schema }}";
603
604 let repair_prompt =
606 build_protocol_repair_prompt("schema validation failed", malformed_response);
607
608 assert!(repair_prompt.contains(malformed_response));
610 }
611
612 #[test]
613 fn test_build_protocol_repair_prompt_truncates_long_response() {
615 let parse_error = "schema validation failed";
617 let malformed_response = "x".repeat(1000);
618
619 let repair_prompt = build_protocol_repair_prompt(parse_error, &malformed_response);
621
622 assert!(repair_prompt.contains("500 more chars"));
624 assert!(!repair_prompt.contains(&malformed_response));
625 }
626
627 #[test]
628 fn test_build_protocol_repair_prompt_contains_protocol_marker() {
630 let repair_prompt = build_protocol_repair_prompt("error", "response");
632
633 assert!(repair_prompt.contains("Structured response protocol:"));
635 }
636
637 #[test]
638 fn test_truncate_preview_keeps_short_responses_intact() {
640 let preview = truncate_preview("short", 500);
642
643 assert_eq!(preview, "short");
645 }
646
647 #[test]
648 fn test_truncate_preview_truncates_long_responses() {
650 let long_response = "a".repeat(600);
652
653 let preview = truncate_preview(&long_response, 500);
655
656 assert!(preview.starts_with(&"a".repeat(500)));
658 assert!(preview.contains("100 more chars"));
659 }
660}