lean-host-mcp 0.5.0

MCP server hosting Lean 4 via a supervised lean-rs-worker child
Documentation
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
//! Non-mutating proof action tools.
//!
//! `try_proof_step` and `verify_declaration` read a Lean file, send its
//! contents to the worker as an in-memory overlay, and return structured
//! proof/verification outcomes. They never write source files.

// Tool handlers consume request structs so owned strings can cross the
// worker-actor channel without extra lifetimes.
#![allow(clippy::needless_pass_by_value)]

use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::{Path, PathBuf};

use lean_rs_worker_parent::{
    LeanWorkerDeclarationVerificationBatchItem, LeanWorkerDeclarationVerificationBatchRequest,
    LeanWorkerDeclarationVerificationBatchResult, LeanWorkerDeclarationVerificationBatchRow,
    LeanWorkerDeclarationVerificationRequest,
    LeanWorkerDeclarationVerificationResult as WorkerDeclarationVerificationResult,
    LeanWorkerDeclarationVerificationTarget, LeanWorkerElabOptions, LeanWorkerOutputBudgets,
    LeanWorkerProofAttemptRequest, LeanWorkerProofCandidate, LeanWorkerProofEditTarget, LeanWorkerSorryPolicy,
};
use std::borrow::Cow;

use schemars::{JsonSchema, Schema, SchemaGenerator};
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value;

use crate::broker::ProjectHint;
use crate::diagnosis::{
    CallOutcome, IncompleteCause, NEEDS_BUILD_STATUS, WORKER_RECYCLED_STATUS, classify_missing_olean, execution_taint,
    warn_execution_taint, warn_needs_build,
};
use crate::envelope::Response;
use crate::error::{Result, ServerError};
use crate::projections::{
    DeclarationVerificationFacts, DeclarationVerificationResult, ElabFailure, ProofAttemptEnvelope, ProofAttemptResult,
    project_declaration_verification, project_proof_attempt,
};
use crate::tools::changed_coverage::{
    ChangedCoverageReport, ChangedCoverageRequest, ChangedCoverageResult, ChangedDeclaration, compute_changed_coverage,
};
use crate::tools::position::{ProofPositionSelector, worker_proof_position};
use crate::tools::source_input::{read_query_file, resolve_path, source_path_for_module};
use crate::tools::{OutputBudgetOverrides, ToolContext, session_imports};
use crate::trust::{ArtifactTrust, ArtifactTrustDeduper, display_path};

const MAX_CANDIDATES: usize = 16;
const MAX_VERIFY_TARGETS: usize = 1000;
const DEFAULT_FIELD_BYTES: u32 = 4 * 1024;
const MIN_FIELD_BYTES: u32 = 256;
const MAX_FIELD_BYTES: u32 = 64 * 1024;
const DEFAULT_TOTAL_BYTES: u32 = 64 * 1024;
const MIN_TOTAL_BYTES: u32 = 1024;
const MAX_TOTAL_BYTES: u32 = 64 * 1024;

#[derive(Debug, Clone, Deserialize, JsonSchema)]
pub struct TryProofStepRequest {
    /// Path to a `.lean` file; relative paths resolve against the project root.
    pub file: PathBuf,
    /// Declaration to target within `file`.
    pub declaration: String,
    /// Where in the proof to act; defaults to the pristine entry goal (the
    /// snippet is spliced before the first tactic). See [`ProofPositionSelector`].
    #[serde(default)]
    pub proof_position: ProofPositionSelector,
    /// Project-root override; defaults to the server's configured Lake project.
    #[serde(default)]
    pub project: Option<String>,
    /// Proof text to attempt at the position. Use `snippets` to try several.
    #[serde(default)]
    pub snippet: Option<String>,
    /// Proof snippets to attempt independently at the position, in one call.
    #[serde(default)]
    pub snippets: Vec<String>,
}

#[derive(Debug, Clone, Deserialize, JsonSchema)]
pub struct VerifyDeclarationRequest {
    /// Path to a `.lean` file; relative paths resolve against the project root.
    pub file: PathBuf,
    /// Declaration to verify within `file`.
    pub declaration: String,
    /// Project-root override; defaults to the server's configured Lake project.
    #[serde(default)]
    pub project: Option<String>,
    /// Treat `sorry`/`admit` as success instead of failure.
    #[serde(default)]
    pub allow_sorry: bool,
    /// Include the axioms the proof depends on (slower).
    #[serde(default)]
    pub report_axioms: bool,
}

#[derive(Debug, Clone, Deserialize, JsonSchema)]
pub struct LeanVerifyRequest {
    /// Explicit, file-wide, or module-wide declaration groups to verify.
    pub targets: Vec<LeanVerifyTargetGroup>,
    /// Project-root override; defaults to the server's configured Lake project.
    #[serde(default)]
    pub project: Option<String>,
    /// Treat `sorry`/`admit` as success instead of failure.
    #[serde(default)]
    pub allow_sorry: bool,
    /// Include the axioms each proof depends on (slower).
    #[serde(default)]
    pub report_axioms: bool,
    /// Verification row verbosity. `compact` omits repeated target/candidate
    /// span blocks; `full` preserves them.
    #[serde(default)]
    pub detail: LeanVerifyDetail,
}

#[derive(Debug, Clone, Copy, Default, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum LeanVerifyDetail {
    #[default]
    Compact,
    Full,
}

#[derive(Debug, Clone)]
pub struct LeanVerifyToolRequest(Value);

impl LeanVerifyToolRequest {
    pub fn into_inner(self) -> Value {
        self.0
    }
}

impl<'de> Deserialize<'de> for LeanVerifyToolRequest {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Value::deserialize(deserializer).map(Self)
    }
}

impl JsonSchema for LeanVerifyToolRequest {
    fn schema_name() -> Cow<'static, str> {
        Cow::Borrowed("LeanVerifyRequest")
    }

    fn json_schema(generator: &mut SchemaGenerator) -> Schema {
        LeanVerifyRequest::json_schema(generator)
    }
}

impl From<VerifyDeclarationRequest> for LeanVerifyRequest {
    fn from(req: VerifyDeclarationRequest) -> Self {
        Self {
            targets: vec![LeanVerifyTargetGroup::Explicit {
                file: req.file,
                declarations: vec![req.declaration],
            }],
            project: req.project,
            allow_sorry: req.allow_sorry,
            report_axioms: req.report_axioms,
            detail: LeanVerifyDetail::Compact,
        }
    }
}

#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum LeanVerifyTargetGroup {
    Explicit {
        file: PathBuf,
        declarations: Vec<String>,
    },
    FileAll {
        file: PathBuf,
    },
    ModuleAll {
        module: String,
    },
    Changed {
        #[serde(default)]
        base: Option<String>,
        #[serde(default)]
        files: Vec<PathBuf>,
        #[serde(default)]
        include_untracked: bool,
    },
}

#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct LeanVerifyResult {
    pub summary: LeanVerifySummary,
    pub results: Vec<LeanVerifyRow>,
    #[serde(skip_serializing_if = "ChangedCoverageReport::is_empty")]
    pub coverage: ChangedCoverageReport,
}

#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct LeanVerifySummary {
    pub requested: usize,
    pub verified: usize,
    pub failed: usize,
    pub needs_build: usize,
    pub unknown_coverage: usize,
    pub truncated: bool,
}

#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct LeanVerifyRow {
    pub id: String,
    pub file: String,
    pub declaration: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    pub verification_status: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub facts: Option<Box<DeclarationVerificationFacts>>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub missing_imports: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub diagnostics: Option<ElabFailure>,
}

/// Try one or more proof snippets against an in-memory source overlay.
///
/// # Errors
///
/// Returns infrastructure failures only. Failed proof candidates and
/// unsupported worker shims are normal result statuses.
pub async fn try_proof_step(ctx: &ToolContext, req: TryProofStepRequest) -> Result<Response<ProofAttemptResult>> {
    let hint = ProjectHint::from_request(req.project.clone());
    let meta = ctx.broker.resolve_meta(&hint)?;
    let input = read_query_file(&meta.canonical_root, &req.file)?;
    let source_fact = ArtifactTrust::source_file_edit_fresh(&meta.canonical_root, &input.resolved);
    let file_label = input.resolved.to_string_lossy().into_owned();
    let budgets = proof_action_budgets(&ctx.config.output);
    let candidates = proof_candidates(&req);
    let requested_count = candidates.len();

    if candidates.is_empty() {
        let runtime = ctx
            .broker
            .project_identity_without_worker(&hint, input.imports.clone())?;
        return Ok(Response::ok(
            ProofAttemptResult::Ok {
                result: empty_proof_attempt_envelope(),
                imports: input.imports,
            },
            runtime.freshness,
        )
        .with_runtime(runtime.runtime)
        .with_trust_artifact(source_fact)
        .warn("try_proof_step requires `snippet` or `snippets`"));
    }

    let imports = input.imports;
    let request = LeanWorkerProofAttemptRequest {
        source: input.source,
        edit: LeanWorkerProofEditTarget::Declaration {
            name: req.declaration.clone(),
            position: worker_proof_position(req.proof_position.clone()),
        },
        candidates,
        budgets,
    };
    // A missing-`.olean` in the target's own import closure means the worker
    // could not assemble the environment to attempt anything; degrade to the
    // shared needs_build verdict instead of letting the raw error propagate.
    let call = match classify_missing_olean(
        ctx.broker
            .attempt_proof(
                hint.clone(),
                session_imports(imports.clone()),
                imports.clone(),
                request,
                elab_options(&file_label, ctx.config.output.heartbeat_limit),
            )
            .await,
    )? {
        CallOutcome::Ready(call) => call,
        CallOutcome::NeedsBuild(err) => return proof_step_needs_build_response(ctx, hint, imports, source_fact, err),
    };
    let taint = execution_taint(&call.runtime).cloned();
    let mut response = Response::ok(
        refresh_proof_attempt_summary(project_proof_attempt(call.value), requested_count),
        call.freshness,
    )
    .with_runtime(call.runtime);
    response.trust_artifacts.push(source_fact);
    response
        .next_actions
        .push("source file was not modified; apply the chosen snippet manually if desired".to_owned());
    // If the attempt ran against imports the worker could not load, the
    // candidate diagnostics describe a degraded environment; tell the agent.
    let missing = match response.result_ref() {
        Some(ProofAttemptResult::MissingImports { missing, .. }) => Some(missing.clone()),
        _ => None,
    };
    if let Some(missing) = missing {
        response = warn_needs_build(response, &IncompleteCause::MissingImports(missing));
    }
    // A recycle mid-attempt can turn a closing tactic into a spurious `failed`;
    // there is no single verdict to relabel, so flag the whole attempt.
    if let Some(event) = &taint {
        response = warn_execution_taint(response, event);
    }
    warn_partial_proof_attempt(&mut response);
    // A from-scratch tactic block submitted to an explicit `index` / `after_text`
    // position can fail because the binders it re-introduces are already in scope
    // from earlier tactics. The default targets the pristine entry goal, so this
    // never bites there; for explicit positions, point the agent back at the
    // entry/default or at continuing from this position's `goals_after`.
    if attempt_reintroduces_bound_binders(&response) {
        response.warnings.push(
            "a candidate failed to introduce binders that are already in scope at this position; \
             a from-scratch tactic block belongs at the pristine entry goal, not after earlier tactics have run"
                .to_owned(),
        );
        response.next_actions.push(
            "omit `proof_position` (or use the default) to start from the pristine entry goal, \
             or continue this candidate from the position's `goals_after`"
                .to_owned(),
        );
    }
    Ok(response)
}

/// Lean diagnostics for a tactic that tried to introduce binders no longer
/// available — the signature of a from-scratch block run *after* earlier
/// tactics already introduced those binders, rather than at the entry goal.
fn diagnostics_reintroduce_binders(diagnostics: &ElabFailure) -> bool {
    diagnostics.diagnostics.iter().any(|diagnostic| {
        let message = &diagnostic.message;
        // `introN` is the binder-introduction primitive `intro` lowers to; the
        // phrasings vary across Lean versions ("no additional binders or `let`
        // bindings in the goal to introduce", "insufficient number of binders").
        message.contains("introN")
            || message.contains("no additional binders")
            || message.contains("no binders to introduce")
            || message.contains("insufficient number of binders")
    })
}

/// True when some failed candidate carries a binder-reintroduction diagnostic.
/// Read-only over the built response, so it never disturbs the result payload.
fn attempt_reintroduces_bound_binders(response: &Response<ProofAttemptResult>) -> bool {
    let Some(ProofAttemptResult::Ok { result, .. } | ProofAttemptResult::MissingImports { result, .. }) =
        response.result_ref()
    else {
        return false;
    };
    result
        .candidates
        .iter()
        .any(|candidate| candidate.status == "failed" && diagnostics_reintroduce_binders(&candidate.diagnostics))
}

/// Build the degraded envelope when `try_proof_step`'s target import closure
/// hit an unbuilt `.olean`: no candidate could run against an incomplete
/// environment. Mirrors the verify degrade — a `missing_imports` result plus
/// the canonical `needs_build` warning naming the blocking olean.
fn proof_step_needs_build_response(
    ctx: &ToolContext,
    hint: ProjectHint,
    imports: Vec<String>,
    source_fact: ArtifactTrust,
    err: ServerError,
) -> Result<Response<ProofAttemptResult>> {
    let base = ctx.broker.project_identity_without_worker(&hint, imports.clone())?;
    let mut response = Response::ok(needs_build_attempt_result(imports), base.freshness)
        .with_runtime(base.runtime)
        .with_trust_artifact(source_fact);
    response
        .next_actions
        .push("source file was not modified; apply the chosen snippet manually if desired".to_owned());
    Ok(warn_needs_build(
        response,
        &IncompleteCause::MissingOlean(err.to_string()),
    ))
}

/// The proof-attempt result for an unbuilt-dependency degrade: an empty
/// `missing_imports` envelope (nothing ran). Pure, for unit testing.
fn needs_build_attempt_result(imports: Vec<String>) -> ProofAttemptResult {
    ProofAttemptResult::MissingImports {
        result: empty_proof_attempt_envelope(),
        imports,
        missing: Vec::new(),
    }
}

/// Verify one declaration in an in-memory source snapshot.
///
/// # Errors
///
/// Returns infrastructure failures only. Policy failures, missing
/// declarations, and unsupported worker shims are normal result statuses.
pub async fn verify_declaration(
    ctx: &ToolContext,
    req: VerifyDeclarationRequest,
) -> Result<Response<DeclarationVerificationResult>> {
    let hint = ProjectHint::from_request(req.project.clone());
    let meta = ctx.broker.resolve_meta(&hint)?;
    let input = read_query_file(&meta.canonical_root, &req.file)?;
    let source_fact = ArtifactTrust::source_file_edit_fresh(&meta.canonical_root, &input.resolved);
    let file_label = input.resolved.to_string_lossy().into_owned();
    let budgets = proof_action_budgets(&ctx.config.output);
    if req.declaration.trim().is_empty() {
        let runtime = ctx
            .broker
            .project_identity_without_worker(&hint, input.imports.clone())?;
        return Ok(
            Response::ok(DeclarationVerificationResult::Unsupported, runtime.freshness)
                .with_runtime(runtime.runtime)
                .with_trust_artifact(source_fact)
                .warn("verify_declaration requires `declaration`"),
        );
    }
    let target = LeanWorkerDeclarationVerificationTarget::Name {
        name: req.declaration.clone(),
    };

    let request = LeanWorkerDeclarationVerificationRequest {
        source: input.source,
        target,
        sorry_policy: if req.allow_sorry {
            LeanWorkerSorryPolicy::Allow
        } else {
            LeanWorkerSorryPolicy::Deny
        },
        report_axioms: req.report_axioms,
        budgets,
    };
    let imports = input.imports;
    // A missing-`.olean` in the target's own import closure means the worker
    // could not assemble the environment to check anything; degrade to the
    // shared needs_build verdict instead of letting the raw error propagate.
    let call = match classify_missing_olean(
        ctx.broker
            .verify_declaration(
                hint.clone(),
                session_imports(imports.clone()),
                imports.clone(),
                request,
                elab_options(&file_label, ctx.config.output.heartbeat_limit),
            )
            .await,
    )? {
        CallOutcome::Ready(call) => call,
        CallOutcome::NeedsBuild(err) => return verification_needs_build_response(ctx, hint, imports, source_fact, err),
    };
    // If the worker was recycled/crashed mid-call, a non-positive verdict is a
    // likely casualty of the recycle, not a real result; relabel it honestly
    // before it reaches the agent (verification is monotone, so a `verified`
    // verdict is left trustworthy even under duress).
    let taint = execution_taint(&call.runtime).cloned();
    let mut result = project_declaration_verification(call.value);
    let recycled = taint.is_some() && relabel_recycled_verdict(&mut result);
    if recycled && let Some(event) = taint.as_ref() {
        tracing::debug!(
            cause = %event.cause,
            "relabeled verification verdict to worker_recycled (execution taint)"
        );
    }
    let mut response = Response::ok(result, call.freshness).with_runtime(call.runtime);
    response.trust_artifacts.push(source_fact);
    response
        .next_actions
        .push("source file was not modified by verification".to_owned());
    // Honest diagnostics: route the verdict's resolution health (needs_build
    // vs genuine ambiguity) through the shared renderer, and flag when the
    // axiom walk could not run.
    let (cause, candidates, axiom_warning) = match response.result_ref() {
        Some(result) => (
            verification_incomplete_cause(result),
            verification_ambiguous_candidates(result),
            axiom_unavailable_warning(result, req.report_axioms),
        ),
        None => (None, Vec::new(), None),
    };
    if let Some(cause) = cause {
        response = warn_needs_build(response, &cause);
    }
    response = crate::diagnosis::warn_ambiguous(response, &candidates);
    if let Some(warning) = axiom_warning {
        response = response.warn(warning);
    }
    if let Some(event) = taint.as_ref().filter(|_| recycled) {
        response = warn_execution_taint(response, event);
    }
    Ok(response)
}

/// Verify explicit, file-wide, or module-wide declaration groups.
///
/// # Errors
///
/// Returns infrastructure failures only. Per-declaration Lean failures are
/// projected into row verdicts.
pub async fn verify_targets(ctx: &ToolContext, req: LeanVerifyRequest) -> Result<Response<LeanVerifyResult>> {
    let hint = ProjectHint::from_request(req.project.clone());
    let meta = ctx.broker.resolve_meta(&hint)?;
    let mut expansion = VerifyExpansion::new(meta.canonical_root.clone());

    for (group_index, target_group) in req.targets.iter().enumerate() {
        match target_group {
            LeanVerifyTargetGroup::Explicit { file, declarations } => {
                expansion.push_explicit_group(group_index, file, declarations);
            }
            LeanVerifyTargetGroup::FileAll { file } => {
                let inventory = crate::tools::declaration_inventory::declaration_inventory(
                    ctx,
                    crate::tools::declaration_inventory::DeclarationInventoryRequest {
                        target: crate::tools::declaration_inventory::DeclarationInventoryTarget::File {
                            path: file.clone(),
                        },
                        project: req.project.clone(),
                        limit: Some(MAX_VERIFY_TARGETS),
                    },
                )
                .await?;
                expansion.absorb_inventory_response(&inventory);
                if let Some(result) = inventory.result_ref() {
                    expansion.truncated |= result.truncated;
                    if result.status == "ok" || result.status == NEEDS_BUILD_STATUS {
                        expansion.push_inventory_group(
                            group_index,
                            VerifySource::File(file.clone()),
                            &result.declarations,
                        );
                    } else if let Some(message) = &result.message {
                        expansion
                            .warnings
                            .push(format!("file_all inventory did not produce declarations: {message}"));
                    }
                }
            }
            LeanVerifyTargetGroup::ModuleAll { module } => {
                let inventory = crate::tools::declaration_inventory::declaration_inventory(
                    ctx,
                    crate::tools::declaration_inventory::DeclarationInventoryRequest {
                        target: crate::tools::declaration_inventory::DeclarationInventoryTarget::Module {
                            module: module.clone(),
                        },
                        project: req.project.clone(),
                        limit: Some(MAX_VERIFY_TARGETS),
                    },
                )
                .await?;
                expansion.absorb_inventory_response(&inventory);
                if let Some(result) = inventory.result_ref() {
                    expansion.truncated |= result.truncated;
                    if result.status == "ok" || result.status == NEEDS_BUILD_STATUS {
                        let source = if result.source == "ilean" {
                            VerifySource::ModuleIndex {
                                module: module.clone(),
                                display_file: source_path_for_module(&meta.canonical_root, module),
                            }
                        } else {
                            VerifySource::File(source_path_for_module(&meta.canonical_root, module))
                        };
                        expansion.push_inventory_group(group_index, source, &result.declarations);
                    } else if let Some(message) = &result.message {
                        expansion
                            .warnings
                            .push(format!("module_all inventory did not produce declarations: {message}"));
                    }
                }
            }
            LeanVerifyTargetGroup::Changed {
                base,
                files,
                include_untracked,
            } => {
                let coverage = compute_changed_coverage(
                    ctx,
                    hint.clone(),
                    &meta.canonical_root,
                    ChangedCoverageRequest {
                        base: base.clone(),
                        files: files.clone(),
                        include_untracked: *include_untracked,
                        project: req.project.clone(),
                    },
                )
                .await?;
                expansion.absorb_changed_coverage(&coverage);
                if let Some(result) = coverage.result_ref() {
                    expansion.coverage.extend(result.coverage.clone());
                    expansion.truncated |= result.coverage.truncated;
                    expansion.push_changed_group(group_index, &result.known);
                }
            }
        }
    }

    let requested = expansion.requested;
    if expansion.groups_total_targets() > MAX_VERIFY_TARGETS {
        expansion.truncated = true;
        expansion.truncate(MAX_VERIFY_TARGETS);
    }

    let mut rows = Vec::new();
    let mut last_identity = None;
    let mut build_causes = Vec::new();
    let mut ambiguous = Vec::new();
    let mut axiom_warnings = Vec::new();
    let mut recycled = None;

    let order_by_id = expansion.order_map();
    for group in std::mem::take(&mut expansion.groups) {
        if group.targets.is_empty() {
            continue;
        }
        let prepared = prepare_verify_group(&meta.canonical_root, group)?;
        let source_fact = prepared.source_fact.clone();
        let target_meta = prepared
            .targets
            .iter()
            .map(|target| (target.id.clone(), target.clone()))
            .collect::<HashMap<_, _>>();
        let request = LeanWorkerDeclarationVerificationBatchRequest {
            source: prepared.source,
            targets: prepared
                .targets
                .iter()
                .map(|target| LeanWorkerDeclarationVerificationBatchItem {
                    id: target.id.clone(),
                    target: LeanWorkerDeclarationVerificationTarget::Name {
                        name: target.declaration.clone(),
                    },
                })
                .collect(),
            sorry_policy: if req.allow_sorry {
                LeanWorkerSorryPolicy::Allow
            } else {
                LeanWorkerSorryPolicy::Deny
            },
            report_axioms: req.report_axioms,
            budgets: proof_action_budgets(&ctx.config.output),
        };
        let file_label = prepared.file_label.clone();
        let call = match classify_missing_olean(
            ctx.broker
                .verify_declaration_batch(
                    hint.clone(),
                    session_imports(prepared.imports.clone()),
                    prepared.imports.clone(),
                    request,
                    elab_options(&file_label, ctx.config.output.heartbeat_limit),
                )
                .await,
        )? {
            CallOutcome::Ready(call) => call,
            CallOutcome::NeedsBuild(err) => {
                let base = ctx
                    .broker
                    .project_identity_without_worker(&hint, prepared.imports.clone())?;
                last_identity = Some((base.freshness, base.runtime));
                build_causes.push(IncompleteCause::MissingOlean(err.to_string()));
                rows.extend(prepared.targets.into_iter().map(needs_build_row));
                if let Some(fact) = source_fact {
                    expansion.trust_artifacts.push(fact);
                }
                continue;
            }
        };
        let taint = execution_taint(&call.runtime).cloned();
        last_identity = Some((call.freshness.clone(), call.runtime.clone()));
        if let Some(fact) = source_fact {
            expansion.trust_artifacts.push(fact);
        }
        let projected = project_batch_rows(call.value, &target_meta, req.report_axioms, req.detail, taint.as_ref());
        if projected.recycled
            && let Some(event) = taint
        {
            recycled = Some(event);
        }
        build_causes.extend(projected.build_causes);
        ambiguous.extend(projected.ambiguous);
        axiom_warnings.extend(projected.axiom_warnings);
        rows.extend(projected.rows);
    }

    rows.sort_by_key(|row| order_by_id.get(&row.id).copied().unwrap_or(usize::MAX));
    let summary = summarize_rows(requested, expansion.truncated, expansion.coverage.unknown.len(), &rows);
    let (freshness, runtime) = match last_identity {
        Some(identity) => identity,
        None => {
            let base = ctx.broker.project_identity_without_worker(&hint, Vec::new())?;
            (base.freshness, base.runtime)
        }
    };
    let mut response = Response::ok(
        LeanVerifyResult {
            summary,
            results: rows,
            coverage: expansion.coverage,
        },
        freshness,
    )
    .with_runtime(runtime)
    .with_trust_artifacts(expansion.trust_artifacts.into_vec());
    response.warnings.extend(expansion.warnings);
    response.next_actions.extend(expansion.next_actions);
    if req.targets.is_empty() {
        response = response
            .warn("lean_verify received no target groups; no declarations were checked")
            .hint("Provide at least one target group, for example `{\"kind\":\"explicit\",\"file\":\"...\",\"declarations\":[\"...\"]}`.");
    }
    response
        .next_actions
        .push("source files were not modified by verification".to_owned());
    for cause in build_causes {
        response = warn_needs_build(response, &cause);
    }
    response = crate::diagnosis::warn_ambiguous(response, &ambiguous);
    for warning in axiom_warnings {
        if !response.warnings.contains(&warning) {
            response.warnings.push(warning);
        }
    }
    if let Some(event) = recycled.as_ref() {
        response = warn_execution_taint(response, event);
    }
    Ok(response)
}

#[derive(Debug, Clone)]
enum VerifySource {
    File(PathBuf),
    ModuleIndex { module: String, display_file: PathBuf },
}

#[derive(Debug, Clone)]
struct VerifyTarget {
    order: usize,
    id: String,
    file: String,
    declaration: String,
    reason: Option<String>,
}

#[derive(Debug, Clone)]
struct VerifyGroup {
    source: VerifySource,
    targets: Vec<VerifyTarget>,
}

struct VerifyExpansion {
    root: PathBuf,
    groups: Vec<VerifyGroup>,
    group_by_key: HashMap<String, usize>,
    seen_ids: HashSet<String>,
    requested: usize,
    next_order: usize,
    truncated: bool,
    coverage: ChangedCoverageReport,
    trust_artifacts: ArtifactTrustDeduper,
    warnings: Vec<String>,
    next_actions: Vec<String>,
}

struct VerifyDeclarationItem<'a> {
    name: &'a str,
    reason: Option<String>,
}

impl<'a> From<&'a str> for VerifyDeclarationItem<'a> {
    fn from(name: &'a str) -> Self {
        Self { name, reason: None }
    }
}

impl<'a> From<(&'a str, Option<String>)> for VerifyDeclarationItem<'a> {
    fn from((name, reason): (&'a str, Option<String>)) -> Self {
        Self { name, reason }
    }
}

impl VerifyExpansion {
    fn new(root: PathBuf) -> Self {
        Self {
            root,
            groups: Vec::new(),
            group_by_key: HashMap::new(),
            seen_ids: HashSet::new(),
            requested: 0,
            next_order: 0,
            truncated: false,
            coverage: ChangedCoverageReport::default(),
            trust_artifacts: ArtifactTrustDeduper::default(),
            warnings: Vec::new(),
            next_actions: Vec::new(),
        }
    }

    fn push_explicit_group(&mut self, group_index: usize, file: &Path, declarations: &[String]) {
        self.push_declarations(
            group_index,
            VerifySource::File(file.to_path_buf()),
            declarations.iter().map(|name| (name.as_str(), None)),
        );
    }

    fn push_inventory_group(
        &mut self,
        group_index: usize,
        source: VerifySource,
        declarations: &[crate::tools::declaration_inventory::DeclarationInventoryRow],
    ) {
        self.push_declarations(
            group_index,
            source,
            declarations.iter().map(|row| (row.name.as_str(), None)),
        );
    }

    fn push_changed_group(&mut self, group_index: usize, declarations: &[ChangedDeclaration]) {
        let mut by_file = BTreeMap::<String, Vec<(&str, Option<String>)>>::new();
        for declaration in declarations {
            by_file
                .entry(declaration.file.clone())
                .or_default()
                .push((declaration.declaration.as_str(), Some(declaration.reason.clone())));
        }
        for (file, declarations) in by_file {
            self.push_declarations(group_index, VerifySource::File(PathBuf::from(file)), declarations);
        }
    }

    fn push_declarations<'a, I>(&mut self, group_index: usize, source: VerifySource, declarations: I)
    where
        I: IntoIterator,
        I::Item: Into<VerifyDeclarationItem<'a>>,
    {
        let file = file_display(&self.root, &source);
        let key = source_key(&self.root, &source);
        let group_idx = match self.group_by_key.get(&key).copied() {
            Some(idx) => idx,
            None => {
                let idx = self.groups.len();
                self.groups.push(VerifyGroup {
                    source,
                    targets: Vec::new(),
                });
                self.group_by_key.insert(key, idx);
                idx
            }
        };
        for declaration in declarations {
            let declaration = declaration.into();
            let name = declaration.name.trim();
            if name.is_empty() {
                self.warnings
                    .push("lean_verify ignored an empty declaration target".to_owned());
                continue;
            }
            self.requested = self.requested.saturating_add(1);
            let mut id = format!("group_{}:{name}", group_index.saturating_add(1));
            if !self.seen_ids.insert(id.clone()) {
                id = format!("{id}#{}", self.next_order.saturating_add(1));
                let _ = self.seen_ids.insert(id.clone());
            }
            if let Some(group) = self.groups.get_mut(group_idx) {
                group.targets.push(VerifyTarget {
                    order: self.next_order,
                    id,
                    file: file.clone(),
                    declaration: name.to_owned(),
                    reason: declaration.reason,
                });
            }
            self.next_order = self.next_order.saturating_add(1);
        }
    }

    fn absorb_inventory_response(
        &mut self,
        response: &Response<crate::tools::declaration_inventory::DeclarationInventoryResult>,
    ) {
        self.trust_artifacts.extend(response.trust_artifacts.iter().cloned());
        self.warnings.extend(response.warnings.clone());
        self.next_actions.extend(response.next_actions.clone());
    }

    fn absorb_changed_coverage(&mut self, response: &Response<ChangedCoverageResult>) {
        self.trust_artifacts.extend(response.trust_artifacts.iter().cloned());
        self.warnings.extend(response.warnings.clone());
        self.next_actions.extend(response.next_actions.clone());
    }

    fn groups_total_targets(&self) -> usize {
        self.groups.iter().map(|group| group.targets.len()).sum()
    }

    fn truncate(&mut self, limit: usize) {
        let mut remaining = limit;
        for group in &mut self.groups {
            if remaining >= group.targets.len() {
                remaining = remaining.saturating_sub(group.targets.len());
            } else {
                group.targets.truncate(remaining);
                remaining = 0;
            }
        }
    }

    fn order_map(&self) -> HashMap<String, usize> {
        self.groups
            .iter()
            .flat_map(|group| group.targets.iter())
            .map(|target| (target.id.clone(), target.order))
            .collect()
    }
}

struct PreparedVerifyGroup {
    source: String,
    imports: Vec<String>,
    file_label: String,
    source_fact: Option<ArtifactTrust>,
    targets: Vec<VerifyTarget>,
}

fn prepare_verify_group(root: &Path, group: VerifyGroup) -> Result<PreparedVerifyGroup> {
    match group.source {
        VerifySource::File(path) => {
            let input = read_query_file(root, &path)?;
            let file_label = input.resolved.to_string_lossy().into_owned();
            Ok(PreparedVerifyGroup {
                source: input.source,
                imports: input.imports,
                file_label,
                source_fact: Some(ArtifactTrust::source_file_edit_fresh(root, &input.resolved)),
                targets: group.targets,
            })
        }
        VerifySource::ModuleIndex { module, display_file } => Ok(PreparedVerifyGroup {
            source: String::new(),
            imports: vec![module],
            file_label: display_file.to_string_lossy().into_owned(),
            source_fact: None,
            targets: group.targets,
        }),
    }
}

fn source_key(root: &Path, source: &VerifySource) -> String {
    match source {
        VerifySource::File(path) => format!("file:{}", display_path(root, &resolve_path(root, path))),
        VerifySource::ModuleIndex { module, .. } => format!("module_index:{module}"),
    }
}

fn file_display(root: &Path, source: &VerifySource) -> String {
    match source {
        VerifySource::File(path) => display_path(root, &resolve_path(root, path)),
        VerifySource::ModuleIndex { display_file, .. } => display_path(root, display_file),
    }
}

struct ProjectedBatchRows {
    rows: Vec<LeanVerifyRow>,
    build_causes: Vec<IncompleteCause>,
    ambiguous: Vec<crate::diagnosis::CompetingDecl>,
    axiom_warnings: Vec<String>,
    recycled: bool,
}

fn project_batch_rows(
    result: LeanWorkerDeclarationVerificationBatchResult,
    target_meta: &HashMap<String, VerifyTarget>,
    report_axioms: bool,
    detail: LeanVerifyDetail,
    taint: Option<&crate::envelope::RuntimeRestartEvent>,
) -> ProjectedBatchRows {
    match result {
        LeanWorkerDeclarationVerificationBatchResult::Ok { results, imports } => {
            project_batch_verdict_rows(results, imports, None, target_meta, report_axioms, detail, taint)
        }
        LeanWorkerDeclarationVerificationBatchResult::MissingImports {
            results,
            imports,
            missing,
        } => project_batch_verdict_rows(
            results,
            imports,
            Some(missing),
            target_meta,
            report_axioms,
            detail,
            taint,
        ),
        LeanWorkerDeclarationVerificationBatchResult::HeaderParseFailed { diagnostics } => {
            let diagnostics = crate::projections::project_failure(&diagnostics);
            ProjectedBatchRows {
                rows: target_meta
                    .values()
                    .map(|target| LeanVerifyRow {
                        id: target.id.clone(),
                        file: target.file.clone(),
                        declaration: target.declaration.clone(),
                        reason: target.reason.clone(),
                        verification_status: "header_parse_failed".to_owned(),
                        facts: None,
                        missing_imports: Vec::new(),
                        diagnostics: Some(diagnostics.clone()),
                    })
                    .collect(),
                build_causes: Vec::new(),
                ambiguous: Vec::new(),
                axiom_warnings: Vec::new(),
                recycled: false,
            }
        }
        LeanWorkerDeclarationVerificationBatchResult::Unsupported => ProjectedBatchRows {
            rows: target_meta
                .values()
                .map(|target| LeanVerifyRow {
                    id: target.id.clone(),
                    file: target.file.clone(),
                    declaration: target.declaration.clone(),
                    reason: target.reason.clone(),
                    verification_status: "unsupported".to_owned(),
                    facts: None,
                    missing_imports: Vec::new(),
                    diagnostics: None,
                })
                .collect(),
            build_causes: Vec::new(),
            ambiguous: Vec::new(),
            axiom_warnings: Vec::new(),
            recycled: false,
        },
        _ => ProjectedBatchRows {
            rows: target_meta
                .values()
                .map(|target| LeanVerifyRow {
                    id: target.id.clone(),
                    file: target.file.clone(),
                    declaration: target.declaration.clone(),
                    reason: target.reason.clone(),
                    verification_status: "unsupported".to_owned(),
                    facts: None,
                    missing_imports: Vec::new(),
                    diagnostics: None,
                })
                .collect(),
            build_causes: Vec::new(),
            ambiguous: Vec::new(),
            axiom_warnings: Vec::new(),
            recycled: false,
        },
    }
}

fn project_batch_verdict_rows(
    rows: Vec<LeanWorkerDeclarationVerificationBatchRow>,
    imports: Vec<String>,
    missing: Option<Vec<String>>,
    target_meta: &HashMap<String, VerifyTarget>,
    report_axioms: bool,
    detail: LeanVerifyDetail,
    taint: Option<&crate::envelope::RuntimeRestartEvent>,
) -> ProjectedBatchRows {
    let mut out = ProjectedBatchRows {
        rows: Vec::with_capacity(rows.len()),
        build_causes: Vec::new(),
        ambiguous: Vec::new(),
        axiom_warnings: Vec::new(),
        recycled: false,
    };
    if let Some(missing) = missing.as_ref() {
        out.build_causes.push(IncompleteCause::MissingImports(missing.clone()));
    }
    for row in rows {
        let Some(target) = target_meta.get(&row.id) else {
            continue;
        };
        let mut projected = match missing.clone() {
            Some(missing) => project_declaration_verification(WorkerDeclarationVerificationResult::MissingImports {
                verification_status: row.verification_status,
                facts: row.facts,
                imports: imports.clone(),
                missing,
            }),
            None => project_declaration_verification(WorkerDeclarationVerificationResult::Ok {
                verification_status: row.verification_status,
                facts: row.facts,
                imports: imports.clone(),
            }),
        };
        if taint.is_some() && relabel_recycled_verdict(&mut projected) {
            out.recycled = true;
        }
        if let Some(cause) = verification_incomplete_cause(&projected) {
            out.build_causes.push(cause);
        }
        out.ambiguous.extend(verification_ambiguous_candidates(&projected));
        if let Some(warning) = axiom_unavailable_warning(&projected, report_axioms) {
            out.axiom_warnings.push(warning);
        }
        out.rows.push(row_from_projected(target, projected, detail));
    }
    out
}

fn row_from_projected(
    target: &VerifyTarget,
    result: DeclarationVerificationResult,
    detail: LeanVerifyDetail,
) -> LeanVerifyRow {
    match result {
        DeclarationVerificationResult::Ok {
            verification_status,
            facts,
            ..
        } => LeanVerifyRow {
            id: target.id.clone(),
            file: target.file.clone(),
            declaration: target.declaration.clone(),
            reason: target.reason.clone(),
            verification_status,
            facts: Some(apply_verify_detail(facts, detail)),
            missing_imports: Vec::new(),
            diagnostics: None,
        },
        DeclarationVerificationResult::MissingImports {
            verification_status,
            facts,
            missing,
            ..
        } => LeanVerifyRow {
            id: target.id.clone(),
            file: target.file.clone(),
            declaration: target.declaration.clone(),
            reason: target.reason.clone(),
            verification_status,
            facts: Some(apply_verify_detail(facts, detail)),
            missing_imports: missing,
            diagnostics: None,
        },
        DeclarationVerificationResult::HeaderParseFailed { diagnostics } => LeanVerifyRow {
            id: target.id.clone(),
            file: target.file.clone(),
            declaration: target.declaration.clone(),
            reason: target.reason.clone(),
            verification_status: "header_parse_failed".to_owned(),
            facts: None,
            missing_imports: Vec::new(),
            diagnostics: Some(diagnostics),
        },
        DeclarationVerificationResult::Unsupported => LeanVerifyRow {
            id: target.id.clone(),
            file: target.file.clone(),
            declaration: target.declaration.clone(),
            reason: target.reason.clone(),
            verification_status: "unsupported".to_owned(),
            facts: None,
            missing_imports: Vec::new(),
            diagnostics: None,
        },
    }
}

fn apply_verify_detail(
    mut facts: Box<DeclarationVerificationFacts>,
    detail: LeanVerifyDetail,
) -> Box<DeclarationVerificationFacts> {
    if detail == LeanVerifyDetail::Compact {
        facts.target = None;
        facts.candidates.clear();
    }
    facts
}

fn needs_build_row(target: VerifyTarget) -> LeanVerifyRow {
    LeanVerifyRow {
        id: target.id,
        file: target.file,
        declaration: target.declaration,
        reason: target.reason,
        verification_status: NEEDS_BUILD_STATUS.to_owned(),
        facts: Some(Box::new(needs_build_facts())),
        missing_imports: Vec::new(),
        diagnostics: None,
    }
}

fn summarize_rows(
    requested: usize,
    truncated: bool,
    unknown_coverage: usize,
    rows: &[LeanVerifyRow],
) -> LeanVerifySummary {
    let verified = rows.iter().filter(|row| row.verification_status == "verified").count();
    let needs_build = rows
        .iter()
        .filter(|row| row.verification_status == NEEDS_BUILD_STATUS)
        .count();
    LeanVerifySummary {
        requested,
        verified,
        failed: rows.len().saturating_sub(verified).saturating_sub(needs_build),
        needs_build,
        unknown_coverage,
        truncated,
    }
}

/// When the worker was recycled mid-call, a non-positive verification verdict is
/// suspect: relabel it to `worker_recycled` with untrustworthy facts. Returns
/// `true` if it relabeled. Leaves `verified` (still trustworthy — verification
/// is monotone) and the already-honest `needs_build` / `ambiguous` verdicts
/// unchanged, and only touches the `Ok` variant — a `MissingImports` verdict's
/// honest action is `lake build`, not a recycle notice. Pure, for unit testing.
fn relabel_recycled_verdict(result: &mut DeclarationVerificationResult) -> bool {
    let DeclarationVerificationResult::Ok {
        verification_status,
        facts,
        ..
    } = result
    else {
        return false;
    };
    let status = verification_status.as_str();
    // `verified` is monotone-trustworthy; `needs_build` / `ambiguous` carry their
    // own honest verdict; and the relabel is idempotent (already `worker_recycled`).
    if status == "verified" || status == NEEDS_BUILD_STATUS || status == "ambiguous" || status == WORKER_RECYCLED_STATUS
    {
        return false;
    }
    WORKER_RECYCLED_STATUS.clone_into(verification_status);
    facts.facts_trustworthy = false;
    true
}

/// Build the degraded verdict + envelope when `verify_declaration`'s target
/// import closure hit an unbuilt `.olean`. Freshness/runtime come from the
/// non-spawning broker identity path, so only this rare arm pays for it.
fn verification_needs_build_response(
    ctx: &ToolContext,
    hint: ProjectHint,
    imports: Vec<String>,
    source_fact: ArtifactTrust,
    err: ServerError,
) -> Result<Response<DeclarationVerificationResult>> {
    let base = ctx.broker.project_identity_without_worker(&hint, imports.clone())?;
    let mut response = Response::ok(needs_build_verification_result(imports), base.freshness)
        .with_runtime(base.runtime)
        .with_trust_artifact(source_fact);
    response
        .next_actions
        .push("source file was not modified by verification".to_owned());
    Ok(warn_needs_build(
        response,
        &IncompleteCause::MissingOlean(err.to_string()),
    ))
}

/// The verification verdict for an unbuilt-dependency degrade. Same wire shape
/// as the worker-typed `needs_build` (status `missing_imports`,
/// `verification_status:"needs_build"`, `facts_trustworthy:false`) so the two
/// degrade paths are indistinguishable to a client. Pure, for unit testing.
fn needs_build_verification_result(imports: Vec<String>) -> DeclarationVerificationResult {
    DeclarationVerificationResult::MissingImports {
        verification_status: NEEDS_BUILD_STATUS.to_owned(),
        facts: Box::new(needs_build_facts()),
        imports,
        missing: Vec::new(),
    }
}

/// Untrustworthy, empty facts for a degraded verdict: nothing was checked
/// because the environment could not be assembled. `axioms_available:false`
/// reads the empty `axioms` as "not computed", not "no axioms".
fn needs_build_facts() -> DeclarationVerificationFacts {
    DeclarationVerificationFacts {
        target: None,
        diagnostics: ElabFailure {
            diagnostics: Vec::new(),
            truncated: false,
        },
        unresolved_goals: Vec::new(),
        contains_sorry: false,
        contains_admit: false,
        contains_sorry_ax: false,
        axioms: Vec::new(),
        axioms_truncated: false,
        axioms_available: false,
        output_truncated: false,
        candidates: Vec::new(),
        facts_trustworthy: false,
    }
}

/// Incomplete-build cause for a verification result, if the verdict was
/// computed against an environment that was not fully assembled.
fn verification_incomplete_cause(result: &DeclarationVerificationResult) -> Option<IncompleteCause> {
    match result {
        // The worker reports needs_build through the MissingImports outcome,
        // which names the unbuilt modules.
        DeclarationVerificationResult::MissingImports { missing, .. } => {
            Some(IncompleteCause::MissingImports(missing.clone()))
        }
        DeclarationVerificationResult::Ok {
            verification_status, ..
        } if verification_status == NEEDS_BUILD_STATUS => Some(IncompleteCause::MissingImports(Vec::new())),
        DeclarationVerificationResult::Ok { .. }
        | DeclarationVerificationResult::HeaderParseFailed { .. }
        | DeclarationVerificationResult::Unsupported => None,
    }
}

/// Competing declarations when the verdict is genuinely ambiguous, ready for
/// the shared ambiguity renderer. Empty otherwise.
fn verification_ambiguous_candidates(result: &DeclarationVerificationResult) -> Vec<crate::diagnosis::CompetingDecl> {
    let DeclarationVerificationResult::Ok {
        verification_status,
        facts,
        ..
    } = result
    else {
        return Vec::new();
    };
    if verification_status != "ambiguous" {
        return Vec::new();
    }
    facts
        .candidates
        .iter()
        .map(|c| crate::diagnosis::CompetingDecl {
            name: c.declaration_name.clone(),
            namespace: (!c.namespace_name.is_empty()).then(|| c.namespace_name.clone()),
        })
        .collect()
}

/// When `report_axioms` was requested but the worker could not compute the
/// axiom set (`axioms_available == false`), the empty `axioms` list means "not
/// computed", not "no axioms". Say so. A genuine empty set
/// (`axioms_available == true`) needs no caveat — the false-positive is defined
/// out of existence.
fn axiom_unavailable_warning(result: &DeclarationVerificationResult, report_axioms: bool) -> Option<String> {
    if !report_axioms {
        return None;
    }
    let DeclarationVerificationResult::Ok { facts, .. } = result else {
        return None;
    };
    (!facts.axioms_available).then(|| {
        "report_axioms: the axiom dependency set could not be computed (target unresolved or budget exhausted); \
         the empty `axioms` list means \"not computed\", not \"no axioms\""
            .to_owned()
    })
}

fn proof_action_budgets(output: &OutputBudgetOverrides) -> LeanWorkerOutputBudgets {
    LeanWorkerOutputBudgets {
        per_field_bytes: output
            .max_field_bytes
            .unwrap_or(DEFAULT_FIELD_BYTES)
            .clamp(MIN_FIELD_BYTES, MAX_FIELD_BYTES),
        total_bytes: output
            .max_total_bytes
            .unwrap_or(DEFAULT_TOTAL_BYTES)
            .clamp(MIN_TOTAL_BYTES, MAX_TOTAL_BYTES),
    }
}

fn elab_options(file_label: &str, heartbeat_limit: Option<u64>) -> LeanWorkerElabOptions {
    let options = LeanWorkerElabOptions::new().file_label(file_label);
    match heartbeat_limit {
        Some(limit) => options.heartbeat_limit(limit),
        None => options,
    }
}

fn proof_candidates(req: &TryProofStepRequest) -> Vec<LeanWorkerProofCandidate> {
    requested_snippets(req)
        .into_iter()
        .enumerate()
        .map(|(idx, text)| LeanWorkerProofCandidate {
            id: format!("candidate_{}", idx.saturating_add(1)),
            text,
        })
        .collect()
}

fn requested_snippets(req: &TryProofStepRequest) -> Vec<String> {
    let mut snippets = Vec::new();
    if let Some(snippet) = req.snippet.as_ref().filter(|text| !text.trim().is_empty()) {
        snippets.push(snippet.clone());
    }
    snippets.extend(req.snippets.iter().filter(|text| !text.trim().is_empty()).cloned());
    snippets
}

fn empty_proof_attempt_envelope() -> ProofAttemptEnvelope {
    let mut envelope = ProofAttemptEnvelope {
        candidates: Vec::new(),
        candidate_limit: MAX_CANDIDATES as u32,
        candidates_truncated: false,
        summary: crate::projections::ProofAttemptSummary {
            requested_candidates: 0,
            returned_candidates: 0,
            candidate_limit: MAX_CANDIDATES as u32,
            candidates_truncated: false,
            partial: false,
            closed: 0,
            progressed: 0,
            failed: 0,
            timeout: 0,
            budget_exceeded: 0,
            not_attempted: 0,
            unsupported: 0,
            output_truncated: 0,
        },
    };
    envelope.refresh_summary(0);
    envelope
}

fn refresh_proof_attempt_summary(result: ProofAttemptResult, requested_count: usize) -> ProofAttemptResult {
    match result {
        ProofAttemptResult::Ok { result, imports } => ProofAttemptResult::Ok {
            result: refresh_envelope_summary(result, requested_count),
            imports,
        },
        ProofAttemptResult::MissingImports {
            result,
            imports,
            missing,
        } => ProofAttemptResult::MissingImports {
            result: refresh_envelope_summary(result, requested_count),
            imports,
            missing,
        },
        ProofAttemptResult::HeaderParseFailed { diagnostics } => ProofAttemptResult::HeaderParseFailed { diagnostics },
        ProofAttemptResult::Unsupported => ProofAttemptResult::Unsupported,
    }
}

fn refresh_envelope_summary(mut envelope: ProofAttemptEnvelope, requested_count: usize) -> ProofAttemptEnvelope {
    envelope.refresh_summary(requested_count);
    envelope
}

fn warn_partial_proof_attempt(response: &mut Response<ProofAttemptResult>) {
    let Some(summary) = response.result_ref().and_then(proof_attempt_summary).cloned() else {
        return;
    };
    if summary.candidates_truncated {
        response.warnings.push(format!(
            "proof candidate batch was truncated at {} of {} requested snippets",
            summary.returned_candidates, summary.requested_candidates
        ));
        response
            .next_actions
            .push("submit fewer proof snippets if you need a verdict for every candidate".to_owned());
    }
    if summary.budget_exceeded > 0 || summary.not_attempted > 0 || summary.output_truncated > 0 {
        response.warnings.push(format!(
            "proof candidate batch returned partial output: budget_exceeded={}, not_attempted={}, output_truncated={}",
            summary.budget_exceeded, summary.not_attempted, summary.output_truncated
        ));
        response.next_actions.push(
            "retry promising snippets individually or raise output.max_total_bytes for a larger batch response"
                .to_owned(),
        );
    }
}

fn proof_attempt_summary(result: &ProofAttemptResult) -> Option<&crate::projections::ProofAttemptSummary> {
    match result {
        ProofAttemptResult::Ok { result, .. } | ProofAttemptResult::MissingImports { result, .. } => {
            Some(&result.summary)
        }
        ProofAttemptResult::HeaderParseFailed { .. } | ProofAttemptResult::Unsupported => None,
    }
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::unwrap_used,
        clippy::indexing_slicing,
        clippy::panic,
        reason = "unit tests should fail directly on malformed fixtures"
    )]

    use serde_json::json;

    use super::*;
    use crate::broker::{BrokerConfig, ProjectBroker};
    use crate::tools::{ToolConfig, ToolContext};
    use crate::trust::{ArtifactKind, TrustScope, TrustStatus};

    fn make_lake_dir(root: &std::path::Path) -> std::path::PathBuf {
        let dir = root.join("proof_action");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("lakefile.lean"), "package proof_action\nlean_lib Demo\n").unwrap();
        std::fs::write(dir.join("lean-toolchain"), "leanprover/lean4:v4.31.0-rc2\n").unwrap();
        std::fs::write(dir.join("lake-manifest.json"), "{}\n").unwrap();
        std::fs::write(dir.join("Demo.lean"), "import Init\nexample : True := by trivial\n").unwrap();
        dir.canonicalize().unwrap()
    }

    fn test_context(root: std::path::PathBuf) -> (ToolContext, std::sync::Arc<ProjectBroker>) {
        let broker = ProjectBroker::new(BrokerConfig {
            config_default: None,
            env_default: Some(root.clone()),
            cwd: root,
            max_projects: BrokerConfig::default_max_projects(),
            idle_timeout: std::time::Duration::ZERO,
            semantic_permits: BrokerConfig::default_semantic_permits(),
            semantic_waiters: BrokerConfig::default_semantic_waiters(),
            semantic_admission_timeout: BrokerConfig::default_semantic_admission_timeout(),
            semantic_lock_dir: BrokerConfig::default_semantic_lock_dir(),
        });
        (
            ToolContext {
                broker: std::sync::Arc::clone(&broker),
                config: ToolConfig::default(),
            },
            broker,
        )
    }

    fn assert_source_edit_fresh(response: &Response<impl serde::Serialize + JsonSchema>) {
        assert!(response.trust_artifacts.iter().any(|artifact| {
            artifact.artifact == ArtifactKind::Source
                && artifact.scope == TrustScope::File
                && artifact.status == TrustStatus::EditFresh
                && artifact.path.as_deref() == Some("Demo.lean")
        }));
    }

    #[test]
    fn try_proof_step_request_accepts_single_snippet() {
        let req: TryProofStepRequest = serde_json::from_value(json!({
            "file": "Demo.lean",
            "declaration": "Demo.closed",
            "snippet": "rfl"
        }))
        .unwrap();
        assert_eq!(requested_snippets(&req), vec!["rfl"]);
    }

    #[test]
    fn try_proof_step_request_accepts_snippet_list_for_upstream_batching() {
        let snippets = (0..20).map(|idx| format!("exact h{idx}")).collect::<Vec<_>>();
        let req = TryProofStepRequest {
            file: PathBuf::from("Demo.lean"),
            declaration: "Demo.closed".to_owned(),
            proof_position: ProofPositionSelector::Default,
            project: None,
            snippet: None,
            snippets,
        };
        let candidates = proof_candidates(&req);
        assert_eq!(candidates.len(), 20);
        assert_eq!(candidates[MAX_CANDIDATES].id, "candidate_17");
    }

    #[test]
    fn proof_step_partial_summary_counts_upstream_not_attempted_rows() {
        use crate::projections::{ProofAttemptCandidate, RenderedText};
        let candidate = |id: &str, status: &str, output_truncated: bool| ProofAttemptCandidate {
            id: id.to_owned(),
            status: status.to_owned(),
            snippet: RenderedText {
                value: "trivial".to_owned(),
                truncated: false,
            },
            diagnostics: ElabFailure {
                diagnostics: Vec::new(),
                truncated: false,
            },
            downstream_diagnostics: ElabFailure {
                diagnostics: Vec::new(),
                truncated: false,
            },
            goals: Vec::new(),
            declaration: None,
            proof_position: None,
            output_truncated,
        };
        let result = refresh_proof_attempt_summary(
            ProofAttemptResult::Ok {
                result: ProofAttemptEnvelope {
                    candidates: vec![
                        candidate("candidate_1", "closed", false),
                        candidate("candidate_2", "budget_exceeded", true),
                        candidate("candidate_3", "not_attempted", false),
                    ],
                    candidate_limit: MAX_CANDIDATES as u32,
                    candidates_truncated: false,
                    summary: empty_proof_attempt_envelope().summary,
                },
                imports: Vec::new(),
            },
            3,
        );
        let Some(summary) = proof_attempt_summary(&result) else {
            panic!("proof attempt should have a summary");
        };
        assert_eq!(summary.requested_candidates, 3);
        assert_eq!(summary.returned_candidates, 3);
        assert_eq!(summary.closed, 1);
        assert_eq!(summary.budget_exceeded, 1);
        assert_eq!(summary.not_attempted, 1);
        assert_eq!(summary.output_truncated, 1);
        assert!(summary.partial);
    }

    #[tokio::test]
    async fn try_proof_step_marks_read_source_snapshot_edit_fresh() {
        let tmp = tempfile::tempdir().unwrap();
        let root = make_lake_dir(tmp.path());
        let (ctx, broker) = test_context(root);
        let response = try_proof_step(
            &ctx,
            TryProofStepRequest {
                file: PathBuf::from("Demo.lean"),
                declaration: "Demo.example".to_owned(),
                proof_position: ProofPositionSelector::Default,
                project: None,
                snippet: None,
                snippets: Vec::new(),
            },
        )
        .await
        .unwrap();

        assert_source_edit_fresh(&response);
        assert!(broker.resident_paths().is_empty());
        drop(ctx);
        drop(broker);
    }

    #[test]
    fn binder_reintroduction_diagnostics_drive_the_cue() {
        use crate::projections::{CoordinateSpace, Diagnostic, Severity};
        let with = |message: &str| ElabFailure {
            diagnostics: vec![Diagnostic {
                severity: Severity::Error,
                message: message.to_owned(),
                coordinate_space: CoordinateSpace::Unknown,
                position: None,
                original_range: None,
                synthetic_range: None,
                file: None,
                coordinate_note: None,
            }],
            truncated: false,
        };
        // The exact message Lean 4.31 emits for this fixture, plus an older phrasing.
        assert!(diagnostics_reintroduce_binders(&with(
            "Tactic `introN` failed: There are no additional binders or `let` bindings in the goal to introduce"
        )));
        assert!(diagnostics_reintroduce_binders(&with(
            "tactic 'introN' failed, insufficient number of binders"
        )));
        assert!(!diagnostics_reintroduce_binders(&with("unknown identifier 'foo'")));
    }

    #[test]
    fn verify_declaration_request_accepts_declaration_mode() {
        let req: VerifyDeclarationRequest = serde_json::from_value(json!({
            "file": "Demo.lean",
            "declaration": "Demo.closed",
            "report_axioms": true
        }))
        .unwrap();
        assert_eq!(req.declaration, "Demo.closed");
        assert!(req.report_axioms);
    }

    #[test]
    fn lean_verify_request_accepts_target_groups() {
        let req: LeanVerifyRequest = serde_json::from_value(json!({
            "targets": [
                {
                    "kind": "explicit",
                    "file": "Demo.lean",
                    "declarations": ["Demo.closed", "Demo.other"]
                },
                { "kind": "file_all", "file": "Other.lean" },
                { "kind": "module_all", "module": "Demo.Other" }
            ],
            "allow_sorry": true,
            "report_axioms": true
        }))
        .unwrap();
        assert_eq!(req.targets.len(), 3);
        assert!(req.allow_sorry);
        assert!(req.report_axioms);
    }

    #[test]
    fn lean_verify_summary_separates_needs_build_from_failures() {
        let rows = vec![
            LeanVerifyRow {
                id: "group_1:Demo.ok".to_owned(),
                file: "Demo.lean".to_owned(),
                declaration: "Demo.ok".to_owned(),
                reason: None,
                verification_status: "verified".to_owned(),
                facts: None,
                missing_imports: Vec::new(),
                diagnostics: None,
            },
            LeanVerifyRow {
                id: "group_1:Demo.sorry".to_owned(),
                file: "Demo.lean".to_owned(),
                declaration: "Demo.sorry".to_owned(),
                reason: None,
                verification_status: "has_sorry".to_owned(),
                facts: None,
                missing_imports: Vec::new(),
                diagnostics: None,
            },
            LeanVerifyRow {
                id: "group_2:Demo.unbuilt".to_owned(),
                file: "Demo.lean".to_owned(),
                declaration: "Demo.unbuilt".to_owned(),
                reason: None,
                verification_status: NEEDS_BUILD_STATUS.to_owned(),
                facts: None,
                missing_imports: Vec::new(),
                diagnostics: None,
            },
        ];

        let summary = summarize_rows(4, true, 2, &rows);
        assert_eq!(summary.requested, 4);
        assert_eq!(summary.verified, 1);
        assert_eq!(summary.failed, 1);
        assert_eq!(summary.needs_build, 1);
        assert_eq!(summary.unknown_coverage, 2);
        assert!(summary.truncated);
    }

    #[test]
    fn lean_verify_expansion_coalesces_targets_by_source() {
        let mut expansion = VerifyExpansion::new(std::path::PathBuf::from("/tmp/project"));
        expansion.push_explicit_group(
            0,
            std::path::Path::new("Demo.lean"),
            &["Demo.a".to_owned(), "Demo.b".to_owned()],
        );
        expansion.push_explicit_group(1, std::path::Path::new("Demo.lean"), &["Demo.c".to_owned()]);

        assert_eq!(expansion.groups.len(), 1);
        assert_eq!(expansion.groups[0].targets.len(), 3);
        assert_eq!(expansion.requested, 3);
        assert_eq!(
            expansion.groups[0]
                .targets
                .iter()
                .map(|target| target.declaration.as_str())
                .collect::<Vec<_>>(),
            ["Demo.a", "Demo.b", "Demo.c"]
        );
    }

    #[tokio::test]
    async fn verify_declaration_marks_read_source_snapshot_edit_fresh() {
        let tmp = tempfile::tempdir().unwrap();
        let root = make_lake_dir(tmp.path());
        let (ctx, broker) = test_context(root);
        let response = verify_declaration(
            &ctx,
            VerifyDeclarationRequest {
                file: PathBuf::from("Demo.lean"),
                declaration: String::new(),
                project: None,
                allow_sorry: false,
                report_axioms: false,
            },
        )
        .await
        .unwrap();

        assert_source_edit_fresh(&response);
        assert!(broker.resident_paths().is_empty());
        drop(ctx);
        drop(broker);
    }

    #[tokio::test]
    async fn lean_verify_empty_targets_warns_that_nothing_was_checked() {
        let tmp = tempfile::tempdir().unwrap();
        let root = make_lake_dir(tmp.path());
        let (ctx, broker) = test_context(root);

        let response = verify_targets(
            &ctx,
            LeanVerifyRequest {
                targets: Vec::new(),
                project: None,
                allow_sorry: false,
                report_axioms: false,
                detail: LeanVerifyDetail::Compact,
            },
        )
        .await
        .unwrap();

        let result = response.result_ref().unwrap();
        assert_eq!(result.summary.requested, 0);
        assert!(result.results.is_empty());
        assert!(
            response
                .warnings
                .iter()
                .any(|warning| warning.contains("no target groups"))
        );
        assert!(
            response
                .next_actions
                .iter()
                .any(|action| action.contains("\"kind\":\"explicit\""))
        );
        assert!(broker.resident_paths().is_empty());
        drop(ctx);
        drop(broker);
    }

    #[test]
    fn proof_action_budget_clamps() {
        let low = proof_action_budgets(&OutputBudgetOverrides {
            max_field_bytes: Some(1),
            max_total_bytes: Some(1),
            heartbeat_limit: None,
        });
        assert_eq!(low.per_field_bytes, MIN_FIELD_BYTES);
        assert_eq!(low.total_bytes, MIN_TOTAL_BYTES);

        let high = proof_action_budgets(&OutputBudgetOverrides {
            max_field_bytes: Some(u32::MAX),
            max_total_bytes: Some(u32::MAX),
            heartbeat_limit: None,
        });
        assert_eq!(high.per_field_bytes, MAX_FIELD_BYTES);
        assert_eq!(high.total_bytes, MAX_TOTAL_BYTES);

        let default = proof_action_budgets(&OutputBudgetOverrides::default());
        assert_eq!(default.per_field_bytes, DEFAULT_FIELD_BYTES);
        assert_eq!(default.total_bytes, DEFAULT_TOTAL_BYTES);
    }

    #[test]
    fn unbuilt_dependency_verification_is_needs_build_with_untrustworthy_facts() {
        // The env-based degrade must match the worker-typed needs_build shape:
        // verification_status "needs_build" + facts_trustworthy false.
        let DeclarationVerificationResult::MissingImports {
            verification_status,
            facts,
            ..
        } = needs_build_verification_result(vec!["Foo.Bar".to_owned()])
        else {
            panic!("expected a missing_imports verdict");
        };
        assert_eq!(verification_status, NEEDS_BUILD_STATUS);
        assert!(!facts.facts_trustworthy);
        assert!(!facts.axioms_available);
        assert!(!facts.contains_sorry);
    }

    fn ok_verdict(status: &str, trustworthy: bool) -> DeclarationVerificationResult {
        let mut facts = needs_build_facts();
        facts.facts_trustworthy = trustworthy;
        DeclarationVerificationResult::Ok {
            verification_status: status.to_owned(),
            facts: Box::new(facts),
            imports: Vec::new(),
        }
    }

    #[test]
    fn recycled_relabels_nonpositive_ok_verdict_to_worker_recycled() {
        // A `not_found` produced while the worker was recycled is a likely
        // casualty of the recycle, not a real "name absent".
        let mut verdict = ok_verdict("not_found", true);
        assert!(relabel_recycled_verdict(&mut verdict));
        let DeclarationVerificationResult::Ok {
            verification_status,
            facts,
            ..
        } = verdict
        else {
            panic!("expected an Ok verdict");
        };
        assert_eq!(verification_status, WORKER_RECYCLED_STATUS);
        assert!(!facts.facts_trustworthy);
    }

    #[test]
    fn recycled_leaves_verified_and_already_honest_verdicts_unchanged() {
        // `verified` is monotone-trustworthy even under duress; needs_build and
        // ambiguous already carry their own honest, actionable verdict.
        for status in ["verified", NEEDS_BUILD_STATUS, "ambiguous"] {
            let mut verdict = ok_verdict(status, true);
            assert!(
                !relabel_recycled_verdict(&mut verdict),
                "{status} must not be relabeled"
            );
            let DeclarationVerificationResult::Ok {
                verification_status,
                facts,
                ..
            } = verdict
            else {
                panic!("expected an Ok verdict");
            };
            assert_eq!(verification_status, status);
            assert!(facts.facts_trustworthy);
        }
    }

    #[test]
    fn recycled_does_not_touch_missing_imports_verdict() {
        // A MissingImports verdict's honest action is `lake build`, owned by the
        // needs_build path — not a recycle notice.
        let mut verdict = needs_build_verification_result(vec!["Foo.Bar".to_owned()]);
        assert!(!relabel_recycled_verdict(&mut verdict));
    }

    #[test]
    fn unbuilt_dependency_proof_attempt_is_empty_missing_imports() {
        let ProofAttemptResult::MissingImports { result, missing, .. } =
            needs_build_attempt_result(vec!["Foo.Bar".to_owned()])
        else {
            panic!("expected a missing_imports envelope");
        };
        assert!(result.candidates.is_empty());
        assert!(missing.is_empty());
    }
}