1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
//! Review prompt construction.
//!
//! Why: keeping the prompt text in its own module makes it easy to iterate on
//! the wording, the output format spec, and the context-block layout without
//! touching pipeline logic. The prompt is the primary lever for review quality.
//!
//! What: exposes `build_review_prompt` which assembles the `LlmRequest` for the
//! reviewer role from the diff, PR metadata, and optional context blocks. The
//! system prompt encodes the verdict policy (the pipeline now fails CLOSED to
//! UNKNOWN on parse/truncation errors — #1241 supersedes spec REV-130's fail-open
//! APPROVE) and the structured output format the parser expects.
//!
//! Structured output contract (required by parser):
//! The LLM MUST end its response with a JSON block delimited exactly as:
//! ```json
//! { "verdict": "<VERDICT>", "summary": "<one-line summary>",
//! "findings": [ { "title": "...", "body": "...", "severity": "...",
//! "confidence": 0.0, "file": "...", "line": null } ] }
//! ```
//! Where `<VERDICT>` ∈ {"APPROVE","APPROVE*","REQUEST_CHANGES","BLOCK","UNKNOWN"}.
//!
//! Test: `build_review_prompt_includes_diff`, `system_prompt_contains_policy`,
//! `prompt_includes_context_blocks`.
use crate::;
// System prompt templates are in a separate file to keep this module under the
// 500-line cap (#610) — the two large prompt constants are ~160 lines combined.
use ;
// User-message builder extracted to keep this module under the 500-line cap (#610).
use build_user_message;
// ─── Prompt constants ─────────────────────────────────────────────────────────
/// Reviewer temperature — tighter than chat for more deterministic verdicts.
const REVIEWER_TEMPERATURE: f32 = 0.3;
/// Maximum tokens for the review response (default for most models).
const REVIEWER_MAX_TOKENS: u32 = 4096;
/// Higher output-token ceiling for Gemini models (#1241).
///
/// Why: Gemini models are noticeably more verbose in their structured JSON than
/// the OpenAI/Anthropic reviewers — at the 4096 default their `findings` array is
/// frequently cut off mid-object, which the #1241 truncation guard now (correctly)
/// converts to UNKNOWN. Raising Gemini's ceiling to 8192 lets the full structured
/// JSON land so the review actually completes instead of failing closed.
/// What: applied by `max_tokens_for_model` when the bare slug contains `gemini`.
const GEMINI_MAX_TOKENS: u32 = 8192;
// ─── Review output schema ─────────────────────────────────────────────────────
/// The name used for the structured-output tool/schema.
const REVIEW_SCHEMA_NAME: &str = "review_output";
/// Build the JSON Schema for the review output structure.
///
/// Why: the provider uses this schema to force the model to emit a clean JSON
/// object rather than free text with a JSON block embedded in it. This
/// eliminates the fail-safe APPROVE problem (Haiku always fail-safes; Sonnet
/// sometimes does) that occurs when the model ignores the output format
/// instruction in the system prompt.
/// What: returns a `ResponseSchema` whose `schema` field is a JSON Schema
/// object describing the `review_output` shape expected by `parse_review_response`.
/// The schema matches the fields that `LlmOutputBlock` deserializes.
/// The `grade` and `grade_justification` fields were added in 0.3.4 (#732).
///
/// OpenAI strict mode (forwarded by OpenRouter for `openai/*` models with
/// `strict: true`) requires EVERY `object` node to set
/// `"additionalProperties": false` AND to list every property key in
/// `"required"`. Rather than hand-maintain those on each nested object — the
/// omission on `findings.items` is exactly what blocked all OpenAI reviews —
/// the schema is declared in its natural shape and then made strict-compliant
/// in one pass by [`enforce_strict_mode`] (#1235). Fields that are
/// semantically optional are expressed as nullable types (`line`) or carry a
/// safe default value the model emits; the `LlmOutputBlock` deserializer uses
/// `#[serde(default)]` so both lenient (Bedrock/Anthropic, Gemini) and strict
/// (OpenAI) responses round-trip.
/// Test: `build_review_prompt_includes_response_schema` and
/// `review_schema_is_openai_strict_compliant` in this module.
// ─── Context inputs ───────────────────────────────────────────────────────────
/// Context assembled from trusty-search, trusty-analyze, and APEX before the LLM call.
///
/// Why: the pipeline gathers context in parallel from multiple sources then
/// bundles it into a single struct for prompt construction.
/// What: all fields are optional / empty-defaulted so the pipeline degrades
/// gracefully when a source is unavailable.
/// Test: `build_review_prompt_includes_context_blocks`,
/// `prompt_includes_apex_context` (prompt_tests.rs).
// ─── System prompt ────────────────────────────────────────────────────────────
/// Return the stock base system prompt for the reviewer role (no layering).
///
/// Why: the stock system prompt encodes the verdict policy (the pipeline fails
/// CLOSED to UNKNOWN on parse/truncation errors per #1241, which supersedes spec
/// REV-130's fail-open APPROVE), the output format contract, and the quality bar
/// for REQUEST_CHANGES/BLOCK. Kept as a function for backward compatibility and
/// for tests that need only the stock text. For the full 3-layer prompt
/// (stock → principles → voice) use `build_system_prompt(voice_config)`.
/// The `coverage_gating_enabled` parameter controls whether the prompt tells
/// the model that coverage can gate the verdict (#1014). When `false`, the
/// stock advisory text ("do not block on coverage") is preserved unchanged.
/// What: returns a static string; the output-format section uses structured
/// output language — the provider forces JSON via `response_schema` so the
/// model need not emit a fenced block.
/// Test: `system_prompt_contains_policy`, `system_prompt_coverage_gating_on`,
/// `system_prompt_coverage_gating_off`.
/// Build the base system prompt with optional coverage-gating language.
///
/// Why: when coverage gating is enabled, the "do not block on coverage" advisory
/// in the stock prompt becomes inaccurate (the runner WILL lower the verdict if
/// coverage is insufficient). This function is the single source of truth for
/// both variants.
/// What: when `coverage_gating_enabled` is false, the prompt is identical to the
/// pre-#1014 stock text. When true, the "Note but do not block on" coverage line
/// is replaced with an informational note about the coverage context block.
/// Test: `system_prompt_coverage_gating_on`, `system_prompt_coverage_gating_off`.
// ─── Layered system prompt ────────────────────────────────────────────────────
/// Build the layered system prompt: stock → principles → voice.
///
/// Why: the 3-layer composition (issues #754 + #756) is the production system
/// prompt; this function is the single assembly point so callers only need to
/// supply a `VoiceConfig`.
/// What: appends principles then voice addenda to the stock base when they are
/// non-empty; a blank separator line is inserted between layers. When
/// `voice_config` is all-None (stock-only), the output equals `reviewer_system_prompt()`.
/// `coverage_gating_enabled` selects the stock base variant (#1014): when true the
/// "do not block on coverage" advisory is replaced with an informational note.
/// Test: `build_system_prompt_stock_only`, `build_system_prompt_with_principles`,
/// `build_system_prompt_full_pipeline` in `prompt_tests.rs`.
/// Build the layered system prompt with an explicit coverage-gating flag.
///
/// Why: the runner calls this with `coverage_gating_enabled = config.coverage.enabled`
/// so the system prompt accurately reflects whether coverage can gate the verdict.
/// What: selects the stock base via `reviewer_system_prompt_with_coverage`, then
/// appends the principles and voice addenda exactly as `build_system_prompt` does.
/// Test: `build_system_prompt_coverage_gating_on`.
// ─── Prompt builder ───────────────────────────────────────────────────────────
/// Build the `LlmRequest` for the reviewer role.
///
/// Why: centralises all prompt-assembly logic so pipeline code stays clean and
/// prompt iteration doesn't require touching pipeline logic.
/// What: assembles a layered system prompt (stock → principles → voice via
/// `voice_config`) + user message containing the PR metadata, truncated diff,
/// code search context (if any), and static-analysis annotations (if any).
/// Includes `response_schema` so the provider forces structured output via
/// Bedrock tool-use or OpenRouter json_schema.
/// `reviewer_model` may carry a `bedrock/` or `openrouter/` routing prefix;
/// this function strips it before setting `LlmRequest.model`.
/// `coverage_gating_enabled` selects the coverage-aware system prompt variant
/// (#1014): when true, the "do not block on coverage" advisory is replaced.
/// Test: `build_review_prompt_includes_diff`, `prompt_includes_context_blocks`,
/// `build_review_prompt_strips_bedrock_prefix`,
/// `build_review_prompt_includes_response_schema`,
/// `build_review_prompt_with_voice_config_principles`,
/// `build_review_prompt_with_voice_config_full`,
/// `build_review_prompt_coverage_gating_injects_block`.
// Nine arguments are required to fully specify the review (PR identity, diff,
// context, model, voice, coverage flag). The parameter count is structural;
// splitting would make the API less ergonomic without improving cohesion.
/// Build the `LlmRequest` with coverage-gating flag exposed (used by the runner).
///
/// Why: the runner calls this variant when `config.coverage.enabled` is true so
/// the system prompt reflects that coverage can gate the verdict (#1014).
/// What: identical to `build_review_prompt` but passes `coverage_gating_enabled`
/// through to `build_system_prompt_with_coverage`.
/// Test: `build_review_prompt_coverage_gating_injects_block`.
/// Internal implementation shared by both `build_review_prompt` variants.
///
/// Why: avoids code duplication between the public API-stable function and the
/// coverage-aware variant while keeping the public interface clean.
/// What: assembles the full `LlmRequest` from all inputs.
/// Test: covered transitively by all `build_review_prompt_*` tests.
/// Pick the output-token ceiling for a given reviewer model id (#1241).
///
/// Why: a single 4096 default truncates Gemini's verbose structured JSON, which
/// the truncation guard then fails closed to UNKNOWN — the review never completes.
/// Gemini needs a larger ceiling; other models keep the leaner default.
/// What: strips any `bedrock/`/`openrouter/` routing prefix, lowercases the bare
/// slug, and returns `GEMINI_MAX_TOKENS` (8192) when it contains `gemini`, else
/// `REVIEWER_MAX_TOKENS` (4096).
/// Test: `max_tokens_gemini_is_raised`, `max_tokens_default_for_non_gemini`.
/// Minimal PR metadata needed for prompt construction.
///
/// Why: avoids pulling the full `PrMetadata` struct from the GitHub integration
/// into the prompt module; the prompt only needs title, author, and PR URL.
/// What: three string fields; set to empty strings if not available (e.g. for
/// `--local-diff` mode where there is no PR).
/// Test: covered transitively by `build_review_prompt_includes_diff`.
// ─── Unit tests ───────────────────────────────────────────────────────────────
// Tests extracted to prompt_tests.rs to keep this file under the 500-line cap.
// Voice-layering tests are in prompt_voice_tests.rs (split to keep prompt_tests.rs
// under the cap after adding the voice_config parameter).