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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
//! Per-finding verification round (Phase 2, #583).
//!
//! Why: the reviewer LLM over-fires — calibration showed REQUEST_CHANGES/BLOCK
//! verdicts driven by speculative findings that do not survive scrutiny. A
//! second, cheaper LLM pass that confirms or refutes each candidate finding
//! cuts those false-positive blocking verdicts before they are posted. This is
//! the trusty-review port of the code-intelligence verifier protocol.
//!
//! What: `run_verification_round` selects candidate findings (per the primary
//! verdict), verifies each concurrently against the verifier model with a strict
//! CONFIRMED / REFUTED judgment, demotes REFUTED findings below the advisory
//! tier (without dropping them — the outcome is recorded on the finding), and
//! re-derives the final verdict so a BLOCK whose only blocking finding was
//! refuted relaxes correctly. `probe_verifier_liveness` is the startup gate that
//! refuses live mode when the verifier model is unavailable.
//!
//! ## Liveness gate
//! The startup liveness probe (`probe_verifier_liveness`, in `verify_liveness.rs`)
//! refuses live mode when the verifier model is dead, so a stale inference profile
//! cannot silently auto-refute every finding. See that module for the full incident
//! rationale.
//!
//! Test: `verify_tests.rs` — candidate selection, CONFIRMED/REFUTED outcomes,
//! verdict re-derivation, truncation regression (#726), and liveness-gate logic.
use Arc;
use ;
use Deserialize;
use ;
use crate::;
/// Maximum number of verifier calls to run concurrently.
///
/// Why: verifications are independent per finding, so running them concurrently
/// cuts wall-clock latency; the bound caps provider concurrency so a PR with
/// many findings does not burst the verifier model's rate limit.
/// What: `buffer_unordered(VERIFY_CONCURRENCY)` over the candidate stream.
const VERIFY_CONCURRENCY: usize = 4;
// ─── Runner seam ──────────────────────────────────────────────────────────────
/// Run the verification round if enabled and a verifier is wired, else return
/// the verdict unchanged.
///
/// Why: this is the single gating seam the runner calls so the enabled /
/// verifier-wired checks live with the rest of the verification logic instead of
/// cluttering the orchestration loop. Keeping it here also keeps `runner.rs`
/// under the 500-line cap.
/// What: when `config.verification.enabled` and a `verifier` provider is present,
/// delegates to `run_verification_round` with the resolved verifier role config;
/// otherwise logs why it was skipped and returns `verdict` unchanged (findings
/// untouched).
/// Test: runner-level `run_review_verification_*` tests; the disabled path is
/// `run_review_verification_disabled_skips_round`.
pub async
// ─── Public entry point ──────────────────────────────────────────────────────
/// Run the per-finding verification round and return the re-derived verdict.
///
/// Why: this is the single seam the runner calls between verdict parse and
/// finalisation. It mutates `findings` in place (recording each outcome and
/// demoting refuted findings) and returns the verdict re-derived from the
/// post-verification confidence distribution, so a blocking verdict whose only
/// blocking finding was refuted correctly relaxes.
/// What: selects candidates via `select_candidates`, verifies each concurrently
/// (bounded), applies the outcome (CONFIRMED keeps confidence, REFUTED demotes
/// below the advisory tier), then returns `derive_verdict(primary, findings)`.
/// When there are no candidates the findings are left untouched and the primary
/// verdict is re-derived unchanged.
/// Test: `verify_confirmed_keeps_and_block_holds`,
/// `verify_refuted_demotes_and_block_relaxes`,
/// `verify_no_candidates_is_noop`.
pub async
/// Re-derive the final verdict from the surviving (non-refuted) findings.
///
/// Why: refuted findings can no longer justify a blocking verdict; `derive_verdict`
/// treats its model_proposed as a lower bound, so always passing the original
/// BLOCK would pin the result even when every blocking finding was refuted.
///
/// Four-way baseline selection:
/// a) confirmed + at least one confirmed High-effort finding
/// → keep `primary_verdict` (grounded critical evidence, e.g. BLOCK stays BLOCK)
/// a2) confirmed, but only Medium/Low-effort findings confirmed (#1015 + #1343)
/// → CAP (ceiling) the baseline at APPROVE*: `min(primary_verdict, APPROVE*)`.
/// A lone confirmed Medium must not anchor REQUEST_CHANGES from a
/// floor-driven escalation (#1015) — BUT confirming a non-High finding must
/// ALSO never *raise* a clean APPROVE baseline to APPROVE* (#1343 runtime
/// residual). Using the severity-min of (primary, APPROVE*) is the
/// source-of-truth reconciliation that mirrors grade.rs::derive_verdict: a
/// confirmed `praise`/Low-effort finding can neither harden the verdict nor
/// downgrade the grade when the model itself said APPROVE.
/// b) clean model REFUTED, nothing confirmed
/// → drop to APPROVE baseline (escalation rested on refuted evidence)
/// c) all demotions are infra failures (TruncationRefuted/ErrorRefuted), no confirmed
/// → preserve `primary_verdict` (do not discard on verifier infra failure, #726)
///
/// `UNKNOWN` is handled by the caller and never reaches here.
/// What: filters survivors (non-refuted), selects baseline (path a2 takes the
/// severity-min of `primary_verdict` and APPROVE*), calls
/// `derive_verdict(baseline, survivors)`.
/// Test: `rederive_excludes_refuted_relaxes` (b), `rederive_keeps_confirmed_block` (a),
/// `rederive_confirmed_medium_caps_at_approve_star` (a2 — #1015),
/// `rederive_confirmed_praise_keeps_clean_approve` (a2 — #1343 runtime residual),
/// `rederive_error_refuted_preserves_primary_verdict` (c — #726),
/// `rederive_truncation_refuted_preserves_primary_verdict` (c).
/// Return the *less severe* (severity-min) of two verdicts.
///
/// Why: path (a2) of `rederive_verdict` must CAP the baseline at APPROVE* without
/// ever *raising* a clean APPROVE — confirming a Medium/Low-effort finding may relax
/// a floor-driven REQUEST_CHANGES (#1015) but must never harden an APPROVE the model
/// itself emitted (#1343 runtime residual). `derive_verdict` already takes the
/// stricter-of(model, floor) downstream, so using the severity-min here is purely a
/// ceiling on the *baseline*, not on the final verdict.
/// What: defines the ordinal APPROVE(0) < APPROVE*(1) < REQUEST_CHANGES(2) <
/// BLOCK(3) and returns whichever of `a`/`b` has the lower ordinal. `Unknown` is
/// terminal and never reaches here (the caller short-circuits it).
/// Test: `rederive_confirmed_medium_caps_at_approve_star` (REQUEST_CHANGES→APPROVE*),
/// `rederive_confirmed_praise_keeps_clean_approve` (APPROVE stays APPROVE — #1343).
// ─── Candidate selection ─────────────────────────────────────────────────────
/// Select the indices of findings to send to the verifier for a given verdict.
///
/// Why: verifying every finding is wasteful; the candidate set depends on the
/// primary verdict (#583 work item (b)). On a blocking verdict we cast a wide
/// net — any finding ≥ `VERIFY_CANDIDATE_MIN_CONFIDENCE` could be the sole reason
/// the verdict escalated, so each must be confirmed before it is allowed to
/// drive a block. On an approving verdict only the blocking-tier findings (the
/// ones that could *escalate* if confirmed) are worth the verifier's time.
/// What: returns indices into `findings`. For REQUEST_CHANGES / BLOCK: every
/// finding with `confidence >= VERIFY_CANDIDATE_MIN_CONFIDENCE` (0.50). For
/// APPROVE / APPROVE*: only findings with `confidence >= BLOCK_VERDICT_MIN_CONFIDENCE`
/// (0.90). UNKNOWN never reaches here (handled by the caller).
/// Test: `select_candidates_block_uses_wide_net`,
/// `select_candidates_approve_uses_block_tier_only`.
// ─── Single-finding verification ─────────────────────────────────────────────
/// Verifier JSON output (forced via `response_schema`).
///
/// Why: the verifier is forced to emit `{judgment, reason}`; parsing it into a
/// typed struct lets the outcome mapping be exhaustive instead of string-sniffing.
/// What: `judgment` is `"CONFIRMED"` / `"REFUTED"`; `reason` is advisory.
/// Test: covered by `verify_one` behaviour in `verify_tests.rs`.
/// Verify one finding and map the provider result to a `VerifyOutcome`.
///
/// Why: this is where the safety-critical error handling lives. A config/
/// lifecycle error (`is_alarm`) from the verifier model must NOT be silently
/// swallowed as a plain refutation — that is exactly the incident this phase
/// guards against. Such errors map to `ErrorRefuted { error_class }` AND emit
/// the `verification_model_error` signal. An unparseable/truncated response maps
/// to `TruncationRefuted` (distinct from a clean model `Refuted`) so
/// `rederive_verdict` can tell apart "the model said REFUTED" from "the provider
/// returned garbage", and preserve the model's escalation in the latter case.
/// What: calls the verifier, parses the forced JSON judgment, and returns
/// `Confirmed` / `Refuted` accordingly. On an alarm-class `LlmError`, emits the
/// signal and returns `ErrorRefuted`. On a transient error returns plain `Refuted`
/// (conservative: unverifiable via transient fault — not a structural problem).
/// On a successful call that returns unparseable output returns `TruncationRefuted`
/// (structurally distinct from a clean REFUTED judgment).
/// Test: `verify_one_confirmed`, `verify_one_refuted`,
/// `verify_one_model_unavailable_emits_signal`,
/// `verify_truncated_response_is_truncation_refuted`.
async
/// Apply a verification outcome to a finding: record it and demote if refuted.
///
/// Why: the spec (REV-606) forbids silently dropping a refuted finding — its
/// outcome must stay on the result for transparency. Demoting the confidence
/// (rather than deleting the finding) makes `derive_verdict` treat it as noise
/// while the `verified` field records *why*.
/// What: sets `finding.verified`; for any refutation variant
/// (`Refuted` / `ErrorRefuted` / `TruncationRefuted`) also clamps the confidence
/// down to `VERIFY_REFUTED_CONFIDENCE` (0.10), below every advisory / block gate.
/// `Confirmed` and `Skipped` leave the confidence untouched.
/// Test: `verify_confirmed_keeps_and_block_holds`,
/// `verify_refuted_demotes_and_block_relaxes`.
/// Parse the verifier's forced JSON judgment into `Some(true)`=CONFIRMED,
/// `Some(false)`=REFUTED, or `None` if unparseable.
///
/// Why: the verifier output is forced JSON `{judgment, reason}`; a robust parse
/// (with a keyword fallback for non-structured providers) keeps the outcome
/// deterministic.
/// What: tries direct JSON deserialisation first; falls back to a case-insensitive
/// keyword scan (CONFIRMED before REFUTED) so a provider that ignored the schema
/// still produces a decision. Returns `None` only when neither token appears.
/// Test: `parse_judgment_confirmed`, `parse_judgment_refuted`,
/// `parse_judgment_unparseable`.
// The startup liveness gate (`LivenessDecision`, `probe_verifier_liveness`)
// lives in the sibling `verify_liveness` module to keep this file under the
// 500-line cap. Re-export here so callers and the verify test module reach the
// whole verification API through one path.
pub use crate;
// ─── Signal emission (alarm hook) ────────────────────────────────────────────
/// Emit the `verification_model_error` signal.
///
/// Why: a broken verifier model is an operational incident that must be visible.
/// The signal is the stable, queryable event the alarm/metrics backend will key
/// off in Phase 7.
/// What: emits a structured `tracing::error!` with a stable `event` field and
/// the error class/model. This is the *only* sink today.
///
/// TODO(#554, Phase 7): wire this to the real metrics/alarm backend (counter +
/// alarm). Do NOT build that backend here — this phase ships only the structured
/// log signal. Until #554 lands, operators alarm on the `event="verification_model_error"`
/// log line.
/// Test: `verify_one_model_unavailable_emits_signal` (asserts the outcome, which
/// is the observable side effect; the log line itself is side-effect-only).
pub
/// Map an `LlmError` to a short, stable error-class string for the signal.
///
/// Why: the `VerifyOutcome::ErrorRefuted` variant and the signal both carry an
/// error class; deriving it in one place keeps them consistent.
/// What: returns a stable PascalCase token per alarm-class variant.
/// Test: `error_class_maps_alarm_variants`.
pub
/// Truncate a string to `max` chars for safe logging.
///
/// Why: verifier output is short, but a misbehaving provider could return a wall
/// of text; we cap it before it reaches a log line.
/// What: returns up to `max` chars, appending `…` when truncated.
/// Test: side-effect-only logging helper; covered transitively.
// ─── Unit tests ───────────────────────────────────────────────────────────────