Skip to main content

drep/analysis/
prompt.rs

1//! The code-quality system prompt for one language.
2//!
3//! The prompt is the bridge between the deterministic layer (the configured
4//! linters and formatters) and the semantic layer (the LLM): it tells the
5//! model what drep has already done and what is left for it to do. The body
6//! is identical for every language; only `display_name` and `conventions`
7//! vary, so the JSON shape the model is asked to return is never language-
8//! dependent and the parser in [`crate::analysis::code_quality`] stays total.
9//!
10//! Two instructions are load-bearing and must survive untouched:
11//!
12//! - The "do not report anything a formatter or linter would catch" line.
13//!   The deterministic layer already produces those findings, and without
14//!   this guard the model floods every file with lint noise that the gate
15//!   then has to deduplicate against the tooling's own output.
16//! - The schema block. A model that emits a different shape is, from the
17//!   parser's point of view, an unanalyzed file — the parser does not
18//!   attempt to recover a foreign schema.
19//!
20//! Every payload line carries its real file line number in the gutter, and a
21//! finding must not be reported on a line that has no number. Together with
22//! [`crate::analysis::payload::Payload::valid_lines`] they are the line-
23//! number provenance the parser relies on to drop findings that point at
24//! code the model was never shown.
25
26use crate::analysis::findings::LlmSeverity;
27use crate::analysis::response_contract::{
28    CATEGORY, CODE_SNIPPET, COMPILE_FAILURE, ISSUES, LINE, MESSAGE, SEVERITY, SUGGESTION, SUMMARY,
29};
30use crate::languages::spec::LanguageSupport;
31
32/// Build the code-quality system prompt for one language.
33///
34/// The whole body is one template: the categories, the JSON schema, and the
35/// "do not duplicate the linter" instruction are fixed across languages, so
36/// the model is always answering the same question in the same shape. Only
37/// `display_name` and the optional `conventions` block move.
38///
39/// Pass `&LanguageSupport` rather than `&str` so the registry key
40/// (`"rust"`) cannot be substituted for the model-facing name (`"Rust"`).
41pub fn build_analysis_prompt(language: &LanguageSupport) -> String {
42    let conventions = conventions_block(language);
43    let display_name = language.display_name;
44    // Rendered from the same review vocabulary as the strict output schema.
45    // The parser accepts the wider legacy vocabulary so an old cache entry or
46    // unconstrained provider response cannot make a whole file malformed.
47    let severities = LlmSeverity::review_alternation();
48    let issues = ISSUES;
49    let summary = SUMMARY;
50    let line = LINE;
51    let severity = SEVERITY;
52    let category = CATEGORY;
53    let message = MESSAGE;
54    let suggestion = SUGGESTION;
55    let code_snippet = CODE_SNIPPET;
56    let compile_failure = COMPILE_FAILURE;
57    // The template is shaped so the conventions block, when empty, leaves
58    // no stray heading and no doubled blank line. The newline after the
59    // placeholder is the only one that exists in the template, so an
60    // empty conventions block is followed directly by `For each issue
61    // found`.
62    format!(
63        "You are an expert {display_name} code reviewer.\n\
64         Review the following code as a merge gate. Report only concrete issues\n\
65         that are worth fixing before merge:\n\
66         \n\
67         1. **Bugs & Logic Errors**: Incorrect logic, reachable crashes, data\n\
68            loss, broken contracts, type errors\n\
69         2. **Security Issues**: Injection, path traversal, unsafe deserialization,\n\
70            hardcoded secrets, weak cryptography\n\
71         3. **Reliability & Maintainability Defects**: Resource leaks, races,\n\
72            inconsistent state, or a design defect with a concrete failure mode\n\
73         4. **Performance Defects**: Material algorithmic or resource problems on\n\
74            a plausible execution path\n\
75         \n\
76         {conventions}\
77         For each issue found, provide:\n\
78         - The exact gutter line number of the affected code\n\
79         - Severity: critical (security vulnerabilities, data loss), high (bugs,\n\
80           crashes, serious issues), medium (material but non-critical defects).\n\
81           Low and info suggestions are outside this review and must not be emitted\n\
82         - Category: bug, security, performance, maintainability\n\
83         - Clear message explaining the issue\n\
84         - Specific, actionable suggestion for fixing it\n\
85         - The problematic code snippet\n\
86         - Whether the finding explicitly claims the code cannot compile\n\
87         \n\
88         **Important instructions:**\n\
89         - Only report a finding when it is concrete and reachable from the code\n\
90           shown, with a plausible execution path and a material consequence\n\
91         - This is not an exhaustive hardening exercise. Do not report optional hardening,\n\
92           extreme edge cases without a plausible execution path, nits, subjective\n\
93           preferences, cleanup, or refactoring opportunities\n\
94         - Do not report missing tests or documentation unless their absence creates\n\
95           a concrete product or API defect in the shown change\n\
96         - Prefer no finding over a speculative or marginal finding\n\
97         - Provide actionable suggestions, not vague advice\n\
98         - Focus on correctness, security, reliability, and material performance\n\
99         - The input is a line-numbered excerpt. Report the finding's `line`\n\
100           as the number shown in the gutter, never an offset into the\n\
101           excerpt. The excerpt itself states which lines are in scope.\n\
102         - Do not report subjective style issues, and do not report anything a\n\
103           formatter or linter would catch: those run separately and deterministically\n\
104         \n\
105         Return your analysis as valid JSON matching this exact schema:\n\
106         {{\n\
107           \"{issues}\": [\n\
108             {{\n\
109               \"{line}\": <line_number>,\n\
110               \"{severity}\": \"<{severities}>\",\n\
111               \"{category}\": \"<bug|security|performance|maintainability>\",\n\
112               \"{message}\": \"<clear description of the issue>\",\n\
113               \"{suggestion}\": \"<specific recommendation for fixing>\",\n\
114               \"{code_snippet}\": \"<the problematic code>\",\n\
115               \"{compile_failure}\": <true|false>\n\
116             }}\n\
117           ],\n\
118           \"{summary}\": \"<overall assessment of code quality>\"\n\
119         }}\n\
120         \n\
121         If no issues are found, return:\n\
122         {{\n\
123           \"{issues}\": [],\n\
124           \"{summary}\": \"No significant issues found. Code quality looks good.\"\n\
125         }}\n"
126    )
127}
128
129/// Build the language-specific concerns block, or an empty string when the
130/// language has no conventions.
131///
132/// Heading + one bullet per entry, trailing newline. The newline is consumed
133/// by the template's own following newline so a missing block leaves no
134/// blank hole and a present block does not leave a doubled one.
135fn conventions_block(language: &LanguageSupport) -> String {
136    if language.conventions.is_empty() {
137        return String::new();
138    }
139    let mut out = format!("**{}-specific concerns:**\n", language.display_name);
140    for concern in language.conventions {
141        out.push_str("- ");
142        out.push_str(concern);
143        out.push('\n');
144    }
145    out
146}