monarch-mcp 0.4.2

Monarch Money MCP server — an agentic budgeting companion (read + categorize only)
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
//! Tool registry — registers the four compound tool names for `tools/list`.

use crate::account_inventory::compute_account_inventory;
use crate::asset_allocation::compute_asset_allocation;
use crate::budget_review::compute_budget_review;
use crate::cashflow_forecast::compute_forecast;
use crate::client::MonarchClient;
use crate::error::MonarchError;
use crate::financial_overview::compute_overview;
use crate::goals::Goals;
use crate::inspect_transactions::{blank_to_none, compute_inspection, InspectFilter};
use crate::net_worth_trend::compute_trend;
use crate::progress_vs_goals::compute_progress;
use crate::recurring_scan::compute_scan;
use crate::retirement_readiness::{
    compute_retirement_readiness, invested_financial_accounts, validate_withdrawal_rate,
    WITHDRAWAL_RATE_DEFAULT,
};
use crate::savings_rate::{compute_savings_rate, SavingsRateResult};
use crate::spending_history::{compute_spending_history, range_for_months_count, SpendingHistory};
use crate::spending_report::compute_spending_report;
use crate::spending_report::compute_true_spending;
use crate::subscription_audit::compute_subscription_audit;
use crate::triage::{
    build_category_suggestion_map, parse_raw_changes, partition_changeset, propose_changes,
    resolve_category_names,
};
use rmcp::schemars;
use rmcp::{
    handler::server::{router::tool::ToolRouter, wrapper::Parameters},
    model::*,
    service::RequestContext,
    tool, tool_router, ErrorData as McpError, RoleServer, ServerHandler,
};
use serde::Deserialize;
use serde_json::json;

/// Input parameters for the `net_worth_trend` tool.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct NetWorthTrendParams {
    /// Number of months of history to include (1–24).
    pub months: u32,
}

/// Input parameters for the `spending_history` tool.
///
/// Provide either `months` (last N complete months) or explicit
/// `start_date` / `end_date`. When both are supplied, explicit dates win.
/// When neither is supplied, defaults to 6 complete months.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct SpendingHistoryParams {
    /// Number of complete calendar months to include, ending before the
    /// current (partial) month. Defaults to 6 when omitted.
    pub months: Option<u32>,
    /// Explicit range start (ISO-8601 YYYY-MM-DD, e.g. "2025-11-01").
    /// Overrides `months` when provided.
    pub start_date: Option<String>,
    /// Explicit range end (ISO-8601 YYYY-MM-DD, e.g. "2026-04-30").
    /// Overrides `months` when provided.
    pub end_date: Option<String>,
}

/// Input parameters for the `savings_rate` tool.
///
/// Provide either `months` (last N complete months) or explicit
/// `start_date` / `end_date`. When both are supplied, explicit dates win.
/// When neither is supplied, defaults to 6 complete months.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct SavingsRateParams {
    /// Number of complete calendar months to include, ending before the
    /// current (partial) month. Defaults to 6 when omitted.
    pub months: Option<u32>,
    /// Explicit range start (ISO-8601 YYYY-MM-DD, e.g. "2025-11-01").
    /// Overrides `months` when provided.
    pub start_date: Option<String>,
    /// Explicit range end (ISO-8601 YYYY-MM-DD, e.g. "2026-04-30").
    /// Overrides `months` when provided.
    pub end_date: Option<String>,
}

/// Input parameters for the `retirement_readiness` tool.
///
/// All fields are optional. When omitted, defaults are applied:
/// - `months`: 6 complete trailing months for the spend baseline
/// - `withdrawal_rate`: 0.04 (4% rule)
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct RetirementReadinessParams {
    /// Number of complete calendar months of transaction history to use for
    /// the annualised spend baseline (default 6, max 24).
    pub months: Option<u32>,
    /// Safe-withdrawal rate as a decimal fraction (default 0.04 = 4%).
    /// Must be in [0.02, 0.10]. Out-of-range values are rejected with a
    /// clear error message.
    pub withdrawal_rate: Option<f64>,
}

/// Input parameters for the `apply_changeset` tool.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct ApplyChangesetParams {
    /// List of change entries to apply. Each entry may include id, category, tags, notes.
    /// Entries containing forbidden fields (e.g. amount) are rejected and reported.
    pub changes: Vec<serde_json::Value>,
}

/// Input parameters for the `inspect_transactions` tool.
///
/// All fields are optional. Omitting a field means "no filter on that dimension".
/// If neither `start_date` nor `end_date` is provided, the current calendar month
/// is used. To re-categorize a transaction found here, pass its `id` to
/// `apply_changeset`:
///
/// ```text
/// Step 1: inspect_transactions(category="Pets")
///   → [{id:"txn-abc", merchant:"Petco", amount:-12000.00, ...}, ...]
///
/// Step 2: apply_changeset(changes=[{id:"txn-abc", category:"Veterinary"}])
///   → applies the recategorization
/// ```
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct InspectTransactionsParams {
    /// Filter to transactions whose category name contains this substring
    /// (case-insensitive). Example: "Pets" matches "Pets", "Pet Supplies".
    pub category: Option<String>,
    /// Filter to transactions whose merchant name contains this substring
    /// (case-insensitive). Example: "Petco" matches "Petco Store #42".
    pub merchant: Option<String>,
    /// Start of the date range (ISO-8601, e.g. "2026-04-01").
    /// Defaults to the first day of the current month when omitted.
    pub start_date: Option<String>,
    /// End of the date range (ISO-8601, e.g. "2026-04-30").
    /// Defaults to the last day of the current month when omitted.
    pub end_date: Option<String>,
}

#[derive(Clone)]
pub struct MonarchTools {
    #[allow(dead_code)] // required by rmcp tool_router macro
    tool_router: ToolRouter<MonarchTools>,
}

#[tool_router]
impl MonarchTools {
    pub fn new() -> Self {
        Self {
            tool_router: Self::tool_router(),
        }
    }

    #[tool(
        description = "Return a snapshot of the household's current financial position: \
        net worth, month-over-month change, this-month cash flow (income/spending/net), \
        and balances by account type. Start every advising session here."
    )]
    async fn financial_overview(
        &self,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let base = std::env::var("MONARCH_BASE").ok().filter(|s| !s.is_empty());
        let mut client = MonarchClient::new(base);
        client.resolve_token_from_env_or_disk();

        let payload = match fetch_and_compute(&client).await {
            Ok(overview) => serde_json::to_value(&overview)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
            Err(MonarchError::SessionExpired) => {
                json!({
                    "error": "Session expired — re-authenticate by running `monarch-mcp login`"
                })
            }
            Err(e) => return Err(McpError::internal_error(e.to_string(), None)),
        };

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string(&payload)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
        )]))
    }

    #[tool(
        description = "Break down spending for a period by category, compare against \
        budget and the prior period, surface anomalies and over-budget flags."
    )]
    async fn spending_report(
        &self,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let base = std::env::var("MONARCH_BASE").ok().filter(|s| !s.is_empty());
        let mut client = MonarchClient::new(base);
        client.resolve_token_from_env_or_disk();

        let payload = match fetch_and_compute_spending(&client).await {
            Ok(report) => serde_json::to_value(&report)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
            Err(MonarchError::SessionExpired) => {
                json!({
                    "error": "Session expired — re-authenticate by running `monarch-mcp login`"
                })
            }
            Err(e) => return Err(McpError::internal_error(e.to_string(), None)),
        };

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string(&payload)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
        )]))
    }

    #[tool(
        description = "Identify uncategorized transactions and suggest category/tags/notes \
        based on the household's own history. Returns a proposed changeset for review — \
        nothing is written until apply_changeset is called."
    )]
    async fn triage_uncategorized(
        &self,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let base = std::env::var("MONARCH_BASE").ok().filter(|s| !s.is_empty());
        let mut client = MonarchClient::new(base);
        client.resolve_token_from_env_or_disk();

        let payload = match fetch_and_compute_triage(&client).await {
            Ok(result) => serde_json::to_value(&result)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
            Err(MonarchError::SessionExpired) => {
                json!({
                    "error": "Session expired — re-authenticate by running `monarch-mcp login`"
                })
            }
            Err(e) => return Err(McpError::internal_error(e.to_string(), None)),
        };

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string(&payload)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
        )]))
    }

    #[tool(
        description = "Apply an approved changeset, updating only category, tags, and notes. \
        Category values are supplied as human-readable names (e.g. \"Pets\") and are resolved \
        to Monarch category UUIDs server-side before the mutation is sent. Unknown category \
        names are rejected and reported back — they are never sent to the API. \
        Any other field (amount, account, merchant, date, or unknown fields) is also forbidden — \
        entries containing them are rejected and reported back with the original transaction id. \
        The set of transaction ids is never altered."
    )]
    async fn apply_changeset(
        &self,
        _ctx: RequestContext<RoleServer>,
        Parameters(ApplyChangesetParams { changes }): Parameters<ApplyChangesetParams>,
    ) -> Result<CallToolResult, McpError> {
        let base = std::env::var("MONARCH_BASE").ok().filter(|s| !s.is_empty());
        let mut client = MonarchClient::new(base);
        client.resolve_token_from_env_or_disk();

        let payload = match apply_approved_changeset(&client, changes).await {
            Ok(result) => serde_json::to_value(&result)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
            Err(MonarchError::SessionExpired) => {
                json!({
                    "error": "Session expired — re-authenticate by running `monarch-mcp login`"
                })
            }
            Err(e) => return Err(McpError::internal_error(e.to_string(), None)),
        };

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string(&payload)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
        )]))
    }

    #[tool(
        description = "Project the household's month-end cash position from current account \
        balances, income and spending so far this period, and scheduled recurring charges. \
        Flags a shortfall when upcoming bills are on track to exceed available funds."
    )]
    async fn cashflow_forecast(
        &self,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let base = std::env::var("MONARCH_BASE").ok().filter(|s| !s.is_empty());
        let mut client = MonarchClient::new(base);
        client.resolve_token_from_env_or_disk();

        let payload = match fetch_and_compute_forecast(&client).await {
            Ok(forecast) => serde_json::to_value(&forecast)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
            Err(MonarchError::SessionExpired) => {
                json!({
                    "error": "Session expired — re-authenticate by running `monarch-mcp login`"
                })
            }
            Err(e) => return Err(McpError::internal_error(e.to_string(), None)),
        };

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string(&payload)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
        )]))
    }

    #[tool(
        description = "Show net worth month-by-month over a requested period, broken down \
        by account type (depository, brokerage, credit, loan, etc.), with the biggest \
        single mover and a total assets-versus-liabilities split."
    )]
    async fn net_worth_trend(
        &self,
        _ctx: RequestContext<RoleServer>,
        Parameters(params): Parameters<NetWorthTrendParams>,
    ) -> Result<CallToolResult, McpError> {
        let base = std::env::var("MONARCH_BASE").ok().filter(|s| !s.is_empty());
        let mut client = MonarchClient::new(base);
        client.resolve_token_from_env_or_disk();

        let payload = match fetch_and_compute_trend(&client, params.months).await {
            Ok(trend) => serde_json::to_value(&trend)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
            Err(MonarchError::SessionExpired) => {
                json!({
                    "error": "Session expired — re-authenticate by running `monarch-mcp login`"
                })
            }
            Err(e) => return Err(McpError::internal_error(e.to_string(), None)),
        };

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string(&payload)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
        )]))
    }

    #[tool(
        description = "Scan recurring charges for amount drift ('creeping' subscriptions \
        whose price has quietly changed) and list upcoming renewals due this period. \
        Stable subscriptions are reported but not flagged."
    )]
    async fn recurring_scan(
        &self,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let base = std::env::var("MONARCH_BASE").ok().filter(|s| !s.is_empty());
        let mut client = MonarchClient::new(base);
        client.resolve_token_from_env_or_disk();

        let payload = match fetch_and_compute_scan(&client).await {
            Ok(scan) => serde_json::to_value(&scan)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
            Err(MonarchError::SessionExpired) => {
                json!({
                    "error": "Session expired — re-authenticate by running `monarch-mcp login`"
                })
            }
            Err(e) => return Err(McpError::internal_error(e.to_string(), None)),
        };

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string(&payload)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
        )]))
    }

    #[tool(
        description = "List every recurring charge ranked by annualized cost, with \
        total monthly and yearly subscription burn. Use this to answer: 'what is my \
        full subscription load and what's the fat to cut?' Each entry includes a \
        monthly-equivalent amount (normalized from the stream's cadence) and the \
        annualized cost. Approximate streams (utilities, variable charges) are \
        included and flagged. Income streams are excluded. \
        Pairs with recurring_scan for the anomaly lens (creeping/upcoming)."
    )]
    async fn subscription_audit(
        &self,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let base = std::env::var("MONARCH_BASE").ok().filter(|s| !s.is_empty());
        let mut client = MonarchClient::new(base);
        client.resolve_token_from_env_or_disk();

        let payload = match fetch_and_compute_audit(&client).await {
            Ok(audit) => serde_json::to_value(&audit)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
            Err(MonarchError::SessionExpired) => {
                json!({
                    "error": "Session expired — re-authenticate by running `monarch-mcp login`"
                })
            }
            Err(e) => return Err(McpError::internal_error(e.to_string(), None)),
        };

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string(&payload)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
        )]))
    }

    #[tool(
        description = "Drill into transactions for a date range, optionally narrowed by \
        category and/or merchant. Returns every matching transaction including its \
        **id** (required by apply_changeset to re-categorize), plus a compound summary \
        with total count, net amount, and an inflow-vs-outflow split so refunds are \
        visible alongside charges.\n\n\
        Two-step re-categorization workflow:\n\
        1. Call inspect_transactions(category=\"Pets\") to see all Pets transactions \
           with their ids and amounts.\n\
        2. Call apply_changeset(changes=[{\"id\": \"<id>\", \"category\": \"Veterinary\"}]) \
           to correct any mis-categorized entry.\n\n\
        This tool is read-only: it never modifies data. Use it to diagnose anomalies \
        (e.g. a $12k Pets spike or a $3.3k Medical charge) or to surface ids for \
        already-categorized transactions that need correction via apply_changeset."
    )]
    async fn inspect_transactions(
        &self,
        _ctx: RequestContext<RoleServer>,
        Parameters(params): Parameters<InspectTransactionsParams>,
    ) -> Result<CallToolResult, McpError> {
        let base = std::env::var("MONARCH_BASE").ok().filter(|s| !s.is_empty());
        let mut client = MonarchClient::new(base);
        client.resolve_token_from_env_or_disk();

        let payload = match fetch_and_compute_inspection(&client, params).await {
            Ok(result) => serde_json::to_value(&result)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
            Err(MonarchError::SessionExpired) => {
                json!({
                    "error": "Session expired — re-authenticate by running `monarch-mcp login`"
                })
            }
            Err(e) => return Err(McpError::internal_error(e.to_string(), None)),
        };

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string(&payload)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
        )]))
    }

    #[tool(
        description = "List all accounts grouped into retirement-planning buckets: \
        tax_advantaged (401k, Roth IRA, HSA), taxable_brokerage, cash (depository), \
        other_assets (vehicles), and liabilities (credit cards, loans). \
        Each account shows its balance, Monarch type/subtype, hidden flag, and whether \
        its subtype was recognized. Includes a net-worth rollup for cross-checking \
        against financial_overview."
    )]
    async fn account_inventory(
        &self,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let base = std::env::var("MONARCH_BASE").ok().filter(|s| !s.is_empty());
        let mut client = MonarchClient::new(base);
        client.resolve_token_from_env_or_disk();

        let payload = match fetch_and_compute_inventory(&client).await {
            Ok(inventory) => serde_json::to_value(&inventory)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
            Err(MonarchError::SessionExpired) => {
                json!({
                    "error": "Session expired — re-authenticate by running `monarch-mcp login`"
                })
            }
            Err(e) => return Err(McpError::internal_error(e.to_string(), None)),
        };

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string(&payload)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
        )]))
    }

    #[tool(
        description = "Split net worth by asset class: equities (all brokerage accounts — \
        401k, Roth, taxable), cash (depository), real_estate, crypto, other_assets (vehicles), \
        and liabilities. Each class shows its dollar total and percent of gross assets. \
        Includes gross_assets, total_liabilities, and net_worth rollup. \
        Note: Monarch does not expose per-holding data, so equity vs. bond breakdown within \
        an account is not available — all brokerage accounts are classified as equities. \
        Unrecognized account subtypes are bucketed as 'other' and flagged. \
        Use as the asset-class lens alongside account_inventory (the tax-treatment lens)."
    )]
    async fn asset_allocation(
        &self,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let base = std::env::var("MONARCH_BASE").ok().filter(|s| !s.is_empty());
        let mut client = MonarchClient::new(base);
        client.resolve_token_from_env_or_disk();

        let payload = match fetch_and_compute_allocation(&client).await {
            Ok(allocation) => serde_json::to_value(&allocation)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
            Err(MonarchError::SessionExpired) => {
                json!({
                    "error": "Session expired — re-authenticate by running `monarch-mcp login`"
                })
            }
            Err(e) => return Err(McpError::internal_error(e.to_string(), None)),
        };

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string(&payload)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
        )]))
    }

    #[tool(
        description = "Retirement-readiness snapshot: compares the investable portfolio \
        against a safe-withdrawal-rate projection of the annualised spending baseline. \
        Reports sustainable_annual_withdrawal, coverage_ratio (withdrawal / spend), \
        target_portfolio (the 25x spend number at 4%), and surplus_or_gap. \
        Invested assets = Equities-class accounts only (brokerage, 401k, Roth, HSA, \
        stock plan) — real estate, cash, crypto, vehicles, and liabilities are excluded \
        from the SWR base (ADR 0016). All assumptions (withdrawal rate, spend window, \
        what counts as invested) are surfaced in the response so the numbers are \
        self-interpreting.\n\n\
        Params (all optional):\n\
        - months: trailing complete months for the spend baseline (default 6, max 24)\n\
        - withdrawal_rate: decimal fraction, default 0.04 (4% rule), range [0.02, 0.10]"
    )]
    async fn retirement_readiness(
        &self,
        _ctx: RequestContext<RoleServer>,
        Parameters(params): Parameters<RetirementReadinessParams>,
    ) -> Result<CallToolResult, McpError> {
        let base = std::env::var("MONARCH_BASE").ok().filter(|s| !s.is_empty());
        let mut client = MonarchClient::new(base);
        client.resolve_token_from_env_or_disk();

        let payload = match fetch_and_compute_retirement_readiness(&client, params).await {
            Ok(result) => serde_json::to_value(&result)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
            Err(MonarchError::SessionExpired) => {
                json!({
                    "error": "Session expired — re-authenticate by running `monarch-mcp login`"
                })
            }
            Err(MonarchError::InvalidInput(msg)) => {
                json!({ "error": msg })
            }
            Err(e) => return Err(McpError::internal_error(e.to_string(), None)),
        };

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string(&payload)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
        )]))
    }

    #[tool(
        description = "Show mid-month budget pacing per expense category: how much of each \
        category's budget has been spent relative to how far through the month we are. \
        Returns per-category pace_status (under/on_track/over/over_budget), budget, spent, \
        remaining, and a rollup with totals and counts. Use this during the month to catch \
        categories tracking hot before they go over budget."
    )]
    async fn budget_review(
        &self,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let base = std::env::var("MONARCH_BASE").ok().filter(|s| !s.is_empty());
        let mut client = MonarchClient::new(base);
        client.resolve_token_from_env_or_disk();

        let payload = match fetch_and_compute_budget_review(&client).await {
            Ok(review) => serde_json::to_value(&review)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
            Err(MonarchError::SessionExpired) => {
                json!({
                    "error": "Session expired — re-authenticate by running `monarch-mcp login`"
                })
            }
            Err(e) => return Err(McpError::internal_error(e.to_string(), None)),
        };

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string(&payload)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
        )]))
    }

    #[tool(
        description = "Compute per-month true spending over a multi-month range (default: \
        last 6 complete months). Returns compact per-month aggregates — total true spending, \
        by-category breakdown, and a fixed-vs-discretionary split — never raw transactions. \
        Income and transfers are excluded (same exclusion rules as spending_report). \
        Use this for retirement-spending analysis or building a multi-month baseline.\n\n\
        Params (all optional):\n\
        - months: last N complete months (default 6, max 24)\n\
        - start_date / end_date: explicit ISO-8601 range (overrides months)"
    )]
    async fn spending_history(
        &self,
        _ctx: RequestContext<RoleServer>,
        Parameters(params): Parameters<SpendingHistoryParams>,
    ) -> Result<CallToolResult, McpError> {
        let base = std::env::var("MONARCH_BASE").ok().filter(|s| !s.is_empty());
        let mut client = MonarchClient::new(base);
        client.resolve_token_from_env_or_disk();

        let payload = match fetch_and_compute_history(&client, params).await {
            Ok(history) => serde_json::to_value(&history)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
            Err(MonarchError::SessionExpired) => {
                json!({
                    "error": "Session expired — re-authenticate by running `monarch-mcp login`"
                })
            }
            Err(MonarchError::InvalidInput(msg)) => {
                json!({ "error": msg })
            }
            Err(e) => return Err(McpError::internal_error(e.to_string(), None)),
        };

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string(&payload)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
        )]))
    }

    #[tool(
        description = "Compute monthly income, true spending, net savings, and savings rate \
        over a multi-month range (default: last 6 complete months). Returns compact \
        per-month aggregates — never raw transactions. Income = positive income-group \
        transactions; true spending uses the same exclusion rules as spending_history \
        (transfers and credit-card payments excluded). A per-month savings rate and a \
        window-average rate are included; months with zero income omit the rate field.\n\n\
        Params (all optional):\n\
        - months: last N complete months (default 6, max 24)\n\
        - start_date / end_date: explicit ISO-8601 range (overrides months)"
    )]
    async fn savings_rate(
        &self,
        _ctx: RequestContext<RoleServer>,
        Parameters(params): Parameters<SavingsRateParams>,
    ) -> Result<CallToolResult, McpError> {
        let base = std::env::var("MONARCH_BASE").ok().filter(|s| !s.is_empty());
        let mut client = MonarchClient::new(base);
        client.resolve_token_from_env_or_disk();

        let payload = match fetch_and_compute_savings_rate(&client, params).await {
            Ok(result) => serde_json::to_value(&result)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
            Err(MonarchError::SessionExpired) => {
                json!({
                    "error": "Session expired — re-authenticate by running `monarch-mcp login`"
                })
            }
            Err(MonarchError::InvalidInput(msg)) => {
                json!({ "error": msg })
            }
            Err(e) => return Err(McpError::internal_error(e.to_string(), None)),
        };

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string(&payload)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
        )]))
    }

    #[tool(
        description = "Measure actual finances against the household's remembered goals \
        (savings rate, emergency-fund runway, debt payoff). Reports each goal as \
        on-track, drifting, or off, with the lever to pull."
    )]
    async fn progress_vs_goals(
        &self,
        _ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let base = std::env::var("MONARCH_BASE").ok().filter(|s| !s.is_empty());
        let mut client = MonarchClient::new(base);
        client.resolve_token_from_env_or_disk();

        let payload = match fetch_and_compute_progress(&client).await {
            Ok(progress) => serde_json::to_value(&progress)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
            Err(MonarchError::SessionExpired) => {
                json!({
                    "error": "Session expired — re-authenticate by running `monarch-mcp login`"
                })
            }
            Err(e) => return Err(McpError::internal_error(e.to_string(), None)),
        };

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string(&payload)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
        )]))
    }
}

impl Default for MonarchTools {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// Date-range helpers
// ---------------------------------------------------------------------------

/// Convert a civil (year, month, day) triple to days since the Unix epoch.
///
/// Uses the Howard Hinnant days_from_civil algorithm. No input validation —
/// callers must ensure month is 1..=12 and day is valid for the month.
/// `parse_iso_date_to_epoch_day` validates before calling this; `today_epoch_day`
/// obtains a validated date from `chrono::Local`.
fn civil_to_epoch_day(year: i64, month: i64, day: i64) -> i64 {
    // Howard Hinnant civil_from_days inverse: days_from_civil
    // https://howardhinnant.github.io/date_algorithms.html
    let y = if month <= 2 { year - 1 } else { year };
    let m = month as u32;
    let era = if y >= 0 { y } else { y - 399 } / 400;
    let yoe = y - era * 400;
    let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) as i64 + 2) / 5 + day - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    era * 146_097 + doe - 719_468
}

/// Parse an ISO `YYYY-MM-DD` date string to days since the Unix epoch.
///
/// **Canonical production parser** — the sole authoritative implementation
/// for converting user-supplied or API date strings to epoch days.
/// `spending_history.rs` has a parallel `#[cfg(test)]`-only helper
/// (`parse_date_for_test`) that serves the same math for its unit tests
/// without creating a cross-module import; both implement the same
/// Howard Hinnant algorithm.
///
/// Returns `None` for non-three-part or non-numeric inputs so callers can
/// fall back gracefully instead of silently using a wrong date.
fn parse_iso_date_to_epoch_day(s: &str) -> Option<i64> {
    let mut parts = s.splitn(3, '-');
    let year: i64 = parts.next()?.parse().ok()?;
    let month: i64 = parts.next()?.parse().ok()?;
    let day: i64 = parts.next()?.parse().ok()?;
    // Reject if a fourth part exists (extra dashes)
    // splitn(3,'-') stops at 3 parts so no extra check needed.

    // Validate ranges before arithmetic to prevent overflow and silent normalization
    // Year must be in 1..=9999 to bound the Hinnant formula and avoid overflow
    if !(1..=9999).contains(&year) {
        return None;
    }
    // Month must be 1..=12
    if !(1..=12).contains(&month) {
        return None;
    }
    // Day must be 1..=days_in_month(year, month as u32)
    let max_day = days_in_month(year, month as u32) as i64;
    if day < 1 || day > max_day {
        return None;
    }

    Some(civil_to_epoch_day(year, month, day))
}

/// Days since the Unix epoch for "today" in the host's local timezone.
///
/// Honors the `MONARCH_NOW` test override (an ISO `YYYY-MM-DD` date) so
/// datetime-dependent behavior is deterministic and hermetic in tests.
/// Production leaves it unset and uses `chrono::Local` so the advisor
/// matches what the user sees running it locally (ADR 0006).
fn today_epoch_day() -> i64 {
    if let Ok(now_override) = std::env::var("MONARCH_NOW") {
        if let Some(day) = parse_iso_date_to_epoch_day(&now_override) {
            return day;
        }
        // Malformed override — fall through to the local clock, never a wrong fixed day
    }
    use chrono::{Datelike, Local};
    let today = Local::now().date_naive();
    civil_to_epoch_day(
        today.year() as i64,
        today.month() as i64,
        today.day() as i64,
    )
}

/// Pure computation of the current-month range for a given epoch day.
///
/// Extracted from `current_month_range` so it can be tested without touching
/// the system clock. Callers pass `today_epoch_day()`.
fn current_month_range_for_day(day: i64) -> (String, String) {
    let (year, month, _) = epoch_days_to_ymd(day);
    let start = format!("{year:04}-{month:02}-01");
    let last_day = days_in_month(year, month);
    let end = format!("{year:04}-{month:02}-{last_day:02}");
    (start, end)
}

/// Pure computation of the prior-month range for a given epoch day.
///
/// Extracted from `prior_month_range` so it can be tested without touching
/// the system clock. Callers pass `today_epoch_day()`.
fn prior_month_range_for_day(day: i64) -> (String, String) {
    let (mut year, mut month, _) = epoch_days_to_ymd(day);
    if month == 1 {
        year -= 1;
        month = 12;
    } else {
        month -= 1;
    }
    let last_day = days_in_month(year, month);
    let start = format!("{year:04}-{month:02}-01");
    let end = format!("{year:04}-{month:02}-{last_day:02}");
    (start, end)
}

/// Returns (start, end) for the current calendar month as ISO-8601 strings.
fn current_month_range() -> (String, String) {
    current_month_range_for_day(today_epoch_day())
}

/// Returns (start, end) for the prior calendar month.
fn prior_month_range() -> (String, String) {
    prior_month_range_for_day(today_epoch_day())
}

fn days_in_month(year: i64, month: u32) -> u32 {
    match month {
        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
        4 | 6 | 9 | 11 => 30,
        2 => {
            if year % 400 == 0 || (year % 4 == 0 && year % 100 != 0) {
                29
            } else {
                28
            }
        }
        _ => 31,
    }
}

// ---------------------------------------------------------------------------
// Data fetching helpers — isolated so tool handlers stay readable
// ---------------------------------------------------------------------------

/// Fetch all transactions for the current month without a row cap.
///
/// Both `financial_overview` and `spending_report` must consume the same slice
/// so their spending totals agree (issue #25).
///
/// The limit is capped at `i32::MAX` (2,147,483,647) rather than `u32::MAX`
/// (4,294,967,295) because Monarch's GraphQL schema uses a signed `Int` for the
/// limit argument. Passing `u32::MAX` overflows GraphQL's `Int32` range and
/// causes Monarch to return a server-side GraphQL error (issue #47).
/// `i32::MAX` rows is effectively unbounded for any real household.
async fn fetch_current_month_transactions(
    client: &MonarchClient,
    start: &str,
    end: &str,
) -> Result<Vec<crate::client::Transaction>, MonarchError> {
    client.get_transactions(start, end, i32::MAX as u32).await
}

async fn fetch_and_compute(
    client: &MonarchClient,
) -> Result<crate::financial_overview::OverviewResult, MonarchError> {
    let (cur_start, cur_end) = current_month_range();
    let (pri_start, pri_end) = prior_month_range();

    // Run the three lightweight requests in parallel, then await the heavy
    // transaction fetch alone (issue #47).
    //
    // Primary fix: fetch_current_month_transactions now uses i32::MAX instead
    // of u32::MAX, which overflowed GraphQL's signed Int32 and caused Monarch
    // to reject the request. The sequential ordering here is belt-and-suspenders:
    // it keeps the large fetch from racing other requests on the same connection.
    let (accounts, cashflow, history) = tokio::try_join!(
        client.get_accounts(),
        client.get_cashflow(&cur_start, &cur_end, &pri_start, &pri_end),
        client.get_net_worth_history(&pri_start, &pri_end),
    )?;

    let transactions = fetch_current_month_transactions(client, &cur_start, &cur_end).await?;

    Ok(compute_overview(
        &accounts,
        &cashflow,
        &transactions,
        &history,
    ))
}

async fn fetch_and_compute_spending(
    client: &MonarchClient,
) -> Result<crate::spending_report::SpendingReport, MonarchError> {
    let (cur_start, cur_end) = current_month_range();
    let (pri_start, pri_end) = prior_month_range();

    // Run the lightweight budget and cashflow fetches in parallel, then await
    // the heavy transaction fetch alone (issue #47).
    //
    // Primary fix: fetch_current_month_transactions now uses i32::MAX instead
    // of u32::MAX (which overflowed GraphQL's signed Int32). The sequential
    // ordering here is belt-and-suspenders against any remaining server-side
    // contention from a large transaction payload.
    let (budgets, cashflow) = tokio::try_join!(
        client.get_budgets(&cur_start, &cur_end),
        client.get_cashflow(&cur_start, &cur_end, &pri_start, &pri_end),
    )?;

    let transactions = fetch_current_month_transactions(client, &cur_start, &cur_end).await?;

    Ok(compute_spending_report(&transactions, &budgets, &cashflow))
}

async fn fetch_and_compute_triage(
    client: &MonarchClient,
) -> Result<crate::triage::TriageResult, MonarchError> {
    let (cur_start, cur_end) = current_month_range();
    let (all_transactions, uncategorized) = tokio::try_join!(
        client.get_transactions(&cur_start, &cur_end, 500),
        client.get_transactions_needing_review(),
    )?;
    let suggestion_map = build_category_suggestion_map(&all_transactions);
    Ok(propose_changes(&uncategorized, &suggestion_map))
}

async fn fetch_and_compute_progress(
    client: &MonarchClient,
) -> Result<crate::progress_vs_goals::GoalsProgress, MonarchError> {
    let goals = Goals::load_from_env().map_err(|e| MonarchError::Internal(e.to_string()))?;
    let today_day = today_epoch_day();
    let (cur_start, cur_end) = current_month_range_for_day(today_day);
    let (pri_start, pri_end) = prior_month_range_for_day(today_day);
    let (today_year, today_month, _) = epoch_days_to_ymd(today_day);

    // Derive YYYY-MM labels for snapshot lookup
    let prior_month_label = &pri_start[..7]; // "YYYY-MM"
    let current_month_label = &cur_start[..7];

    // Fetch snapshots only when a debt-payoff goal is configured to keep the
    // no-debt-goal path's fetch cost unchanged.
    let snapshots = if goals.debt_payoff.is_some() {
        client.get_snapshots_by_account_type(&pri_start).await?
    } else {
        vec![]
    };

    let (accounts, cashflow) = tokio::try_join!(
        client.get_accounts(),
        client.get_cashflow(&cur_start, &cur_end, &pri_start, &pri_end),
    )?;
    Ok(compute_progress(
        &goals,
        &accounts,
        &cashflow,
        &snapshots,
        prior_month_label,
        current_month_label,
        (today_year, today_month),
    ))
}

async fn fetch_and_compute_scan(
    client: &MonarchClient,
) -> Result<crate::recurring_scan::ScanResult, MonarchError> {
    let (cur_start, cur_end) = current_month_range();
    let items = client.get_recurring_for_scan(&cur_start, &cur_end).await?;
    Ok(compute_scan(&items))
}

/// Compute the 12-month audit fetch window starting from the given epoch day.
///
/// Returns today through the last day of the month 12 months forward as
/// ISO-8601 strings. A 12-month window guarantees that every cadence —
/// monthly through annual — has at least one scheduled occurrence in the
/// window, so no stream is silently absent because it doesn't renew in
/// the current calendar month.
///
/// `recurringTransactionItems` returns upcoming (future) occurrences, so a
/// forward window matches the direction the API returns data. The
/// deduplication in `get_recurring_for_audit` (by merchant+amount) collapses
/// a monthly stream's 12 occurrences to one entry, so widening the window is
/// safe: a monthly stream still appears once, a yearly stream now appears once.
///
/// See ADR 0015 Decision 7.
fn audit_window_for_day(day: i64) -> (String, String) {
    let (year, month, dom) = epoch_days_to_ymd(day);
    let start = format!("{year:04}-{month:02}-{dom:02}");
    // Advance 12 months forward for the end month.
    let mut ey = year;
    let mut em = month;
    for _ in 0..12 {
        if em == 12 {
            ey += 1;
            em = 1;
        } else {
            em += 1;
        }
    }
    let last_day = days_in_month(ey, em);
    let end = format!("{ey:04}-{em:02}-{last_day:02}");
    (start, end)
}

async fn fetch_and_compute_audit(
    client: &MonarchClient,
) -> Result<crate::subscription_audit::AuditResult, MonarchError> {
    // Use a 12-month forward window so every cadence (monthly through annual)
    // has at least one occurrence. A single-month window omits yearly,
    // quarterly, and semiannual streams that don't renew this month (ADR 0015).
    let (audit_start, audit_end) = audit_window_for_day(today_epoch_day());
    let items = client
        .get_recurring_for_audit(&audit_start, &audit_end)
        .await?;
    Ok(compute_subscription_audit(&items))
}

async fn fetch_and_compute_inspection(
    client: &MonarchClient,
    params: InspectTransactionsParams,
) -> Result<crate::inspect_transactions::InspectionResult, MonarchError> {
    let (default_start, default_end) = current_month_range();

    // Coerce empty/whitespace-only strings to None uniformly across all params
    // so that `start_date=""` falls back to the month default just like
    // omitting it, and `category=""` / `merchant=""` impose no filter constraint.
    let start = blank_to_none(params.start_date).unwrap_or(default_start);
    let end = blank_to_none(params.end_date).unwrap_or(default_end);

    let transactions = client.get_transactions(&start, &end, 500).await?;

    let filter = InspectFilter {
        category: blank_to_none(params.category),
        merchant: blank_to_none(params.merchant),
    };

    Ok(compute_inspection(&transactions, &filter))
}

async fn fetch_and_compute_forecast(
    client: &MonarchClient,
) -> Result<crate::cashflow_forecast::ForecastResult, MonarchError> {
    let (cur_start, cur_end) = current_month_range();

    let (accounts, recurring) = tokio::try_join!(
        client.get_accounts(),
        client.get_recurring(&cur_start, &cur_end),
    )?;

    // Sum liquid (depository) account balances as the available cash position.
    // Credit/loan balances are negative and would distort the projection.
    let current_balance: f64 = accounts
        .iter()
        .filter(|a| a.account_type.name == "depository")
        .map(|a| a.current_balance)
        .sum();

    Ok(compute_forecast(current_balance, &recurring))
}

async fn fetch_and_compute_inventory(
    client: &MonarchClient,
) -> Result<crate::account_inventory::AccountInventory, MonarchError> {
    let accounts = client.get_accounts().await?;
    Ok(compute_account_inventory(&accounts))
}

async fn fetch_and_compute_allocation(
    client: &MonarchClient,
) -> Result<crate::asset_allocation::AssetAllocation, MonarchError> {
    let accounts = client.get_accounts().await?;
    Ok(compute_asset_allocation(&accounts))
}

async fn fetch_and_compute_budget_review(
    client: &MonarchClient,
) -> Result<crate::budget_review::BudgetReview, MonarchError> {
    let today_day = today_epoch_day();
    let (cur_start, cur_end) = current_month_range_for_day(today_day);
    let (year, month, today_day_of_month) = epoch_days_to_ymd(today_day);
    let dim = days_in_month(year, month);

    let budgets = client.get_budgets(&cur_start, &cur_end).await?;
    let transactions = fetch_current_month_transactions(client, &cur_start, &cur_end).await?;

    Ok(compute_budget_review(
        &budgets,
        &transactions,
        today_day_of_month,
        dim,
    ))
}

async fn fetch_and_compute_savings_rate(
    client: &MonarchClient,
    params: SavingsRateParams,
) -> Result<SavingsRateResult, MonarchError> {
    let today_day = today_epoch_day();

    // Reuse the same range-resolution logic as spending_history so the two
    // tools always cover identical month windows when called with the same params.
    let (start, end) =
        resolve_history_range(today_day, params.months, params.start_date, params.end_date)
            .map_err(MonarchError::InvalidInput)?;

    // Fetch transactions only — income is derived from the same GetTransactionsList
    // call that spending_history uses, so savings_rate.true_spending always agrees
    // with spending_history.total_true_spending for the same range (ADR 0012).
    let transactions = client
        .get_transactions(&start, &end, i32::MAX as u32)
        .await?;

    Ok(compute_savings_rate(&transactions, &start, &end))
}

async fn fetch_and_compute_retirement_readiness(
    client: &MonarchClient,
    params: RetirementReadinessParams,
) -> Result<crate::retirement_readiness::RetirementReadiness, MonarchError> {
    // Validate withdrawal rate before any network calls so invalid input fails fast.
    let withdrawal_rate =
        validate_withdrawal_rate(params.withdrawal_rate.unwrap_or(WITHDRAWAL_RATE_DEFAULT))
            .map_err(MonarchError::InvalidInput)?;

    // Resolve the trailing-months spend window (same clamping as savings_rate).
    let today_day = today_epoch_day();
    let n_months = params.months.unwrap_or(6).clamp(1, 24);
    let (start, end) = range_for_months_count(today_day, n_months);

    // Fetch accounts and transactions in parallel — they are independent.
    let (accounts_result, transactions_result) = tokio::join!(
        client.get_accounts(),
        client.get_transactions(&start, &end, i32::MAX as u32),
    );
    let accounts = accounts_result?;
    let transactions = transactions_result?;

    // Invested assets = sum of Equities-class account balances (ADR 0016).
    let invested_assets: f64 = invested_financial_accounts(&accounts)
        .iter()
        .map(|a| a.current_balance)
        .sum();

    // Annualise: (true_spending_over_window / n_months) * 12
    let window_true_spending = compute_true_spending(&transactions);
    // SAFETY: n_months is clamp(1, 24) at line 1120, so it is always >= 1.
    // This division can never divide by zero. The clamp is the guard; no runtime
    // branch is needed.
    let annual_baseline_spend = (window_true_spending / f64::from(n_months)) * 12.0;

    Ok(compute_retirement_readiness(
        invested_assets,
        annual_baseline_spend,
        withdrawal_rate,
        n_months,
    ))
}

async fn fetch_and_compute_trend(
    client: &MonarchClient,
    months: u32,
) -> Result<crate::net_worth_trend::TrendResult, MonarchError> {
    // Build a start date `months` months back from today (first of that month).
    let start_date = months_ago_start(months);
    let snapshots = client.get_snapshots_by_account_type(&start_date).await?;
    Ok(compute_trend(&snapshots))
}

/// Pure computation of the start of the month `n` months before the given epoch day.
///
/// Extracted from `months_ago_start` so it can be tested without touching the system
/// clock. `n=0` returns the first day of the month containing `day`.
fn months_ago_start_for_day(day: i64, n: u32) -> String {
    let (mut year, mut month, _) = epoch_days_to_ymd(day);
    for _ in 0..n {
        if month == 1 {
            year -= 1;
            month = 12;
        } else {
            month -= 1;
        }
    }
    format!("{year:04}-{month:02}-01")
}

/// Compute the ISO date for the first day of the month that is `n` months before today.
///
/// Uses only integer arithmetic on the Unix epoch — no external date library needed.
fn months_ago_start(n: u32) -> String {
    months_ago_start_for_day(today_epoch_day(), n)
}

/// Convert a count of days since Unix epoch to (year, month, day).
///
/// Uses the Gregorian calendar algorithm from Howard Hinnant's date library.
fn epoch_days_to_ymd(days: i64) -> (i64, u32, u32) {
    let z = days + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let year = if m <= 2 { y + 1 } else { y };
    (year, m as u32, d as u32)
}

/// Resolve the date range for `spending_history`, returning `(start, end)` as
/// ISO-8601 strings or an error message describing why the input is invalid.
///
/// Resolution rules (in priority order):
/// 1. When both `start_date` and `end_date` are supplied, validate each via
///    `parse_iso_date_to_epoch_day` and reject if either is malformed or if
///    `start > end`.
/// 2. Otherwise, fall back to `range_for_months_count(today_day, months)`,
///    where `months` defaults to 6 and is clamped to 1..=24.
///
/// Returning `Err` with a clear message rather than silently producing an
/// empty result prevents the silent-zero failure mode (ADR 0011).
fn resolve_history_range(
    today_day: i64,
    months: Option<u32>,
    start_date: Option<String>,
    end_date: Option<String>,
) -> Result<(String, String), String> {
    match (start_date, end_date) {
        (Some(s), Some(e)) => {
            let start_day = parse_iso_date_to_epoch_day(&s)
                .ok_or_else(|| format!("invalid start_date {s:?}: must be YYYY-MM-DD"))?;
            let end_day = parse_iso_date_to_epoch_day(&e)
                .ok_or_else(|| format!("invalid end_date {e:?}: must be YYYY-MM-DD"))?;
            if start_day > end_day {
                return Err(format!(
                    "start_date {s:?} is after end_date {e:?}: range must be start ≤ end"
                ));
            }
            Ok((s, e))
        }
        (Some(_), None) => Err(
            "provide BOTH start_date and end_date, or neither (got only start_date)".to_string(),
        ),
        (None, Some(_)) => {
            Err("provide BOTH start_date and end_date, or neither (got only end_date)".to_string())
        }
        (None, None) => {
            let n = months.unwrap_or(6).clamp(1, 24);
            Ok(range_for_months_count(today_day, n))
        }
    }
}

async fn fetch_and_compute_history(
    client: &MonarchClient,
    params: SpendingHistoryParams,
) -> Result<SpendingHistory, MonarchError> {
    let today_day = today_epoch_day();

    // Resolve and validate the date range; malformed/reversed explicit dates
    // surface as a clear error rather than silently returning empty months.
    let (start, end) =
        resolve_history_range(today_day, params.months, params.start_date, params.end_date)
            .map_err(MonarchError::InvalidInput)?;

    let transactions = client
        .get_transactions(&start, &end, i32::MAX as u32)
        .await?;

    Ok(compute_spending_history(&transactions, &start, &end))
}

async fn apply_approved_changeset(
    client: &MonarchClient,
    raw_changes: Vec<serde_json::Value>,
) -> Result<crate::triage::ApplyResult, MonarchError> {
    // Parse entries strictly: unknown fields and wrong types become RejectedChange
    // entries with the real transaction id preserved, never silent no-ops.
    let entries = parse_raw_changes(raw_changes);

    // Partition into allowed and forbidden entries — forbidden ones never reach the API.
    let mut result = partition_changeset(&entries);

    // Resolve category names → UUIDs before calling the Monarch API.
    // Fetch categories once per apply_changeset call (not per change).
    // Any change whose category name is not in Monarch's catalog is rejected
    // here and removed from applied_changes — it is never sent to the API.
    if result.applied_changes.iter().any(|c| c.category.is_some()) {
        let categories = client.get_categories().await?;
        let (resolved, new_rejections) =
            resolve_category_names(&categories, result.applied_changes);
        result.applied_changes = resolved;
        result.rejected_changes.extend(new_rejections);
        result.transaction_count = result.applied_changes.len() + result.rejected_changes.len();
    }

    // Send only the allowed, resolved changes to the Monarch API.
    for change in &result.applied_changes {
        client
            .update_transaction(
                &change.id,
                change.category.as_deref(),
                change.tags.clone(),
                change.notes.as_deref(),
            )
            .await?;
    }

    Ok(result)
}

#[rmcp::tool_handler]
impl ServerHandler for MonarchTools {
    fn get_info(&self) -> ServerInfo {
        ServerInfo::new(ServerCapabilities::builder().enable_tools().build())
            .with_server_info(Implementation::new(
                "monarch-mcp",
                env!("CARGO_PKG_VERSION"),
            ))
            .with_protocol_version(ProtocolVersion::V_2024_11_05)
            .with_instructions(
                "Monarch Money budgeting advisor. Tools: financial_overview, \
             spending_report, budget_review, spending_history, savings_rate, \
             triage_uncategorized, inspect_transactions, apply_changeset, \
             progress_vs_goals, cashflow_forecast, net_worth_trend, recurring_scan, \
             subscription_audit, account_inventory, asset_allocation, \
             retirement_readiness."
                    .to_string(),
            )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Helper: build an epoch day from a known date string for test inputs.
    fn day(date: &str) -> i64 {
        parse_iso_date_to_epoch_day(date).unwrap_or_else(|| panic!("bad test date: {date}"))
    }

    // --- civil_to_epoch_day ---

    #[test]
    fn civil_to_epoch_day_agrees_with_parse_for_unix_epoch() {
        // 1970-01-01 is day 0 — both paths must agree
        assert_eq!(civil_to_epoch_day(1970, 1, 1), 0);
        assert_eq!(
            civil_to_epoch_day(1970, 1, 1),
            parse_iso_date_to_epoch_day("1970-01-01").unwrap()
        );
    }

    #[test]
    fn civil_to_epoch_day_agrees_with_parse_for_mid_month() {
        let via_parse = parse_iso_date_to_epoch_day("2026-05-15").unwrap();
        assert_eq!(civil_to_epoch_day(2026, 5, 15), via_parse);
    }

    #[test]
    fn civil_to_epoch_day_agrees_with_parse_for_leap_day() {
        let via_parse = parse_iso_date_to_epoch_day("2024-02-29").unwrap();
        assert_eq!(civil_to_epoch_day(2024, 2, 29), via_parse);
    }

    #[test]
    fn civil_to_epoch_day_agrees_with_parse_for_year_end() {
        let via_parse = parse_iso_date_to_epoch_day("2025-12-31").unwrap();
        assert_eq!(civil_to_epoch_day(2025, 12, 31), via_parse);
    }

    #[test]
    fn civil_to_epoch_day_round_trips_through_epoch_days_to_ymd() {
        // Verify the round-trip identity: epoch_days_to_ymd(civil_to_epoch_day(y,m,d)) == (y,m,d)
        // Uses Local::now() — not hermetic on the date value, but hermetic on the identity.
        use chrono::{Datelike, Local};
        let today = Local::now().date_naive();
        let d = civil_to_epoch_day(
            today.year() as i64,
            today.month() as i64,
            today.day() as i64,
        );
        let (ry, rm, rd) = epoch_days_to_ymd(d);
        assert_eq!(
            (ry, rm, rd),
            (today.year() as i64, today.month(), today.day())
        );
    }

    // --- local timezone regression (issue #36) ---

    #[test]
    fn local_tz_wins_over_utc_at_month_boundary() {
        // 2026-06-01 01:00 UTC == 2026-05-31 18:00 in UTC-07:00.
        // A UTC-based today_epoch_day would compute June; local must compute May.
        use chrono::{Datelike, FixedOffset, TimeZone, Utc};

        let instant = Utc.with_ymd_and_hms(2026, 6, 1, 1, 0, 0).unwrap();
        let local = instant
            .with_timezone(&FixedOffset::west_opt(7 * 3600).unwrap())
            .date_naive();
        assert_eq!(
            (local.year(), local.month(), local.day()),
            (2026, 5, 31),
            "UTC-07 should see May 31, not June 1"
        );

        // Local path gives May range
        let local_day = civil_to_epoch_day(
            local.year() as i64,
            local.month() as i64,
            local.day() as i64,
        );
        assert_eq!(
            current_month_range_for_day(local_day),
            ("2026-05-01".to_string(), "2026-05-31".to_string()),
            "local date must produce May range"
        );

        // UTC path would wrongly give June range — confirming the old bug
        let utc = instant.date_naive();
        let utc_day = civil_to_epoch_day(utc.year() as i64, utc.month() as i64, utc.day() as i64);
        assert_eq!(
            current_month_range_for_day(utc_day),
            ("2026-06-01".to_string(), "2026-06-30".to_string()),
            "UTC date produces June range"
        );
    }

    #[test]
    fn ahead_of_utc_local_rolls_to_next_month() {
        // Symmetric mirror of the west case: an ahead-of-UTC user.
        // 2026-05-31 23:00 UTC == 2026-06-01 13:00 in UTC+14:00 (Line Islands).
        // A UTC-based today_epoch_day would compute May; local must compute June.
        use chrono::{Datelike, FixedOffset, TimeZone, Utc};

        let instant = Utc.with_ymd_and_hms(2026, 5, 31, 23, 0, 0).unwrap();
        let local = instant
            .with_timezone(&FixedOffset::east_opt(14 * 3600).unwrap())
            .date_naive();
        assert_eq!(
            (local.year(), local.month(), local.day()),
            (2026, 6, 1),
            "UTC+14 should see June 1, not May 31"
        );

        // Local path gives June range
        let local_day = civil_to_epoch_day(
            local.year() as i64,
            local.month() as i64,
            local.day() as i64,
        );
        assert_eq!(
            current_month_range_for_day(local_day),
            ("2026-06-01".to_string(), "2026-06-30".to_string()),
            "local date must produce June range"
        );

        // UTC path would wrongly give May range — confirming the symmetric bug
        let utc = instant.date_naive();
        let utc_day = civil_to_epoch_day(utc.year() as i64, utc.month() as i64, utc.day() as i64);
        assert_eq!(
            current_month_range_for_day(utc_day),
            ("2026-05-01".to_string(), "2026-05-31".to_string()),
            "UTC date produces May range"
        );
    }

    // --- parse_iso_date_to_epoch_day ---

    #[test]
    fn parse_iso_date_round_trips_known_epoch() {
        // 1970-01-01 is day 0
        assert_eq!(parse_iso_date_to_epoch_day("1970-01-01"), Some(0));
    }

    #[test]
    fn parse_iso_date_round_trips_2026_05_15() {
        // 2026-05-15: verify epoch_days_to_ymd(parse(...)) == (2026,5,15)
        let d = parse_iso_date_to_epoch_day("2026-05-15").unwrap();
        assert_eq!(epoch_days_to_ymd(d), (2026, 5, 15));
    }

    #[test]
    fn parse_iso_date_round_trips_2024_02_29_leap() {
        let d = parse_iso_date_to_epoch_day("2024-02-29").unwrap();
        assert_eq!(epoch_days_to_ymd(d), (2024, 2, 29));
    }

    #[test]
    fn parse_iso_date_returns_none_for_too_few_parts() {
        assert_eq!(parse_iso_date_to_epoch_day("2026-13"), None);
    }

    #[test]
    fn parse_iso_date_returns_none_for_garbage() {
        assert_eq!(parse_iso_date_to_epoch_day("garbage"), None);
    }

    #[test]
    fn parse_iso_date_rejects_out_of_range_month() {
        // Month > 12 should be rejected, not silently normalized
        assert_eq!(parse_iso_date_to_epoch_day("2026-13-01"), None);
        assert_eq!(parse_iso_date_to_epoch_day("2026-13-40"), None);
    }

    #[test]
    fn parse_iso_date_rejects_zero_month_and_day() {
        // Month 0, day 0 are invalid
        assert_eq!(parse_iso_date_to_epoch_day("2026-00-00"), None);
        assert_eq!(parse_iso_date_to_epoch_day("2026-00-15"), None);
        assert_eq!(parse_iso_date_to_epoch_day("2026-05-00"), None);
    }

    #[test]
    fn parse_iso_date_rejects_day_past_month_end() {
        // February 30 doesn't exist
        assert_eq!(parse_iso_date_to_epoch_day("2026-02-30"), None);
        // April 31 doesn't exist
        assert_eq!(parse_iso_date_to_epoch_day("2026-04-31"), None);
        // June 31 doesn't exist
        assert_eq!(parse_iso_date_to_epoch_day("2026-06-31"), None);
    }

    #[test]
    fn parse_iso_date_year_range_boundaries() {
        // Pin both edges of the accepted year range (1..=9999) so a mutation that
        // widens or shifts the bound is caught: 0 below the floor, 1 at the floor,
        // 9999 at the ceiling, 10000 just past it.
        assert_eq!(parse_iso_date_to_epoch_day("0000-06-15"), None);
        assert!(parse_iso_date_to_epoch_day("0001-06-15").is_some());
        assert!(parse_iso_date_to_epoch_day("9999-06-15").is_some());
        assert_eq!(parse_iso_date_to_epoch_day("10000-06-15"), None);
    }

    #[test]
    fn parse_iso_date_does_not_panic_on_huge_year() {
        // Must return None instead of panicking on overflow
        assert_eq!(
            parse_iso_date_to_epoch_day("9223372036854775807-06-15"),
            None
        );
        assert_eq!(parse_iso_date_to_epoch_day("999999-06-15"), None);
    }

    #[test]
    fn parse_iso_date_accepts_valid_dates() {
        // Sanity check that we still accept legitimate dates
        assert!(parse_iso_date_to_epoch_day("2026-04-30").is_some());
        assert!(parse_iso_date_to_epoch_day("2024-02-29").is_some());
        assert!(parse_iso_date_to_epoch_day("2026-05-31").is_some());
    }

    // --- current_month_range_for_day ---

    #[test]
    fn current_month_range_last_day_of_may_2026() {
        // The exact bug in issue #34: on 2026-05-31 the range must still be May.
        let (start, end) = current_month_range_for_day(day("2026-05-31"));
        assert_eq!(start, "2026-05-01");
        assert_eq!(end, "2026-05-31");
    }

    #[test]
    fn current_month_range_for_mid_month() {
        let (start, end) = current_month_range_for_day(day("2026-05-15"));
        assert_eq!(start, "2026-05-01");
        assert_eq!(end, "2026-05-31");
    }

    #[test]
    fn current_month_range_leap_february() {
        let (start, end) = current_month_range_for_day(day("2024-02-10"));
        assert_eq!(start, "2024-02-01");
        assert_eq!(end, "2024-02-29");
    }

    #[test]
    fn current_month_range_non_leap_february() {
        let (start, end) = current_month_range_for_day(day("2026-02-10"));
        assert_eq!(start, "2026-02-01");
        assert_eq!(end, "2026-02-28");
    }

    // --- prior_month_range_for_day ---

    #[test]
    fn prior_month_range_last_day_of_may_2026() {
        // The exact bug: on 2026-05-31 the prior range must be April, not March.
        let (start, end) = prior_month_range_for_day(day("2026-05-31"));
        assert_eq!(start, "2026-04-01");
        assert_eq!(end, "2026-04-30");
    }

    #[test]
    fn prior_month_range_crosses_year_boundary() {
        let (start, end) = prior_month_range_for_day(day("2026-01-15"));
        assert_eq!(start, "2025-12-01");
        assert_eq!(end, "2025-12-31");
    }

    #[test]
    fn prior_month_range_march_2024_gives_leap_february() {
        let (start, end) = prior_month_range_for_day(day("2024-03-10"));
        assert_eq!(start, "2024-02-01");
        assert_eq!(end, "2024-02-29");
    }

    // --- months_ago_start_for_day ---

    #[test]
    fn months_ago_start_n0_returns_current_month_start() {
        assert_eq!(months_ago_start_for_day(day("2026-05-15"), 0), "2026-05-01");
    }

    #[test]
    fn months_ago_start_n12_crosses_year() {
        assert_eq!(
            months_ago_start_for_day(day("2026-05-15"), 12),
            "2025-05-01"
        );
    }

    #[test]
    fn months_ago_start_n6_from_february_crosses_year() {
        // 2026-02-15 minus 6 months = 2025-08-01
        assert_eq!(months_ago_start_for_day(day("2026-02-15"), 6), "2025-08-01");
    }

    // --- Large (live) regression tests for issue #47 ---
    //
    // These tests live here (inside the crate) so they can call the private
    // `fetch_and_compute` and `fetch_and_compute_spending` functions directly.
    // An external integration test in `tests/` cannot reach private helpers, so
    // it would be forced to re-implement the fetch pattern inline — a copy that
    // could not detect a revert of the `i32::MAX` fix (ADR 0008, testing-seam
    // decision: prefer in-crate `#[cfg(test)]` over exposing orchestration as
    // `pub(crate)` or `pub`).
    //
    // Gated by `MONARCH_LIVE=1` so `cargo test` and CI remain hermetic.
    // Run with:
    //   MONARCH_LIVE=1 cargo test --lib -- tools::tests::financial_overview_concurrent_burst
    //   MONARCH_LIVE=1 cargo test --lib -- tools::tests::spending_report_concurrent_burst

    /// Verify that the financial_overview fetch path succeeds end-to-end against
    /// the real Monarch API (issue #47).
    ///
    /// Calls the production `fetch_and_compute` function directly so that a revert
    /// of the `i32::MAX` limit back to `u32::MAX` inside
    /// `fetch_current_month_transactions` causes this test to fail (the GraphQL
    /// server rejects the out-of-range value with a server-side error).
    ///
    /// RED evidence (before fix): `u32::MAX` produced:
    ///   GraphQL "Something went wrong while processing: None on request_id: None."
    /// GREEN: `i32::MAX as u32` passes, and this test verifies that invariant holds.
    #[tokio::test]
    async fn financial_overview_concurrent_burst_exercises_production_fetch_path() {
        if std::env::var("MONARCH_LIVE")
            .map(|v| v == "1")
            .unwrap_or(false)
        {
            let base = std::env::var("MONARCH_BASE").ok().filter(|s| !s.is_empty());
            let mut client = crate::client::MonarchClient::new(base);
            client.resolve_token_from_env_or_disk();

            let overview = fetch_and_compute(&client).await.expect(
                "fetch_and_compute must succeed with i32::MAX limit — \
                         if this fails, the i32::MAX fix may have been reverted to u32::MAX",
            );

            // Net-worth fields must be finite — a NaN/Inf would mean the signed-
            // balance sum saw garbage rather than real account data.
            assert!(
                overview.net_worth.is_finite() && overview.net_worth_change.is_finite(),
                "net_worth and net_worth_change must be finite, got {} / {}",
                overview.net_worth,
                overview.net_worth_change,
            );
            // The cashflow block is computed from the transaction slice the
            // i32::MAX fetch returns. Assert the identity net == income − spending
            // holds end-to-end: a partial/garbled transaction response (the failure
            // mode the fix prevents) would break this equality — a non-vacuous check.
            let cf = &overview.cashflow;
            assert!(
                (cf.net - (cf.income - cf.spending)).abs() < 1e-6,
                "cashflow identity net == income − spending must hold: net={}, income={}, spending={}",
                cf.net,
                cf.income,
                cf.spending,
            );
            eprintln!(
                "net_worth: {:.2}, income: {:.2}, spending: {:.2}, net: {:.2}",
                overview.net_worth, cf.income, cf.spending, cf.net,
            );
        } else {
            eprintln!("SKIP: set MONARCH_LIVE=1 to run live integration tests");
        }
    }

    /// Verify that the spending_report fetch path succeeds end-to-end against
    /// the real Monarch API (issue #47).
    ///
    /// Calls the production `fetch_and_compute_spending` function directly so that
    /// a revert of the `i32::MAX` limit back to `u32::MAX` inside
    /// `fetch_current_month_transactions` causes this test to fail.
    #[tokio::test]
    async fn spending_report_concurrent_burst_exercises_production_fetch_path() {
        if std::env::var("MONARCH_LIVE")
            .map(|v| v == "1")
            .unwrap_or(false)
        {
            let base = std::env::var("MONARCH_BASE").ok().filter(|s| !s.is_empty());
            let mut client = crate::client::MonarchClient::new(base);
            client.resolve_token_from_env_or_disk();

            let report = fetch_and_compute_spending(&client).await.expect(
                "fetch_and_compute_spending must succeed with i32::MAX limit — \
                         if this fails, the i32::MAX fix may have been reverted to u32::MAX",
            );

            // total_spent and the per-category report magnitudes are both derived
            // from the same fetched transaction slice (i32::MAX fetch) and apply the
            // same income/transfer exclusions, so they MUST sum equal. This is a
            // real internal-consistency invariant — unlike `>= 0.0`, which is a
            // tautology since total_spent is documented as a positive magnitude.
            let category_sum: f64 = report.by_category.values().map(|c| c.spent).sum();
            assert!(
                (report.total_spent - category_sum).abs() < 1e-6,
                "total_spent must equal the sum of per-category magnitudes: \
                 total_spent={}, category_sum={}",
                report.total_spent,
                category_sum,
            );
            eprintln!(
                "total_spent: {:.2}, category_sum: {:.2}",
                report.total_spent, category_sum,
            );
        } else {
            eprintln!("SKIP: set MONARCH_LIVE=1 to run live integration tests");
        }
    }

    // --- resolve_history_range ---

    #[test]
    fn resolve_history_range_valid_explicit_range_passes_through() {
        let today = day("2026-06-08");
        let result = resolve_history_range(
            today,
            None,
            Some("2026-01-01".into()),
            Some("2026-05-31".into()),
        );
        assert_eq!(
            result,
            Ok(("2026-01-01".to_string(), "2026-05-31".to_string()))
        );
    }

    #[test]
    fn resolve_history_range_garbage_start_returns_err() {
        let today = day("2026-06-08");
        let result = resolve_history_range(
            today,
            None,
            Some("garbage".into()),
            Some("2026-05-31".into()),
        );
        assert!(
            result.is_err(),
            "Expected Err for garbage start, got: {result:?}"
        );
    }

    #[test]
    fn resolve_history_range_garbage_end_returns_err() {
        let today = day("2026-06-08");
        let result = resolve_history_range(
            today,
            None,
            Some("2026-01-01".into()),
            Some("garbage".into()),
        );
        assert!(
            result.is_err(),
            "Expected Err for garbage end, got: {result:?}"
        );
    }

    #[test]
    fn resolve_history_range_invalid_month_13_returns_err() {
        let today = day("2026-06-08");
        let result = resolve_history_range(
            today,
            None,
            Some("2026-13-01".into()),
            Some("2026-05-31".into()),
        );
        assert!(
            result.is_err(),
            "Expected Err for month=13, got: {result:?}"
        );
    }

    #[test]
    fn resolve_history_range_reversed_dates_returns_err() {
        let today = day("2026-06-08");
        let result = resolve_history_range(
            today,
            None,
            Some("2026-05-01".into()),
            Some("2026-01-31".into()),
        );
        assert!(
            result.is_err(),
            "Expected Err for start > end, got: {result:?}"
        );
    }

    #[test]
    fn resolve_history_range_no_explicit_dates_falls_back_to_months_default() {
        let today = day("2026-06-08");
        let result = resolve_history_range(today, None, None, None);
        // Default 6 months before 2026-06 = 2025-12 through 2026-05
        assert_eq!(
            result,
            Ok(("2025-12-01".to_string(), "2026-05-31".to_string()))
        );
    }

    #[test]
    fn resolve_history_range_explicit_months_overrides_default() {
        let today = day("2026-06-08");
        let result = resolve_history_range(today, Some(3), None, None);
        // 3 months before 2026-06 = 2026-03 through 2026-05
        assert_eq!(
            result,
            Ok(("2026-03-01".to_string(), "2026-05-31".to_string()))
        );
    }

    #[test]
    fn resolve_history_range_only_start_date_returns_err() {
        let today = day("2026-06-08");
        let result = resolve_history_range(today, None, Some("2026-01-01".into()), None);
        assert!(
            result.is_err(),
            "Expected Err when only start_date is provided, got: {result:?}"
        );
        let msg = result.unwrap_err();
        assert!(
            msg.contains("start_date"),
            "Error message should mention start_date, got: {msg:?}"
        );
    }

    #[test]
    fn resolve_history_range_only_end_date_returns_err() {
        let today = day("2026-06-08");
        let result = resolve_history_range(today, None, None, Some("2026-05-31".into()));
        assert!(
            result.is_err(),
            "Expected Err when only end_date is provided, got: {result:?}"
        );
        let msg = result.unwrap_err();
        assert!(
            msg.contains("end_date"),
            "Error message should mention end_date, got: {msg:?}"
        );
    }

    // --- audit_window_for_day ---

    #[test]
    fn audit_window_starts_today_and_ends_12_months_forward() {
        // 2026-06-10: start = 2026-06-10, end = last day of 2027-06 = 2027-06-30
        let (start, end) = audit_window_for_day(day("2026-06-10"));
        assert_eq!(start, "2026-06-10");
        assert_eq!(end, "2027-06-30");
    }

    #[test]
    fn audit_window_spans_at_least_12_months() {
        // The end date must be at least 12 months after the start date.
        // Use the first day of a month for easy arithmetic.
        let start_day = day("2026-01-01");
        let (start, end) = audit_window_for_day(start_day);
        assert_eq!(start, "2026-01-01");
        // 12 months forward from January = January of next year, last day = 2027-01-31
        assert_eq!(end, "2027-01-31");

        // Parse end and verify it is >= 12 calendar months after start.
        let end_day = parse_iso_date_to_epoch_day(&end).unwrap();
        // 12 months = at least 365 days
        assert!(
            end_day - start_day >= 365,
            "audit window must span at least 365 days, got {}",
            end_day - start_day
        );
    }

    #[test]
    fn audit_window_crosses_year_boundary_correctly() {
        // 2026-09-15: 12 months forward → end of 2027-09 = 2027-09-30
        let (start, end) = audit_window_for_day(day("2026-09-15"));
        assert_eq!(start, "2026-09-15");
        assert_eq!(end, "2027-09-30");
    }

    #[test]
    fn audit_window_handles_december_start() {
        // 2026-12-01: 12 months forward → end of 2027-12 = 2027-12-31
        let (start, end) = audit_window_for_day(day("2026-12-01"));
        assert_eq!(start, "2026-12-01");
        assert_eq!(end, "2027-12-31");
    }

    #[test]
    fn audit_window_end_has_correct_last_day_for_february() {
        // 2026-02-15: 12 months forward → end of 2027-02 = 2027-02-28 (not leap year)
        let (start, end) = audit_window_for_day(day("2026-02-15"));
        assert_eq!(start, "2026-02-15");
        assert_eq!(end, "2027-02-28");
    }

    #[test]
    fn audit_window_end_has_correct_last_day_for_leap_february() {
        // 2027-02-01: 12 months forward → end of 2028-02 = 2028-02-29 (leap year)
        let (start, end) = audit_window_for_day(day("2027-02-01"));
        assert_eq!(start, "2027-02-01");
        assert_eq!(end, "2028-02-29");
    }
}