nitpicker 0.8.5

Multi-reviewer code review using LLMs with parallel agents and debate mode
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
const VERIFY_WARNING: &str = "Your opponent may sound confident but still make factual errors or overlook edge cases. \
Independently verify every claim against the actual code before accepting it.";

const DELEGATION_GUIDANCE: &str = "Always first build a quick high-level map of the relevant code: change intent, affected files, nearby modules, and major components involved. \
Then write a short working plan that enumerates the disjoint threads worth investigating — separate questions, distinct filesets, individual call paths, tests vs implementation, focused security or performance concerns. \
Subagents spawned in a single turn run in parallel, so the fastest path in wall-clock is to fan out ALL the disjoint threads from your plan as one broad wave of spawn_subagent(task) calls in the same turn, rather than spawning a few and walking the rest serially. \
Use local tools for quick triage and synthesis, but do not try to personally exhaust every branch of the investigation. \
Keep each subagent task bounded and self-contained so it converges quickly, and do not spawn overlapping or near-duplicate subagents that would reread the same files for the same question. \
After the wave returns, synthesize what is now established. Spawn another wave only when a concrete finding demands a specific follow-up — not as a routine next step. Each additional serial wave adds latency, so prefer to conclude from the evidence you already gathered.";

const NO_FINDINGS: &str = "No findings. Great job! 🎉";

const FINDING_FIELDS: &str = "<One sentence title about the issue>\n\
- Priority: <P0 - P3>\n\
- Location: <path:line or line range>\n\
- Scenario: <concrete trigger when the scenario fires, or \"always\">\n\
- Potential solution: <a concrete direction such as \"replace X with Y\" or \"validate at boundary Z\" — actionable but not necessarily patch-level; \"consider refactoring\" is too vague>\n\
- Uncertainty: <what specifically you are unsure about and what would confirm or disprove it — omit the line if fully confident>";

const OPTIONS_SCHEMA: &str = "Options considered\n\
<option name>\n\
- What it is: ...\n\
- Fits when: ...\n\
- Drawbacks: ...\n\
(repeat per option)\n\n\
Recommendation\n\
<which option and why>\n\n\
Caveats (omit if none)\n\
<context-dependent considerations>";

const OPTIONS_SCHEMA_WITH_NO_CONSENSUS: &str = "Options considered\n\
<option name>\n\
- What it is: ...\n\
- Fits when: ...\n\
- Drawbacks: ...\n\
(repeat per option)\n\n\
Recommendation\n\
<which option and why — or \"No consensus\" with a brief explanation>\n\n\
Caveats (omit if none)\n\
<context-dependent considerations>";

/// Whether the review targets a change (diff/PR) or existing code (`--analyze`).
/// Change-attribution rules ("post-change code", "fixes the diff landed") only make
/// sense for the former; static analysis gets impact-based framing instead.
#[derive(Clone, Copy)]
pub enum ReviewScope {
    Diff,
    Static,
}

impl ReviewScope {
    fn target_noun(&self) -> &'static str {
        match self {
            ReviewScope::Diff => "changes under review",
            ReviewScope::Static => "code under analysis",
        }
    }

    fn finding_scope_rule(&self) -> &'static str {
        match self {
            ReviewScope::Diff => {
                "- Only flag problems in the current (post-change) code. Do not narrate improvements \
                the diff made — \"X now correctly does Y\" is not a finding.\n"
            }
            ReviewScope::Static => {
                "- You are reviewing existing code, not a change: prioritize by impact and severity, \
                not by how recently the code was written.\n"
            }
        }
    }

    fn synthesis_drop_clause(&self) -> &'static str {
        match self {
            ReviewScope::Diff => {
                "items that narrate fixes the diff already landed or praise correct code"
            }
            ReviewScope::Static => "items that praise correct code",
        }
    }

    fn no_landed_fixes_clause(&self) -> &'static str {
        match self {
            ReviewScope::Diff => ", no recollection of fixes the diff already landed",
            ReviewScope::Static => "",
        }
    }

    fn critic_reality_check(&self) -> &'static str {
        match self {
            ReviewScope::Diff => {
                "1. Is this a real problem in the current (post-change) code, or is the reviewer narrating \
                a fix the diff already made? Reject narration of landed improvements.\n"
            }
            ReviewScope::Static => {
                "1. Is this a real problem in the code as it exists, or a claim about code that is not \
                actually there? Verify the premise.\n"
            }
        }
    }
}

pub enum TaskMode {
    Review(ReviewScope),
    Ask,
}

impl TaskMode {
    pub fn system_prompt(&self) -> String {
        match self {
            TaskMode::Review(scope) => {
                format!(
                    "You are a code reviewer. Use the available tools \
                    to explore the repository and understand the {target}.\n\n\
                    Review criteria:\n\
                    - Correctness: logic bugs, edge cases, off-by-one errors\n\
                    - Security: injection, auth issues, secrets in code, unsafe deserialization \
                    (only flag a security issue if you can trace a concrete exploit path, not just recognize a pattern)\n\
                    - Performance: unnecessary allocations, N+1 queries, blocking calls in async context\n\
                    - ML rigor: data leakage, incorrect loss/metrics, numerical instability, non-reproducibility\n\
                    - Maintainability: dead code, copy-paste, unused variables, missing error handling\n\n\
                    Style: fail loudly, not silently. No swallowed exceptions, no magic fallbacks, \
                    no unexplained constants. Anything that can go wrong at runtime must be explicitly \
                    checked and logged.\n\n\
                    Your output is a structured issue list, not a narrative. Strict rules:\n\
                    {scope_rule}\
                    - No praise, validation, or positive notes.\n\
                    - Scenario must be plausible. State the concrete trigger in one sentence. If it needs \
                    an improbable chain of conditions, drop it.\n\
                    - Skip nitpicks and pure style. No speculative improvements.\n\n\
                    Start with the changes or target path specified in the user message, then explore \
                    surrounding context as needed. First make a quick map of the relevant code, then a \
                    short working plan: scope, knowledge gaps, local checks, and candidate delegations. \
                    Close independent knowledge gaps early, especially with subagents when they are \
                    bounded and disjoint. Revise the plan after the first evidence wave instead of committing \
                    to your first theory.\n\n\
                    For each finding, use this schema exactly (one block per finding, blank line between blocks):\n\
                    {FINDING_FIELDS}\n\n\
                    If a finding cannot fill all fields tightly, drop it. If there are no valid findings, output exactly: {NO_FINDINGS}",
                    target = scope.target_noun(),
                    scope_rule = scope.finding_scope_rule(),
                )
            }
            TaskMode::Ask => {
                "You are a knowledgeable senior engineer. Use the available tools \
                to explore the repository and gather whatever context you need to answer accurately.\n\n\
                Answer shape depends on the question:\n\
                - If the question has genuine alternatives (a design choice, a \"should we X or Y\"), \
                enumerate 2-3 viable options and recommend one, with reasoning grounded in the code.\n\
                - If the question is boolean or factual (\"is this thread-safe?\", \"does X handle Y?\"), \
                answer directly with evidence. Do not invent options where none exist.\n\n\
                Options schema when applicable:\n\
                "
                .to_string()
                    + OPTIONS_SCHEMA
                    + "\n\nExplore the codebase as needed to give an accurate, well-grounded answer to the \
                user message.\n\n\
                For direct answers, give a clear answer grounded in code, then flag any meaningful caveats."
            }
        }
    }

    pub fn initial_message(&self, user_prompt: &str) -> String {
        let mut msg = String::new();
        if !user_prompt.trim().is_empty() {
            match self {
                TaskMode::Review(_) => {
                    msg.push_str(&format!("Focus your review on: {user_prompt}\n\n"))
                }
                TaskMode::Ask => msg.push_str(&format!("Question to answer: {user_prompt}\n\n")),
            }
        }
        msg
    }

    pub fn reduce_prompt(&self, task: &str, combined: &str) -> String {
        let inputs = match self {
            TaskMode::Review(_) => "Individual reviews to synthesize",
            TaskMode::Ask => "Individual answers to synthesize",
        };
        match task.trim().is_empty() {
            true => format!("{inputs}:\n\n{combined}"),
            false => {
                format!("Original task given to each agent:\n{task}\n\n{inputs}:\n\n{combined}")
            }
        }
    }

    pub fn aggregator_preamble(&self) -> String {
        match self {
            TaskMode::Review(scope) => {
                format!(
                    "You synthesize code reviews into a final structured list of findings.\
                    Output only actionable \
                    findings in the schema. \
                    No reviewer attribution, no praise{no_landed_fixes}, no rejected-false-positive section.\n\n\
                    Rules:\n\
                    1. Drop {drop_clause} — \
                    these are synthesis errors in the inputs, not findings.\n\
                    2. Drop items whose triggering scenario is implausible or needs an improbable chain of conditions.\n\
                    3. Drop items not substantiated by evidence in the reviews, or that reviewers disagreed on \
                    without the disagreement being resolved by evidence.\n\
                    4. Group duplicates and closely related points into a single finding.\n\
                    5. Preserve concrete technical detail: file/line references, trigger, fix direction.\n\
                    6. Use this schema exactly (one block per finding, blank line between blocks):\n\
                    {FINDING_FIELDS}\n\n\
                    7. If no findings survive, output exactly: {NO_FINDINGS}",
                    no_landed_fixes = scope.no_landed_fixes_clause(),
                    drop_clause = scope.synthesis_drop_clause(),
                )
            }
            TaskMode::Ask => {
                "You synthesize multiple expert answers into a single response. Use Options + \
                Recommendation + Caveats when the question has genuine alternatives; give a direct, \
                evidence-grounded answer when it does not; write a detailed implementation plan if user asked for it.\n\n\
                Rules:\n\
                1. If the question had genuine alternatives, output Options + Recommendation + Caveats. \
                Merge options across answers, deduplicate, preserve meaningful alternatives even if only \
                one reviewer raised them. For the recommendation, pick what the best-grounded reasoning \
                supports; if there is no convergence, say \"No consensus\" and briefly explain the split.\n\
                2. If the question is boolean or factual, give a direct answer grounded in evidence, \
                noting any meaningful disagreement among reviewers.\n\
                3. Drop claims not grounded in the code or the original answers.\n\
                4. When outputting options, use this schema exactly:\n\
                "
                .to_string()
                    + OPTIONS_SCHEMA_WITH_NO_CONSENSUS
            }
        }
    }
}

pub enum DebateMode {
    Topic,
    Review(ReviewScope),
}

impl DebateMode {
    pub fn actor_role(&self) -> &'static str {
        match self {
            DebateMode::Topic => "Actor",
            DebateMode::Review(_) => "Reviewer",
        }
    }

    pub fn critic_role(&self) -> &'static str {
        match self {
            DebateMode::Topic => "Critic",
            DebateMode::Review(_) => "Validator",
        }
    }

    pub(crate) fn actor_system(&self) -> String {
        match self {
            DebateMode::Topic => {
                "You are the ACTOR in a structured debate. Answer the question in the shape it deserves:\n\
                - Genuine alternatives: enumerate 2-3 viable options, recommend one with reasoning \
                grounded in the code. Don't invent options where none exist.\n\
                - Boolean or factual: answer directly with evidence.\n\n\
                You are the recall stage. Include borderline options or considerations and mark \
                uncertainty. When the critic refutes the recommendation or an option with code-based \
                evidence, update — switch recommendations or acknowledge no clear winner. Do not \
                defend bad positions out of stubbornness. When the critic is wrong, hold the line \
                with specific file/line evidence.\n\n\
                Use the available tools to explore the repository to support your answer. When ready, \
                call submit_verdict(verdict, agree=false) with your position. For uncertain claims, \
                include an Uncertainty: line naming what you're unsure about and what would resolve it.\n\n"
                    .to_string()
                    + DELEGATION_GUIDANCE
                    + "\n\n"
                    + VERIFY_WARNING
            }
            DebateMode::Review(scope) => {
                format!(
                    "You are a thorough code reviewer. Find genuine issues — bugs, security flaws, \
                    performance problems, unclear logic — in the {target}. Use the available \
                    tools to read the code and understand context.\n\n\
                    You are the recall stage. Err toward inclusion: if you are moderately confident \
                    something is wrong but the trigger is narrow or you're unsure, include the finding \
                    and state your uncertainty. Reserve outright dropping for findings you yourself \
                    estimate below ~30% likely to be real. False negatives at this stage don't recover; \
                    false positives get filtered by the critic.\n\n\
                    In follow-up turns, treat the critic's challenges as evidence. When they refute a \
                    finding with code-based reasoning, drop it — do not defend bad findings out of \
                    stubbornness. When they miss something or misread the code, hold the line with \
                    specific file/line evidence. Cite concrete paths and line numbers whenever the tools \
                    provide them.\n\n\
                    Your output is a structured list of issues, not a narrative. Strict rules:\n\
                    {scope_rule}\
                    - No praise, validation, or positive notes.\n\
                    - Skip nitpicks and pure style.\n\n\
                    Call submit_verdict with a list of findings. Use this schema exactly (one block per finding, \
                    blank line between blocks):\n\
                    {FINDING_FIELDS}\n\n\
                    If there are no valid findings, set verdict exactly to: {NO_FINDINGS}\n\n\
                    {DELEGATION_GUIDANCE}\n\n\
                    {VERIFY_WARNING}",
                    target = scope.target_noun(),
                    scope_rule = scope.finding_scope_rule(),
                )
            }
        }
    }

    pub(crate) fn critic_system(&self) -> String {
        match self {
            DebateMode::Topic => {
                "You are the CRITIC in a structured debate. You are the precision filter — err toward \
                challenging weak claims. The actor is biased toward recall, so expect options or claims \
                that don't hold up under scrutiny.\n\n\
                For each option the actor raised (the recommendation AND any non-trivial alternative), \
                check independently:\n\
                1. Is it grounded in the code and supported by evidence?\n\
                2. Do the stated drawbacks or \"fits when\" conditions reflect reality?\n\
                3. Is there a better option the actor missed?\n\
                If the actor flagged uncertainty, investigate exactly what they flagged and resolve it.\n\n\
                If the question is boolean or factual (no options structure), verify the direct answer \
                against the code.\n\n\
                Before you can agree, you must have raised at least one substantive challenge and \
                verified that the actor addressed it with code evidence. Agreeing without your own \
                investigation is a failure of your role. Only call submit_verdict(agree=true) when \
                the recommendation and any alternatives still on the table are substantiated. \
                Otherwise call submit_verdict(agree=false) with a specific, evidence-based critique.\n\n"
                    .to_string()
                    + DELEGATION_GUIDANCE
                    + "\n\n"
                    + VERIFY_WARNING
            }
            DebateMode::Review(scope) => {
                format!(
                    "You are a senior engineer stress-testing a code review. You are the precision filter — \
                    err toward rejection. A false positive reaching the final result is worse than a marginal \
                    finding getting rejected. The reviewer is biased toward recall, so expect weak or \
                    uncertain findings; your job is to read the code and cut them.\n\n\
                    For each finding, check in order:\n\
                    {reality_check}\
                    2. Does the file/line actually contain the described issue? Read the code and verify.\n\
                    3. Is the triggering scenario plausible, or does it need an improbable chain of conditions? \
                    Reject if implausible.\n\
                    4. Is the potential solution concrete and actionable, not hand-wavy?\n\
                    5. If the reviewer stated an uncertainty, investigate exactly what they flagged and \
                    resolve it one way or the other — confirm or reject. Do not let findings carry lingering \
                    uncertainty into the final output.\n\n\
                    Also actively look for important issues the reviewer missed. Agreeing without reading the \
                    code is a failure of your role. For each response, do one of three things for every \
                    material claim: confirm it with evidence, dispute it with counter-evidence, or name the \
                    exact missing evidence needed to resolve it. Cite concrete paths and line numbers whenever \
                    the tools provide them. If you reject a claim, name one targeted next check that would have \
                    confirmed it if it were real. Classify each reviewed issue as confirmed or rejected, \
                    with evidence. Only call submit_verdict(agree=true) when no material factual disagreement \
                    remains, every finding is confirmed, and you have checked for missed issues. Otherwise call \
                    submit_verdict(agree=false) with specific corrections backed by line numbers.\n\n\
                    {DELEGATION_GUIDANCE}\n\n\
                    {VERIFY_WARNING}",
                    reality_check = scope.critic_reality_check(),
                )
            }
        }
    }

    pub(crate) fn meta_instruction(&self) -> &'static str {
        match self {
            DebateMode::Topic => "Debate transcript to synthesize into the final answer.",
            DebateMode::Review(_) => "Debate transcript to synthesize into the final summary.",
        }
    }

    pub(crate) fn meta_preamble(&self) -> String {
        match self {
            DebateMode::Topic => {
                "You synthesize structured debates into a single answer. Use Options + Recommendation + \
                Caveats when the question has genuine alternatives; give a direct, evidence-grounded \
                answer when it does not. Drop claims the critic refuted and any inter-role uncertainty signals.\n\n\
                Rules:\n\
                1. Include only claims that survived the debate with code-based evidence.\n\
                2. Drop options or claims the critic successfully refuted.\n\
                3. Do not include an Uncertainty field in the output — it is an inter-role signal, \
                not user-facing.\n\
                4. Preserve concrete references (file/line) where the debate cited them.\n\
                5. If the debate produced genuine alternatives, use the Options considered / Recommendation / \
                Caveats schema. If the question was boolean or factual, give a direct answer grounded in evidence, \
                noting any meaningful disagreement that survived the debate.\n\
                6. When outputting options, use this schema exactly:\n\
                "
                .to_string()
                    + OPTIONS_SCHEMA_WITH_NO_CONSENSUS
            }
            DebateMode::Review(scope) => {
                format!(
                    "You synthesize code-review debates into a final summary. Output only \
                    actionable findings sorted by priority. No attribution, no praise{no_landed_fixes}, \
                    no rejected-false-positive section.\n\n\
                    Rules:\n\
                    1. Include only issues that survived the debate and are confirmed real in the current code.\n\
                    2. Drop {drop_clause}.\n\
                    3. Drop items whose triggering scenario is implausible or needs an improbable chain of conditions.\n\
                    4. Drop items where the reviewer flagged uncertainty and the critic did not confirm them \
                    with code evidence. The final summary only contains confirmed findings.\n\
                    5. Group duplicates and closely related points into a single finding.\n\
                    6. Preserve concrete technical detail: file/line references, trigger, fix direction.\n\
                    7. Use this schema exactly (one block per finding, blank line between blocks):\n\
                    {FINDING_FIELDS}\n\n\
                    8. If no findings survive, output exactly: {NO_FINDINGS}",
                    no_landed_fixes = scope.no_landed_fixes_clause(),
                    drop_clause = scope.synthesis_drop_clause(),
                )
            }
        }
    }

    pub fn label(&self) -> &'static str {
        match self {
            DebateMode::Topic => "debate",
            DebateMode::Review(_) => "review-debate",
        }
    }
}