rectilinear 0.5.0

Linear issue intelligence tool with hybrid FTS + vector search
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
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
use anyhow::Result;
use rmcp::model::*;
use rmcp::schemars::JsonSchema;
use rmcp::{tool, ServerHandler};
use serde::{Deserialize, Serialize};

use crate::config::Config;
use crate::db::Database;
use crate::embedding::{self, Embedder};
use crate::linear::LinearClient;
use crate::search::{self, SearchMode};

/// Scan a JSON value for issue identifiers (e.g. "CUT-42") and add a `referenced_issues`
/// field with their URLs so agents can render them as clickable links.
fn enrich_with_issue_links(value: &mut serde_json::Value, db: &Database) {
    let text = value.to_string();
    let identifiers = extract_issue_identifiers(&text);
    if identifiers.is_empty() {
        return;
    }

    let mut refs = serde_json::Map::new();
    for ident in &identifiers {
        if let Ok(Some(issue)) = db.get_issue(ident) {
            if !issue.url.is_empty() {
                refs.insert(
                    ident.clone(),
                    serde_json::json!({
                        "url": issue.url,
                        "title": issue.title,
                        "state": issue.state_name,
                    }),
                );
            }
        }
    }

    if !refs.is_empty() {
        if let serde_json::Value::Object(map) = value {
            map.insert(
                "referenced_issues".to_string(),
                serde_json::Value::Object(refs),
            );
        }
    }
}

fn attach_comments_payload(
    value: &mut serde_json::Value,
    db: &Database,
    issue_id: &str,
) -> Result<(), String> {
    let comments = db.get_comments(issue_id).map_err(|e| e.to_string())?;
    let sync_state = db
        .get_comment_sync_state(issue_id)
        .map_err(|e| e.to_string())?;

    value["comments"] = serde_json::to_value(&comments).map_err(|e| e.to_string())?;
    value["comments_status"] = serde_json::Value::String(sync_state.status);
    value["comments_synced_at"] =
        serde_json::to_value(sync_state.synced_at).map_err(|e| e.to_string())?;
    value["comments_sync_error"] =
        serde_json::to_value(sync_state.sync_error).map_err(|e| e.to_string())?;

    Ok(())
}

/// Extract issue identifiers (e.g. "CUT-42", "ENG-123") from text.
/// Matches patterns like 1-4 uppercase letters followed by a dash and digits.
fn extract_issue_identifiers(text: &str) -> Vec<String> {
    let mut result = Vec::new();
    let mut seen = std::collections::HashSet::new();

    let bytes = text.as_bytes();
    let len = bytes.len();
    let mut i = 0;

    while i < len {
        // Look for uppercase letter start
        if bytes[i].is_ascii_uppercase() {
            let start = i;
            // Consume 1-6 uppercase letters
            while i < len && bytes[i].is_ascii_uppercase() {
                i += 1;
            }
            let key_len = i - start;
            if (1..=6).contains(&key_len) && i < len && bytes[i] == b'-' {
                i += 1; // skip dash
                let digit_start = i;
                while i < len && bytes[i].is_ascii_digit() {
                    i += 1;
                }
                if i > digit_start {
                    // Make sure it's not part of a larger word
                    let before_ok = start == 0 || !bytes[start - 1].is_ascii_alphanumeric();
                    let after_ok = i >= len || !bytes[i].is_ascii_alphanumeric();
                    if before_ok && after_ok {
                        let ident = text[start..i].to_string();
                        if seen.insert(ident.clone()) {
                            result.push(ident);
                        }
                    }
                }
            }
        } else {
            i += 1;
        }
    }

    result
}

/// Extract markdown image references from text (e.g., `![alt](url)` or `![](url)`).
fn extract_image_references(text: &str) -> Vec<&str> {
    let mut images = Vec::new();
    let mut remaining = text;
    while let Some(start) = remaining.find("![") {
        if let Some(alt_end) = remaining[start + 2..].find("](") {
            let paren_start = start + 2 + alt_end + 2;
            if let Some(paren_end) = remaining[paren_start..].find(')') {
                let full_end = paren_start + paren_end + 1;
                images.push(&remaining[start..full_end]);
                remaining = &remaining[full_end..];
                continue;
            }
        }
        remaining = &remaining[start + 2..];
    }
    images
}

/// If `new_description` would drop image references present in `original`, append them.
pub(crate) fn preserve_images(original: &str, new_description: &str) -> String {
    let original_images = extract_image_references(original);
    if original_images.is_empty() {
        return new_description.to_string();
    }

    let mut missing: Vec<&str> = Vec::new();
    for img in &original_images {
        if !new_description.contains(img) {
            missing.push(img);
        }
    }

    if missing.is_empty() {
        return new_description.to_string();
    }

    let mut result = new_description.to_string();
    result.push_str("\n\n");
    result.push_str(&missing.join("\n"));
    result
}

/// Extract code-relevant search hints from issue title, description, and labels.
/// Returns terms that Claude should search for in the codebase.
fn extract_code_hints(title: &str, description: &str, labels: &[String]) -> Vec<String> {
    let mut hints = Vec::new();
    let combined = format!("{} {}", title, description);

    // Extract file paths (e.g. src/foo.rs, Components/Bar.swift)
    for word in combined.split_whitespace() {
        let word = word.trim_matches(|c: char| {
            !c.is_alphanumeric() && c != '/' && c != '.' && c != '_' && c != '-'
        });
        if (word.contains('/') && word.contains('.'))
            || word.ends_with(".rs")
            || word.ends_with(".ts")
            || word.ends_with(".swift")
        {
            hints.push(word.to_string());
        }
    }

    // Extract backtick-quoted identifiers (e.g. `WorktreeManager`, `cleanup()`)
    for cap in combined.split('`').collect::<Vec<_>>().chunks(2) {
        if cap.len() == 2 && !cap[1].is_empty() && cap[1].len() < 80 {
            hints.push(cap[1].trim().to_string());
        }
    }

    // Extract PascalCase and snake_case identifiers from title
    for word in title.split_whitespace() {
        let word = word.trim_matches(|c: char| !c.is_alphanumeric() && c != '_');
        // PascalCase: at least 2 uppercase letters with lowercase between
        let upper_count = word.chars().filter(|c| c.is_uppercase()).count();
        if upper_count >= 2
            && word.len() >= 4
            && word.chars().next().is_some_and(|c| c.is_uppercase())
        {
            hints.push(word.to_string());
        }
        // snake_case
        if word.contains('_')
            && word.chars().all(|c| c.is_alphanumeric() || c == '_')
            && word.len() >= 4
        {
            hints.push(word.to_string());
        }
    }

    // Add labels as search terms
    for label in labels {
        if !label.is_empty() {
            hints.push(label.clone());
        }
    }

    // Deduplicate
    hints.sort();
    hints.dedup();
    hints
}

/// Suggest up to 3 label names from the local catalog matching any unknown name as a substring.
/// Returns an empty vec if catalog can't be read or no candidates match.
fn suggest_label_names(db: &Database, workspace: &str, unknown: &[String]) -> Vec<String> {
    let Ok(catalog) = db.list_labels(workspace) else { return Vec::new() };
    let mut hits: Vec<String> = Vec::new();
    for u in unknown {
        let needle = u.to_lowercase();
        for label in &catalog {
            let hay = label.name.to_lowercase();
            if (hay.contains(&needle) || needle.contains(&hay))
                && !hits.contains(&label.name)
            {
                hits.push(label.name.clone());
                if hits.len() >= 3 {
                    return hits;
                }
            }
        }
    }
    hits
}

#[derive(Clone)]
pub struct RectilinearMcp {
    db: Database,
    config: Config,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct ListWorkspacesArgs {}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct ListLabelsArgs {
    /// Workspace name (required). Use list_workspaces to see available workspaces.
    workspace: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct ListProjectsArgs {
    /// Workspace name (required). Use list_workspaces to see available workspaces.
    workspace: Option<String>,
    /// Refresh projects and milestones from Linear before reading. Defaults to true.
    refresh: Option<bool>,
    /// Include archived projects. Defaults to false.
    include_archived: Option<bool>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct GetProjectArgs {
    /// Workspace name (required). Use list_workspaces to see available workspaces.
    workspace: Option<String>,
    /// Project UUID, slug, or name.
    id: String,
    /// Include every milestone and linked issue by importing the full project. Defaults to false.
    include_issues: Option<bool>,
    /// Refresh metadata from Linear before reading. Defaults to true.
    refresh: Option<bool>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct CreateProjectArgs {
    /// Workspace name (required). Use list_workspaces to see available workspaces.
    workspace: Option<String>,
    /// Project name.
    name: String,
    /// Team keys that own the project (for example ["ENG", "IOS"]).
    teams: Vec<String>,
    /// Short project summary.
    description: Option<String>,
    /// Detailed project content in Markdown.
    content: Option<String>,
    /// Linear project icon identifier.
    icon: Option<String>,
    /// Linear project color.
    color: Option<String>,
    /// Project status name or UUID.
    status: Option<String>,
    /// Project priority (0=no priority, 1=urgent, 2=high, 3=medium, 4=low).
    priority: Option<i32>,
    /// Project lead: "me" or a member name.
    lead: Option<String>,
    /// Start date in YYYY-MM-DD format.
    start_date: Option<String>,
    /// Target date in YYYY-MM-DD format.
    target_date: Option<String>,
    /// Project members: each value is "me" or a member name.
    members: Option<Vec<String>>,
    /// Project label names or UUIDs.
    labels: Option<Vec<String>>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct UpdateProjectArgs {
    /// Workspace name (required). Use list_workspaces to see available workspaces.
    workspace: Option<String>,
    /// Project UUID, slug, or current name.
    id: String,
    /// New project name.
    name: Option<String>,
    /// Replacement team keys.
    teams: Option<Vec<String>>,
    /// New short project summary. Pass an empty string to clear.
    description: Option<String>,
    /// New detailed project content. Pass an empty string to clear.
    content: Option<String>,
    /// New icon. Pass "none" to clear.
    icon: Option<String>,
    /// New color. Pass "none" to clear.
    color: Option<String>,
    /// New status name or UUID.
    status: Option<String>,
    /// New project priority.
    priority: Option<i32>,
    /// New lead. Pass "none" to clear.
    lead: Option<String>,
    /// New start date, or "none" to clear.
    start_date: Option<String>,
    /// New target date, or "none" to clear.
    target_date: Option<String>,
    /// Replacement project members.
    members: Option<Vec<String>>,
    /// Replacement project label names or UUIDs. Pass [] to clear.
    labels: Option<Vec<String>>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct DeleteProjectArgs {
    /// Workspace name (required). Use list_workspaces to see available workspaces.
    workspace: Option<String>,
    /// Project UUID, slug, or name.
    id: String,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct ImportProjectArgs {
    /// Workspace name (required). Use list_workspaces to see available workspaces.
    workspace: Option<String>,
    /// Project UUID, slug, or name.
    id: String,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct ListProjectMilestonesArgs {
    /// Workspace name (required). Use list_workspaces to see available workspaces.
    workspace: Option<String>,
    /// Owning project UUID, slug, or name.
    project: String,
    /// Refresh project and milestone metadata from Linear first. Defaults to true.
    refresh: Option<bool>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct GetProjectMilestoneArgs {
    /// Workspace name (required). Use list_workspaces to see available workspaces.
    workspace: Option<String>,
    /// Milestone UUID or name.
    id: String,
    /// Owning project UUID, slug, or name. Recommended when resolving a milestone by name.
    project: Option<String>,
    /// Include all linked issues by importing the full milestone. Defaults to false.
    include_issues: Option<bool>,
    /// Refresh metadata from Linear first. Defaults to true.
    refresh: Option<bool>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct CreateProjectMilestoneArgs {
    /// Workspace name (required). Use list_workspaces to see available workspaces.
    workspace: Option<String>,
    /// Owning project UUID, slug, or name.
    project: String,
    /// Milestone name.
    name: String,
    /// Milestone description.
    description: Option<String>,
    /// Target date in YYYY-MM-DD format.
    target_date: Option<String>,
    /// Position within the project.
    sort_order: Option<f64>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct UpdateProjectMilestoneArgs {
    /// Workspace name (required). Use list_workspaces to see available workspaces.
    workspace: Option<String>,
    /// Milestone UUID or name.
    id: String,
    /// Owning/new project UUID, slug, or name. Also disambiguates milestone names.
    project: Option<String>,
    /// New milestone name.
    name: Option<String>,
    /// New description. Pass an empty string to clear.
    description: Option<String>,
    /// New target date, or "none" to clear.
    target_date: Option<String>,
    /// New position within the project.
    sort_order: Option<f64>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct DeleteProjectMilestoneArgs {
    /// Workspace name (required). Use list_workspaces to see available workspaces.
    workspace: Option<String>,
    /// Milestone UUID or name.
    id: String,
    /// Owning project UUID, slug, or name. Recommended when resolving by name.
    project: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct ImportProjectMilestoneArgs {
    /// Workspace name (required). Use list_workspaces to see available workspaces.
    workspace: Option<String>,
    /// Milestone UUID or name.
    id: String,
    /// Owning project UUID, slug, or name. Recommended when resolving by name.
    project: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct SearchArgs {
    /// Workspace name (required). Use list_workspaces to see available workspaces.
    workspace: Option<String>,
    /// Search query text
    query: String,
    /// Filter by team key (e.g., "ENG")
    team: Option<String>,
    /// Filter by state name
    state: Option<String>,
    /// Search mode: "fts", "vector", or "hybrid"
    mode: Option<String>,
    /// Maximum number of results
    limit: Option<usize>,
    /// Filter to issues that have ALL of these labels (case-insensitive).
    labels: Option<Vec<String>>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct FindDuplicatesArgs {
    /// Workspace name (required). Use list_workspaces to see available workspaces.
    workspace: Option<String>,
    /// Title of the potential new issue
    title: String,
    /// Description of the potential new issue
    description: Option<String>,
    /// Filter by team key
    team: Option<String>,
    /// Minimum similarity threshold (0.0-1.0)
    threshold: Option<f32>,
    /// Maximum number of results
    limit: Option<usize>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct GetIssueArgs {
    /// Workspace name (required). Use list_workspaces to see available workspaces.
    workspace: Option<String>,
    /// Issue ID or identifier (e.g., "ENG-123")
    id: String,
    /// Whether to include comments
    include_comments: Option<bool>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct CreateIssueArgs {
    /// Workspace name (required). Use list_workspaces to see available workspaces.
    workspace: Option<String>,
    /// Team key (e.g., "ENG")
    team: String,
    /// Issue title
    title: String,
    /// Issue description
    description: Option<String>,
    /// Priority: 1=Urgent, 2=High, 3=Medium, 4=Low
    priority: Option<i32>,
    /// Parent issue identifier to create as sub-issue (e.g., "CUT-42")
    parent: Option<String>,
    /// Set labels by name (case-insensitive). Use list_labels to discover.
    labels: Option<Vec<String>>,
    /// Assignee. Pass "me" to assign to the authenticated user, or a name (case-insensitive).
    assignee: Option<String>,
    /// Set project by UUID, slug, or name.
    project: Option<String>,
    /// Set project milestone by UUID or name. Its project is inferred when omitted.
    project_milestone: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct UpdateIssueArgs {
    /// Workspace name (required). Use list_workspaces to see available workspaces.
    workspace: Option<String>,
    /// Issue ID or identifier
    id: String,
    /// New title
    title: Option<String>,
    /// New description
    description: Option<String>,
    /// New priority
    priority: Option<i32>,
    /// Set issue state by name (e.g., "Done", "Cancelled", "In Progress")
    state: Option<String>,
    /// Set labels by name (replaces all existing labels)
    labels: Option<Vec<String>>,
    /// Set project by name (or "none" to remove from project)
    project: Option<String>,
    /// Set project milestone by name/UUID (or "none" to remove from a milestone).
    project_milestone: Option<String>,
    /// Assignee. Pass "me" for self-assign, "none" to clear, or a name (case-insensitive).
    assignee: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct AppendArgs {
    /// Workspace name (required). Use list_workspaces to see available workspaces.
    workspace: Option<String>,
    /// Issue ID or identifier
    id: String,
    /// Comment text to add
    comment: Option<String>,
    /// Text to append to description
    description: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct SyncTeamArgs {
    /// Workspace name (required). Use list_workspaces to see available workspaces.
    workspace: Option<String>,
    /// Team key to sync
    team: String,
    /// Whether to do a full re-sync
    full: Option<bool>,
    /// Include archived Linear issues. Defaults to true for full syncs and false for incremental syncs.
    include_archived: Option<bool>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct IssueContextArgs {
    /// Workspace name (required). Use list_workspaces to see available workspaces.
    workspace: Option<String>,
    /// Issue ID or identifier
    id: String,
    /// Number of similar issues to return
    similar_count: Option<usize>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct GetTriageQueueArgs {
    /// Workspace name (required). Use list_workspaces to see available workspaces.
    workspace: Option<String>,
    /// Team key (e.g., "CUT")
    team: String,
    /// Max issues to return (default 10)
    limit: Option<usize>,
    /// Issue identifiers to skip (already triaged this session)
    exclude: Option<Vec<String>>,
    /// Randomize issue order instead of chronological (default false)
    shuffle: Option<bool>,
    /// Include completed/canceled issues (default false). Useful for archival prioritization.
    include_completed: Option<bool>,
    /// Filter to issues that have ALL of these labels (case-insensitive).
    labels: Option<Vec<String>>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct MarkTriagedArgs {
    /// Workspace name (required). Use list_workspaces to see available workspaces.
    workspace: Option<String>,
    /// Issue identifier (e.g., "CUT-42")
    id: String,
    /// New priority (1=Urgent, 2=High, 3=Medium, 4=Low)
    priority: i32,
    /// Improved title (optional)
    title: Option<String>,
    /// Improved description (optional)
    description: Option<String>,
    /// Triage comment explaining the decision (optional)
    comment: Option<String>,
    /// Set issue state (e.g., "Done", "Cancelled", "Duplicate", "Backlog"). Looked up by name for the issue's team.
    state: Option<String>,
    /// Set labels by name (replaces all existing labels)
    labels: Option<Vec<String>>,
    /// Set project by name (or "none" to remove from project)
    project: Option<String>,
    /// Set project milestone by name/UUID (or "none" to remove from a milestone).
    project_milestone: Option<String>,
    /// Assignee. Pass "me" for self-assign, "none" to clear, or a name (case-insensitive).
    assignee: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct ManageRelationArgs {
    /// Workspace name (required). Use list_workspaces to see available workspaces.
    workspace: Option<String>,
    /// Action: "add" or "remove"
    action: String,
    /// Source issue identifier (e.g., "CUT-42")
    issue: String,
    /// Related issue identifier (e.g., "CUT-99")
    related_issue: String,
    /// Relation type: "blocks", "blocked_by", "related", "duplicate"
    relation_type: String,
}

#[tool(tool_box)]
impl RectilinearMcp {
    pub fn new(db: Database, config: Config) -> Self {
        Self { db, config }
    }

    #[tool(
        name = "list_workspaces",
        description = "List all configured workspaces. Use this to discover available workspace names before calling other tools."
    )]
    async fn list_workspaces(
        &self,
        #[tool(aggr)] _args: ListWorkspacesArgs,
    ) -> Result<String, String> {
        let names = self.config.workspace_names();
        let active = self.config.resolve_active_workspace().ok();

        let mut workspaces = Vec::new();
        for name in &names {
            let ws = self
                .config
                .workspace_config(name)
                .map_err(|e| e.to_string())?;
            let db_info = self.db.get_workspace(name).map_err(|e| e.to_string())?;
            workspaces.push(serde_json::json!({
                "name": name,
                "active": active.as_deref() == Some(name.as_str()),
                "default_team": ws.default_team,
                "org_name": db_info.as_ref().and_then(|w| w.display_name.clone()),
            }));
        }

        serde_json::to_string_pretty(&serde_json::json!({
            "workspaces": workspaces,
            "instruction": "Pass the workspace name to all other tools."
        }))
        .map_err(|e| e.to_string())
    }

    #[tool(
        name = "list_labels",
        description = "List all labels in the workspace, grouped by parent. Pure local read — no Linear API call. If empty, run sync_team to refresh the catalog."
    )]
    async fn list_labels(
        &self,
        #[tool(aggr)] args: ListLabelsArgs,
    ) -> Result<String, String> {
        let workspace = self.require_workspace(&args.workspace)?;
        let labels = self.db.list_labels(&workspace).map_err(|e| e.to_string())?;

        // Index by id for parent name lookup.
        let by_id: std::collections::HashMap<&str, &str> =
            labels.iter().map(|l| (l.id.as_str(), l.name.as_str())).collect();

        // Group: top-level (no parent) and grouped-by-parent.
        let mut top_level: Vec<&_> = labels.iter().filter(|l| l.parent_id.is_none()).collect();
        top_level.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));

        let mut groups: std::collections::BTreeMap<String, Vec<&_>> = std::collections::BTreeMap::new();
        for l in labels.iter().filter(|l| l.parent_id.is_some()) {
            let parent_name = l.parent_id.as_deref()
                .and_then(|pid| by_id.get(pid).copied())
                .unwrap_or("(unknown group)")
                .to_string();
            groups.entry(parent_name).or_default().push(l);
        }
        for v in groups.values_mut() {
            v.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
        }

        let payload = serde_json::json!({
            "workspace": workspace,
            "count": labels.len(),
            "top_level": top_level.iter().map(|l| serde_json::json!({
                "name": l.name,
                "color": l.color,
            })).collect::<Vec<_>>(),
            "groups": groups.iter().map(|(parent, members)| serde_json::json!({
                "parent": parent,
                "labels": members.iter().map(|l| serde_json::json!({
                    "name": l.name,
                    "color": l.color,
                })).collect::<Vec<_>>(),
            })).collect::<Vec<_>>(),
            "note": if labels.is_empty() {
                "Catalog is empty. Run sync_team to populate labels."
            } else { "" },
        });

        serde_json::to_string_pretty(&payload).map_err(|e| e.to_string())
    }

    #[tool(
        name = "list_projects",
        description = "List Linear projects with their status, dates, lead, teams, members, labels, progress, and other metadata. Refreshes the local project/milestone mirror by default."
    )]
    async fn list_projects(
        &self,
        #[tool(aggr)] args: ListProjectsArgs,
    ) -> Result<String, String> {
        let workspace = self.require_workspace(&args.workspace)?;
        if args.refresh.unwrap_or(true) {
            let client = self.client_for_workspace(&workspace)?;
            client
                .sync_projects(&self.db, &workspace)
                .await
                .map_err(|error| error.to_string())?;
        }
        let projects = self
            .db
            .list_projects(&workspace, args.include_archived.unwrap_or(false))
            .map_err(|error| error.to_string())?;
        serde_json::to_string_pretty(&serde_json::json!({
            "workspace": workspace,
            "count": projects.len(),
            "projects": projects,
        }))
        .map_err(|error| error.to_string())
    }

    #[tool(
        name = "get_project",
        description = "Get a Linear project and its milestones. Set include_issues=true to refresh and return the complete importable project bundle with every linked issue."
    )]
    async fn get_project(
        &self,
        #[tool(aggr)] args: GetProjectArgs,
    ) -> Result<String, String> {
        let workspace = self.require_workspace(&args.workspace)?;
        let client = self.client_for_workspace(&workspace)?;
        if args.include_issues.unwrap_or(false) {
            let bundle = client
                .import_project(&self.db, &workspace, &args.id)
                .await
                .map_err(|error| error.to_string())?;
            return serde_json::to_string_pretty(&bundle).map_err(|error| error.to_string());
        }
        if args.refresh.unwrap_or(true) {
            client
                .sync_projects(&self.db, &workspace)
                .await
                .map_err(|error| error.to_string())?;
        }
        let bundle = self
            .db
            .get_project_bundle(&workspace, &args.id)
            .map_err(|error| error.to_string())?
            .ok_or_else(|| format!("Project '{}' not found", args.id))?;
        serde_json::to_string_pretty(&serde_json::json!({
            "project": bundle.project,
            "milestones": bundle.milestones,
        }))
        .map_err(|error| error.to_string())
    }

    #[tool(
        name = "create_project",
        description = "Create a Linear project with first-class status, priority, lead, team, membership, label, date, icon, color, summary, and detailed-content metadata."
    )]
    async fn create_project(
        &self,
        #[tool(aggr)] args: CreateProjectArgs,
    ) -> Result<String, String> {
        let workspace = self.require_workspace(&args.workspace)?;
        let client = self.client_for_workspace(&workspace)?;
        let team_ids = self.resolve_team_ids(&client, &args.teams).await?;
        let status_id = match args.status.as_deref() {
            Some(status) => Some(
                client
                    .get_project_status_id(status)
                    .await
                    .map_err(|error| error.to_string())?,
            ),
            None => None,
        };
        let lead_id = match args.lead.as_deref() {
            Some(lead) if lead.eq_ignore_ascii_case("none") => {
                return Err("Cannot clear a lead while creating a project; omit lead instead.".into())
            }
            Some(lead) => Some(
                client
                    .resolve_assignee_id(lead)
                    .await
                    .map_err(|error| error.to_string())?,
            ),
            None => None,
        };
        let member_ids = match args.members.as_deref() {
            Some(members) => Some(self.resolve_member_ids(&client, members).await?),
            None => None,
        };
        let label_ids = match args.labels.as_deref() {
            Some(labels) => Some(
                client
                    .get_project_label_ids(labels)
                    .await
                    .map_err(|error| error.to_string())?,
            ),
            None => None,
        };
        let input = crate::linear::CreateProjectInput {
            name: args.name,
            team_ids,
            description: args.description,
            content: args.content,
            icon: args.icon,
            color: args.color,
            status_id,
            priority: args.priority,
            lead_id,
            start_date: args.start_date,
            target_date: args.target_date,
            member_ids,
            label_ids,
        };
        let project_id = client
            .create_project(&input)
            .await
            .map_err(|error| error.to_string())?;
        let project = client
            .fetch_project(&project_id, &workspace)
            .await
            .map_err(|error| error.to_string())?;
        self.db
            .upsert_project(&project)
            .map_err(|error| error.to_string())?;
        serde_json::to_string_pretty(&serde_json::json!({
            "status": "created",
            "project": project,
        }))
        .map_err(|error| error.to_string())
    }

    #[tool(
        name = "update_project",
        description = "Update a Linear project's metadata. Empty strings clear descriptions/content; use 'none' to clear nullable lead, date, icon, or color fields."
    )]
    async fn update_project(
        &self,
        #[tool(aggr)] args: UpdateProjectArgs,
    ) -> Result<String, String> {
        let workspace = self.require_workspace(&args.workspace)?;
        let client = self.client_for_workspace(&workspace)?;
        let project_id = self.resolve_project_id(&client, &workspace, &args.id).await?;
        let team_ids = match args.teams.as_deref() {
            Some(teams) => Some(self.resolve_team_ids(&client, teams).await?),
            None => None,
        };
        let status_id = match args.status.as_deref() {
            Some(status) if status.eq_ignore_ascii_case("none") => {
                return Err("A project must have a status; choose a status instead of 'none'.".into())
            }
            Some(status) => Some(
                client
                    .get_project_status_id(status)
                    .await
                    .map_err(|error| error.to_string())?,
            ),
            None => None,
        };
        let lead_id = match args.lead.as_deref() {
            Some(lead) => Some(
                client
                    .resolve_assignee_id(lead)
                    .await
                    .map_err(|error| error.to_string())?,
            ),
            None => None,
        };
        let member_ids = match args.members.as_deref() {
            Some(members) => Some(self.resolve_member_ids(&client, members).await?),
            None => None,
        };
        let label_ids = match args.labels.as_deref() {
            Some(labels) => Some(
                client
                    .get_project_label_ids(labels)
                    .await
                    .map_err(|error| error.to_string())?,
            ),
            None => None,
        };
        let input = crate::linear::UpdateProjectInput {
            name: args.name,
            team_ids,
            description: args.description,
            content: args.content,
            icon: args.icon,
            color: args.color,
            status_id,
            priority: args.priority,
            lead_id,
            start_date: args.start_date,
            target_date: args.target_date,
            member_ids,
            label_ids,
        };
        client
            .update_project(&project_id, &input)
            .await
            .map_err(|error| error.to_string())?;
        let project = client
            .fetch_project(&project_id, &workspace)
            .await
            .map_err(|error| error.to_string())?;
        self.db
            .upsert_project(&project)
            .map_err(|error| error.to_string())?;
        serde_json::to_string_pretty(&serde_json::json!({
            "status": "updated",
            "project": project,
        }))
        .map_err(|error| error.to_string())
    }

    #[tool(
        name = "delete_project",
        description = "Delete (archive) a Linear project and remove its cached project/milestone hierarchy from Rectilinear. Linked issues remain cached."
    )]
    async fn delete_project(
        &self,
        #[tool(aggr)] args: DeleteProjectArgs,
    ) -> Result<String, String> {
        let workspace = self.require_workspace(&args.workspace)?;
        let client = self.client_for_workspace(&workspace)?;
        let project_id = self.resolve_project_id(&client, &workspace, &args.id).await?;
        client
            .delete_project(&project_id)
            .await
            .map_err(|error| error.to_string())?;
        self.db
            .delete_project_local(&project_id)
            .map_err(|error| error.to_string())?;
        Ok(serde_json::json!({
            "status": "deleted",
            "project_id": project_id,
        })
        .to_string())
    }

    #[tool(
        name = "import_project",
        description = "Import a complete Linear project into Rectilinear and return one portable bundle containing project metadata, ordered milestones, and every linked issue across teams."
    )]
    async fn import_project(
        &self,
        #[tool(aggr)] args: ImportProjectArgs,
    ) -> Result<String, String> {
        let workspace = self.require_workspace(&args.workspace)?;
        let client = self.client_for_workspace(&workspace)?;
        let bundle = client
            .import_project(&self.db, &workspace, &args.id)
            .await
            .map_err(|error| error.to_string())?;
        serde_json::to_string_pretty(&bundle).map_err(|error| error.to_string())
    }

    #[tool(
        name = "list_project_milestones",
        description = "List ordered milestones and progress metadata for a Linear project. Refreshes the project hierarchy from Linear by default."
    )]
    async fn list_project_milestones(
        &self,
        #[tool(aggr)] args: ListProjectMilestonesArgs,
    ) -> Result<String, String> {
        let workspace = self.require_workspace(&args.workspace)?;
        let client = self.client_for_workspace(&workspace)?;
        if args.refresh.unwrap_or(true) {
            client
                .sync_projects(&self.db, &workspace)
                .await
                .map_err(|error| error.to_string())?;
        }
        let project_id = self
            .resolve_project_id(&client, &workspace, &args.project)
            .await?;
        let milestones = self
            .db
            .list_project_milestones(&project_id)
            .map_err(|error| error.to_string())?;
        serde_json::to_string_pretty(&serde_json::json!({
            "project_id": project_id,
            "count": milestones.len(),
            "milestones": milestones,
        }))
        .map_err(|error| error.to_string())
    }

    #[tool(
        name = "get_project_milestone",
        description = "Get a Linear project milestone. Set include_issues=true to refresh and return the complete importable milestone bundle with every linked issue."
    )]
    async fn get_project_milestone(
        &self,
        #[tool(aggr)] args: GetProjectMilestoneArgs,
    ) -> Result<String, String> {
        let workspace = self.require_workspace(&args.workspace)?;
        let client = self.client_for_workspace(&workspace)?;
        let project_id = match args.project.as_deref() {
            Some(project) => Some(
                self.resolve_project_id(&client, &workspace, project)
                    .await?,
            ),
            None => None,
        };
        if args.include_issues.unwrap_or(false) {
            let bundle = client
                .import_project_milestone(
                    &self.db,
                    &workspace,
                    project_id.as_deref(),
                    &args.id,
                )
                .await
                .map_err(|error| error.to_string())?;
            return serde_json::to_string_pretty(&bundle).map_err(|error| error.to_string());
        }
        if args.refresh.unwrap_or(true) {
            client
                .sync_projects(&self.db, &workspace)
                .await
                .map_err(|error| error.to_string())?;
        }
        let milestone = self
            .db
            .get_project_milestone(&workspace, &args.id, project_id.as_deref())
            .map_err(|error| error.to_string())?
            .ok_or_else(|| format!("Project milestone '{}' not found", args.id))?;
        serde_json::to_string_pretty(&milestone).map_err(|error| error.to_string())
    }

    #[tool(
        name = "create_project_milestone",
        description = "Create a milestone within a Linear project, including description, target date, and ordering metadata."
    )]
    async fn create_project_milestone(
        &self,
        #[tool(aggr)] args: CreateProjectMilestoneArgs,
    ) -> Result<String, String> {
        let workspace = self.require_workspace(&args.workspace)?;
        let client = self.client_for_workspace(&workspace)?;
        let project_id = self
            .resolve_project_id(&client, &workspace, &args.project)
            .await?;
        let input = crate::linear::CreateProjectMilestoneInput {
            project_id: project_id.clone(),
            name: args.name,
            description: args.description,
            target_date: args.target_date,
            sort_order: args.sort_order,
        };
        let milestone_id = client
            .create_project_milestone(&input)
            .await
            .map_err(|error| error.to_string())?;
        self.cache_project_and_milestone(&client, &workspace, &milestone_id)
            .await?;
        let milestone = self
            .db
            .get_project_milestone(&workspace, &milestone_id, Some(&project_id))
            .map_err(|error| error.to_string())?
            .ok_or_else(|| "Created milestone was not cached".to_string())?;
        serde_json::to_string_pretty(&serde_json::json!({
            "status": "created",
            "milestone": milestone,
        }))
        .map_err(|error| error.to_string())
    }

    #[tool(
        name = "update_project_milestone",
        description = "Update or move a Linear project milestone. Empty description clears it; use 'none' to clear the target date."
    )]
    async fn update_project_milestone(
        &self,
        #[tool(aggr)] args: UpdateProjectMilestoneArgs,
    ) -> Result<String, String> {
        let workspace = self.require_workspace(&args.workspace)?;
        let client = self.client_for_workspace(&workspace)?;
        let project_id = match args.project.as_deref() {
            Some(project) => Some(
                self.resolve_project_id(&client, &workspace, project)
                    .await?,
            ),
            None => None,
        };
        let milestone_id = self
            .resolve_milestone_id(
                &client,
                &workspace,
                project_id.as_deref(),
                &args.id,
            )
            .await?;
        let input = crate::linear::UpdateProjectMilestoneInput {
            project_id,
            name: args.name,
            description: args.description,
            target_date: args.target_date,
            sort_order: args.sort_order,
        };
        client
            .update_project_milestone(&milestone_id, &input)
            .await
            .map_err(|error| error.to_string())?;
        self.cache_project_and_milestone(&client, &workspace, &milestone_id)
            .await?;
        let milestone = self
            .db
            .get_project_milestone(&workspace, &milestone_id, None)
            .map_err(|error| error.to_string())?
            .ok_or_else(|| "Updated milestone was not cached".to_string())?;
        serde_json::to_string_pretty(&serde_json::json!({
            "status": "updated",
            "milestone": milestone,
        }))
        .map_err(|error| error.to_string())
    }

    #[tool(
        name = "delete_project_milestone",
        description = "Delete a Linear project milestone and remove it from Rectilinear's local hierarchy. Linked issues remain cached."
    )]
    async fn delete_project_milestone(
        &self,
        #[tool(aggr)] args: DeleteProjectMilestoneArgs,
    ) -> Result<String, String> {
        let workspace = self.require_workspace(&args.workspace)?;
        let client = self.client_for_workspace(&workspace)?;
        let project_id = match args.project.as_deref() {
            Some(project) => Some(
                self.resolve_project_id(&client, &workspace, project)
                    .await?,
            ),
            None => None,
        };
        let milestone_id = self
            .resolve_milestone_id(
                &client,
                &workspace,
                project_id.as_deref(),
                &args.id,
            )
            .await?;
        client
            .delete_project_milestone(&milestone_id)
            .await
            .map_err(|error| error.to_string())?;
        self.db
            .delete_project_milestone_local(&milestone_id)
            .map_err(|error| error.to_string())?;
        Ok(serde_json::json!({
            "status": "deleted",
            "milestone_id": milestone_id,
        })
        .to_string())
    }

    #[tool(
        name = "import_project_milestone",
        description = "Import a complete Linear milestone into Rectilinear and return one portable bundle containing its project metadata, milestone metadata, and every linked issue."
    )]
    async fn import_project_milestone(
        &self,
        #[tool(aggr)] args: ImportProjectMilestoneArgs,
    ) -> Result<String, String> {
        let workspace = self.require_workspace(&args.workspace)?;
        let client = self.client_for_workspace(&workspace)?;
        let project_id = match args.project.as_deref() {
            Some(project) => Some(
                self.resolve_project_id(&client, &workspace, project)
                    .await?,
            ),
            None => None,
        };
        let bundle = client
            .import_project_milestone(
                &self.db,
                &workspace,
                project_id.as_deref(),
                &args.id,
            )
            .await
            .map_err(|error| error.to_string())?;
        serde_json::to_string_pretty(&bundle).map_err(|error| error.to_string())
    }

    #[tool(
        name = "search_issues",
        description = "Search Linear issues using hybrid FTS + vector search. Supports filtering by team and state."
    )]
    async fn search_issues(&self, #[tool(aggr)] args: SearchArgs) -> Result<String, String> {
        let workspace = self.require_workspace(&args.workspace)?;
        let mode: SearchMode = args
            .mode
            .as_deref()
            .unwrap_or("hybrid")
            .parse()
            .map_err(|e: anyhow::Error| e.to_string())?;

        let limit = args.limit.unwrap_or(self.config.search.default_limit);

        let embedder = if mode != SearchMode::Fts {
            Embedder::new(&self.config).ok()
        } else {
            None
        };

        let label_ids = if let Some(ref names) = args.labels {
            let (resolved, unknown) = self.db
                .resolve_label_ids_local(&workspace, names)
                .map_err(|e| e.to_string())?;
            if !unknown.is_empty() {
                if resolved.is_empty()
                    && self.db.list_labels(&workspace).map_err(|e| e.to_string())?.is_empty()
                {
                    return Err(format!(
                        "No labels synced yet for workspace '{}'. Run sync_team first.",
                        workspace
                    ));
                }
                let suggestions = suggest_label_names(&self.db, &workspace, &unknown);
                return Err(format!(
                    "Label{} {} not found. {}Run list_labels for the full set.",
                    if unknown.len() == 1 { "" } else { "s" },
                    unknown.iter().map(|s| format!("'{}'", s)).collect::<Vec<_>>().join(", "),
                    if suggestions.is_empty() { String::new() }
                    else { format!("Did you mean: {}? ", suggestions.join(", ")) }
                ));
            }
            Some(resolved)
        } else {
            None
        };

        let results = search::search(
            &self.db,
            search::SearchParams {
                query: &args.query,
                mode,
                team_key: args.team.as_deref(),
                state_filter: args.state.as_deref(),
                label_ids: label_ids.as_deref(),
                limit,
                embedder: embedder.as_ref(),
                rrf_k: self.config.search.rrf_k,
                workspace_id: &workspace,
            },
        )
        .await
        .map_err(|e| e.to_string())?;

        serde_json::to_string_pretty(&results).map_err(|e| e.to_string())
    }

    #[tool(
        name = "find_duplicates",
        description = "Find potential duplicate issues. Provide a title and optional description to find similar existing issues with similarity scores."
    )]
    async fn find_duplicates(
        &self,
        #[tool(aggr)] args: FindDuplicatesArgs,
    ) -> Result<String, String> {
        let workspace = self.require_workspace(&args.workspace)?;
        let embedder = Embedder::new(&self.config).map_err(|e| e.to_string())?;

        let search_text = if let Some(ref desc) = args.description {
            format!("{}\n\n{}", args.title, desc)
        } else {
            args.title.clone()
        };

        let threshold = args
            .threshold
            .unwrap_or(self.config.search.duplicate_threshold);
        let limit = args.limit.unwrap_or(10);

        let results = search::find_duplicates(
            &self.db,
            &search_text,
            args.team.as_deref(),
            threshold,
            limit,
            &embedder,
            self.config.search.rrf_k,
            &workspace,
        )
        .await
        .map_err(|e| e.to_string())?;

        serde_json::to_string_pretty(&results).map_err(|e| e.to_string())
    }

    #[tool(
        name = "get_issue",
        description = "Get full details of an issue by ID or identifier (e.g., 'ENG-123'). Includes description, state, priority, labels, relations, and optionally comments. With include_comments=true, Rectilinear returns comments plus comments_status/comments_synced_at/comments_sync_error so an empty comments array is explicit: 'none_found' means Linear returned no comments, 'not_synced' means comments have not been fetched, 'permission_denied' or 'unavailable' means Linear could not provide them. Falls back to fetching from Linear API, including archived issues, if not found locally."
    )]
    async fn get_issue(&self, #[tool(aggr)] args: GetIssueArgs) -> Result<String, String> {
        let workspace = self.require_workspace(&args.workspace)?;
        let issue = match self.db.get_issue(&args.id).map_err(|e| e.to_string())? {
            Some(issue) => issue,
            None => {
                // Not found locally — try fetching from Linear API by identifier
                let client = self.client_for_workspace(&workspace)?;
                let result = client
                    .fetch_issue_by_identifier(&args.id)
                    .await
                    .map_err(|e| e.to_string())?;
                match result {
                    Some((mut issue, relations, label_ids)) => {
                        issue.workspace_id = workspace.clone();
                        self.db.upsert_issue(&issue).map_err(|e| e.to_string())?;
                        self.db
                            .upsert_relations(&issue.id, &relations)
                            .map_err(|e| e.to_string())?;
                        self.db
                            .replace_issue_labels(&issue.id, &label_ids)
                            .map_err(|e| e.to_string())?;
                        issue
                    }
                    None => return Err(format!("Issue '{}' not found", args.id)),
                }
            }
        };

        let mut value = serde_json::to_value(&issue).map_err(|e| e.to_string())?;

        let relations = self
            .db
            .get_relations_enriched(&issue.id)
            .map_err(|e| e.to_string())?;
        if !relations.is_empty() {
            value["relations"] = serde_json::to_value(&relations).map_err(|e| e.to_string())?;
        }

        if args.include_comments.unwrap_or(false) {
            self.ensure_comments_synced_if_needed(&workspace, &issue.id)
                .await?;
            attach_comments_payload(&mut value, &self.db, &issue.id)?;
        }

        enrich_with_issue_links(&mut value, &self.db);
        serde_json::to_string_pretty(&value).map_err(|e| e.to_string())
    }

    #[tool(
        name = "create_issue",
        description = "Create a new issue in Linear. Specify team (key like 'ENG'), title, and optionally description, priority (1=Urgent, 2=High, 3=Medium, 4=Low), labels (list of names), assignee ('me' for self-assign, or a user's display name), project, and project milestone.

IMPORTANT — Before calling this tool, you MUST:

1. **Disambiguate the request.** Ask the user 2-4 clarifying questions to sharpen scope, acceptance criteria, and edge cases. Think like a principal engineer: what assumptions are you making? What could go wrong? What's in vs. out of scope? Do not create the issue until the user has answered.

2. **Check for duplicates.** Call find_duplicates with the intended title/description to verify this issue doesn't already exist. If a match is found (>0.8 similarity), show it to the user and ask whether to proceed, update the existing issue, or cancel.

3. **Write a clear title and description.** The title should be imperative and specific (e.g. 'Add rate limiting to /api/upload endpoint' not 'rate limiting'). The description should include: what the desired behavior is, why it matters, and any constraints or acceptance criteria surfaced during disambiguation."
    )]
    async fn create_issue(&self, #[tool(aggr)] args: CreateIssueArgs) -> Result<String, String> {
        let workspace = self.require_workspace(&args.workspace)?;
        let client = self.client_for_workspace(&workspace)?;

        let team_id = client
            .get_team_id(&args.team)
            .await
            .map_err(|e| e.to_string())?;

        let parent_id = if let Some(ref parent_ident) = args.parent {
            let parent = self
                .db
                .get_issue(parent_ident)
                .map_err(|e| e.to_string())?
                .ok_or_else(|| format!("Parent issue '{}' not found", parent_ident))?;
            Some(parent.id)
        } else {
            None
        };

        let label_ids: Vec<String> = if let Some(ref names) = args.labels {
            self.resolve_labels_for_mutation(&workspace, &client, names).await?
        } else {
            Vec::new()
        };

        // Resolve assignee.
        let assignee_id: Option<String> = if let Some(ref a) = args.assignee {
            if a.eq_ignore_ascii_case("none") {
                return Err("Cannot use 'none' on create_issue; omit the parameter to leave unassigned.".to_string());
            }
            Some(client.resolve_assignee_id(a).await.map_err(|e| e.to_string())?)
        } else {
            None
        };

        let mut project_id = match args.project.as_deref() {
            Some(value) => Some(self.resolve_project_id(&client, &workspace, value).await?),
            None => None,
        };
        let project_milestone_id = match args.project_milestone.as_deref() {
            Some(value) => {
                let milestone_id = self
                    .resolve_milestone_id(
                        &client,
                        &workspace,
                        project_id.as_deref(),
                        value,
                    )
                    .await?;
                let milestone = client
                    .fetch_project_milestone(&milestone_id, &workspace)
                    .await
                    .map_err(|error| error.to_string())?;
                if project_id.is_none() {
                    project_id = Some(milestone.project_id);
                }
                Some(milestone_id)
            }
            None => None,
        };

        let (issue_id, identifier) = client
            .create_issue(crate::linear::CreateIssueInput {
                team_id: &team_id,
                title: &args.title,
                description: args.description.as_deref(),
                priority: args.priority,
                label_ids: &label_ids,
                assignee_id: assignee_id.as_deref(),
                parent_id: parent_id.as_deref(),
                project_id: project_id.as_deref(),
                project_milestone_id: project_milestone_id.as_deref(),
            })
            .await
            .map_err(|e| e.to_string())?;

        let (issue, relations, label_ids) = client
            .fetch_single_issue(&issue_id)
            .await
            .map_err(|e| e.to_string())?;
        self.db.upsert_issue(&issue).map_err(|e| e.to_string())?;
        self.db
            .upsert_relations(&issue.id, &relations)
            .map_err(|e| e.to_string())?;
        self.db
            .replace_issue_labels(&issue.id, &label_ids)
            .map_err(|e| e.to_string())?;

        Ok(serde_json::json!({
            "id": issue_id,
            "identifier": identifier,
            "url": issue.url,
            "status": "created"
        })
        .to_string())
    }

    #[tool(
        name = "update_issue",
        description = "Update an existing Linear issue. Provide the issue ID/identifier and fields to update. Prefer append_to_issue for adding context. Image references in the original description are automatically preserved when updating."
    )]
    async fn update_issue(&self, #[tool(aggr)] args: UpdateIssueArgs) -> Result<String, String> {
        let workspace = self.require_workspace(&args.workspace)?;
        let issue = self
            .db
            .get_issue(&args.id)
            .map_err(|e| e.to_string())?
            .ok_or_else(|| format!("Issue '{}' not found", args.id))?;

        let client = self.client_for_workspace(&workspace)?;

        let state_id = if let Some(ref state_name) = args.state {
            Some(
                client
                    .get_state_id(&issue.team_key, state_name)
                    .await
                    .map_err(|e| e.to_string())?,
            )
        } else {
            None
        };

        let label_ids = if let Some(ref label_names) = args.labels {
            Some(self.resolve_labels_for_mutation(&workspace, &client, label_names).await?)
        } else {
            None
        };

        let mut project_id = if let Some(ref project_name) = args.project {
            if project_name.eq_ignore_ascii_case("none") {
                Some(String::new()) // Empty string removes project in Linear
            } else {
                Some(
                    client
                        .get_project_id(project_name)
                        .await
                        .map_err(|e| e.to_string())?,
                )
            }
        } else {
            None
        };

        let project_milestone_id = if let Some(ref milestone_name) = args.project_milestone {
            if milestone_name.eq_ignore_ascii_case("none") {
                Some(String::new())
            } else {
                if project_id.as_deref() == Some("") {
                    return Err("Cannot assign a milestone while removing the issue's project.".into());
                }
                let owning_project_id = project_id
                    .as_deref()
                    .filter(|id| !id.is_empty())
                    .or(issue.project_id.as_deref());
                let milestone_id = client
                    .find_project_milestone(owning_project_id, milestone_name)
                    .await
                    .map_err(|e| e.to_string())?;
                let milestone = client
                    .fetch_project_milestone(&milestone_id, &workspace)
                    .await
                    .map_err(|e| e.to_string())?;
                if project_id.is_none() && issue.project_id.as_deref() != Some(&milestone.project_id) {
                    project_id = Some(milestone.project_id);
                }
                Some(milestone_id)
            }
        } else {
            None
        };

        let assignee_id: Option<String> = if let Some(ref a) = args.assignee {
            Some(client.resolve_assignee_id(a).await.map_err(|e| e.to_string())?)
        } else {
            None
        };

        // If updating description, re-fetch from Linear to preserve any image references
        let safe_description = if args.description.is_some() {
            let (latest, _, _) = client
                .fetch_single_issue(&issue.id)
                .await
                .map_err(|e| e.to_string())?;
            args.description
                .as_ref()
                .map(|new_desc| match &latest.description {
                    Some(original) => preserve_images(original, new_desc),
                    None => new_desc.clone(),
                })
        } else {
            None
        };

        client
            .update_issue(
                &issue.id,
                crate::linear::UpdateIssueInput {
                    title: args.title.as_deref(),
                    description: safe_description.as_deref(),
                    priority: args.priority,
                    state_id: state_id.as_deref(),
                    label_ids: label_ids.as_deref(),
                    project_id: project_id.as_deref(),
                    assignee_id: assignee_id.as_deref(),
                    project_milestone_id: project_milestone_id.as_deref(),
                },
            )
            .await
            .map_err(|e| e.to_string())?;

        let (mut updated, relations, label_ids) = client
            .fetch_single_issue(&issue.id)
            .await
            .map_err(|e| e.to_string())?;
        updated.workspace_id = workspace.clone();
        self.db.upsert_issue(&updated).map_err(|e| e.to_string())?;
        self.db
            .upsert_relations(&updated.id, &relations)
            .map_err(|e| e.to_string())?;
        self.db
            .replace_issue_labels(&updated.id, &label_ids)
            .map_err(|e| e.to_string())?;

        Ok(serde_json::json!({
            "identifier": issue.identifier,
            "url": issue.url,
            "status": "updated"
        })
        .to_string())
    }

    #[tool(
        name = "append_to_issue",
        description = "Add a comment to an issue or append text to its description."
    )]
    async fn append_to_issue(&self, #[tool(aggr)] args: AppendArgs) -> Result<String, String> {
        let workspace = self.require_workspace(&args.workspace)?;
        let issue = self
            .db
            .get_issue(&args.id)
            .map_err(|e| e.to_string())?
            .ok_or_else(|| format!("Issue '{}' not found", args.id))?;

        let client = self.client_for_workspace(&workspace)?;
        let mut actions: Vec<&str> = Vec::new();

        if let Some(ref comment_text) = args.comment {
            client
                .add_comment(&issue.id, comment_text)
                .await
                .map_err(|e| e.to_string())?;
            let _ = client
                .sync_issue_comments(&self.db, &issue.id, &workspace)
                .await;
            actions.push("comment_added");
        }

        if let Some(ref desc_text) = args.description {
            let new_desc = match &issue.description {
                Some(existing) => format!("{}\n\n{}", existing, desc_text),
                None => desc_text.clone(),
            };
            client
                .update_issue(
                    &issue.id,
                    crate::linear::UpdateIssueInput {
                        description: Some(&new_desc),
                        ..Default::default()
                    },
                )
                .await
                .map_err(|e| e.to_string())?;
            actions.push("description_updated");
        }

        let (mut updated, relations, label_ids) = client
            .fetch_single_issue(&issue.id)
            .await
            .map_err(|e| e.to_string())?;
        updated.workspace_id = workspace.clone();
        self.db.upsert_issue(&updated).map_err(|e| e.to_string())?;
        self.db
            .upsert_relations(&updated.id, &relations)
            .map_err(|e| e.to_string())?;
        self.db
            .replace_issue_labels(&updated.id, &label_ids)
            .map_err(|e| e.to_string())?;

        Ok(serde_json::json!({
            "identifier": issue.identifier,
            "actions": actions
        })
        .to_string())
    }

    #[tool(
        name = "sync_team",
        description = "Sync issues from Linear for a specific team. Use full=true for a complete re-sync; full syncs include archived issues by default so completed/canceled archived evidence issues are refreshed. Each synced issue also refreshes Linear comments and records comment sync diagnostics for get_issue(include_comments=true)."
    )]
    async fn sync_team(&self, #[tool(aggr)] args: SyncTeamArgs) -> Result<String, String> {
        let workspace = self.require_workspace(&args.workspace)?;
        let client = self.client_for_workspace(&workspace)?;
        let full = args.full.unwrap_or(false);
        let include_archived = args.include_archived.unwrap_or(full);

        let count = client
            .sync_team(&self.db, &args.team, &workspace, full, include_archived, None)
            .await
            .map_err(|e| e.to_string())?;

        let total = self
            .db
            .count_issues(Some(&args.team), &workspace)
            .map_err(|e| e.to_string())?;

        Ok(serde_json::json!({
            "synced": count,
            "total": total,
            "team": args.team,
            "include_archived": include_archived
        })
        .to_string())
    }

    #[tool(
        name = "issue_context",
        description = "Get an issue along with its N most similar issues, useful for understanding context and related work."
    )]
    async fn issue_context(&self, #[tool(aggr)] args: IssueContextArgs) -> Result<String, String> {
        let workspace = self.require_workspace(&args.workspace)?;
        let issue = self
            .db
            .get_issue(&args.id)
            .map_err(|e| e.to_string())?
            .ok_or_else(|| format!("Issue '{}' not found", args.id))?;

        let similar_count = args.similar_count.unwrap_or(5);

        let search_text = format!(
            "{}\n\n{}",
            issue.title,
            issue.description.as_deref().unwrap_or("")
        );

        let similar = if let Ok(embedder) = Embedder::new(&self.config) {
            search::find_duplicates(
                &self.db,
                &search_text,
                Some(&issue.team_key),
                0.3,
                similar_count + 1,
                &embedder,
                self.config.search.rrf_k,
                &workspace,
            )
            .await
            .unwrap_or_default()
            .into_iter()
            .filter(|r| r.issue_id != issue.id)
            .take(similar_count)
            .collect::<Vec<_>>()
        } else {
            Vec::new()
        };

        self.ensure_comments_synced_if_needed(&workspace, &issue.id)
            .await?;
        let relations = self
            .db
            .get_relations_enriched(&issue.id)
            .map_err(|e| e.to_string())?;
        let issue_id = issue.id.clone();

        let mut result = serde_json::json!({
            "issue": issue,
            "similar_issues": similar,
            "relations": relations,
        });
        attach_comments_payload(&mut result, &self.db, &issue_id)?;

        enrich_with_issue_links(&mut result, &self.db);
        serde_json::to_string_pretty(&result).map_err(|e| e.to_string())
    }

    #[tool(
        name = "get_triage_queue",
        description = "Get a batch of unprioritized issues for triage. Returns enriched issues with similar issues and code_search_hints. IMPORTANT: For each issue, BEFORE presenting it to the user, you MUST search the codebase using the code_search_hints (via Grep, Glob, Read, or Cuttlefish MCP tools like get_symbols/find_references). Spend 2-4 tool calls per issue exploring relevant code, then include your findings when asking the user questions."
    )]
    async fn get_triage_queue(
        &self,
        #[tool(aggr)] args: GetTriageQueueArgs,
    ) -> Result<String, String> {
        let workspace = self.require_workspace(&args.workspace)?;
        // Incremental sync to pick up changes made by other users
        if let Ok(client) = self.client_for_workspace(&workspace) {
            let _ = client
                .sync_team(&self.db, &args.team, &workspace, false, false, None)
                .await;
        }

        let label_ids = if let Some(ref names) = args.labels {
            let (resolved, unknown) = self.db
                .resolve_label_ids_local(&workspace, names)
                .map_err(|e| e.to_string())?;
            if !unknown.is_empty() {
                if resolved.is_empty()
                    && self.db.list_labels(&workspace).map_err(|e| e.to_string())?.is_empty()
                {
                    return Err(format!(
                        "No labels synced yet for workspace '{}'. Run sync_team first.",
                        workspace
                    ));
                }
                let suggestions = suggest_label_names(&self.db, &workspace, &unknown);
                return Err(format!(
                    "Label{} {} not found. {}Run list_labels for the full set.",
                    if unknown.len() == 1 { "" } else { "s" },
                    unknown.iter().map(|s| format!("'{}'", s)).collect::<Vec<_>>().join(", "),
                    if suggestions.is_empty() { String::new() }
                    else { format!("Did you mean: {}? ", suggestions.join(", ")) }
                ));
            }
            Some(resolved)
        } else {
            None
        };

        let all_issues = self
            .db
            .get_unprioritized_issues_filtered(
                Some(&args.team),
                args.include_completed.unwrap_or(false),
                &workspace,
                label_ids.as_deref(),
            )
            .map_err(|e| e.to_string())?;

        let exclude_set: std::collections::HashSet<&str> = args
            .exclude
            .as_ref()
            .map(|v| v.iter().map(|s| s.as_str()).collect())
            .unwrap_or_default();

        let filtered: Vec<_> = all_issues
            .into_iter()
            .filter(|i| !exclude_set.contains(i.identifier.as_str()))
            .collect();

        let limit = args.limit.unwrap_or(10);
        let batch: Vec<_> = if args.shuffle.unwrap_or(false) {
            use rand::seq::SliceRandom;
            let mut indices: Vec<usize> = (0..filtered.len()).collect();
            indices.shuffle(&mut rand::rng());
            indices
                .into_iter()
                .take(limit)
                .map(|i| &filtered[i])
                .collect()
        } else {
            filtered.iter().take(limit).collect()
        };

        let total_remaining = filtered.len();

        let embedder = Embedder::new(&self.config).ok();

        let mut enriched = Vec::new();
        for issue in &batch {
            let description = issue.description.as_deref().map(|d| {
                if d.len() > 2000 {
                    let mut end = 2000;
                    while end > 0 && !d.is_char_boundary(end) {
                        end -= 1;
                    }
                    &d[..end]
                } else {
                    d
                }
            });

            let similar = if let Some(ref embedder) = embedder {
                let search_text = format!("{}\n\n{}", issue.title, description.unwrap_or(""));
                search::find_duplicates(
                    &self.db,
                    &search_text,
                    Some(&args.team),
                    0.3,
                    4,
                    embedder,
                    self.config.search.rrf_k,
                    &workspace,
                )
                .await
                .unwrap_or_default()
                .into_iter()
                .filter(|r| r.issue_id != issue.id)
                .take(3)
                .collect::<Vec<_>>()
            } else {
                Vec::new()
            };

            let relations = self
                .db
                .get_relations_enriched(&issue.id)
                .unwrap_or_default();

            // Extract search hints from title and description for code exploration
            let code_search_hints =
                extract_code_hints(&issue.title, description.unwrap_or(""), &issue.labels());

            enriched.push(serde_json::json!({
                "identifier": issue.identifier,
                "url": issue.url,
                "title": issue.title,
                "description": description,
                "state_name": issue.state_name,
                "assignee_name": issue.assignee_name,
                "project_name": issue.project_name,
                "labels": issue.labels(),
                "created_at": issue.created_at,
                "similar_issues": similar,
                "relations": relations,
                "code_search_hints": code_search_hints,
            }));
        }

        let mut result = serde_json::json!({
            "instruction": "IMPORTANT: For each issue below, BEFORE asking the user any questions, search the codebase using the code_search_hints. Use Grep, Glob, Read, or Cuttlefish MCP tools (get_symbols, find_references) to understand the current code state. Then present your code findings alongside the issue summary. Always include the issue's Linear URL as a clickable markdown link [IDENTIFIER](url). Assume the perspective of a principal staff software engineer who has been tasked to implement this issue. Ask 2-4 thoughtful clarifying questions that would help elucidate any ambiguity or uncertainty in the issue description — the kind of questions an experienced engineer asks before writing code.",
            "queue": enriched,
            "total_remaining": total_remaining,
            "team": args.team,
        });

        enrich_with_issue_links(&mut result, &self.db);
        serde_json::to_string_pretty(&result).map_err(|e| e.to_string())
    }

    #[tool(
        name = "mark_triaged",
        description = "Mark an issue as triaged by setting priority and optionally updating title, description, and adding a triage comment. Combines update + comment into one call. Prefer using the comment field over description for adding context — description updates risk losing formatting. Image references in the original description are automatically preserved."
    )]
    async fn mark_triaged(&self, #[tool(aggr)] args: MarkTriagedArgs) -> Result<String, String> {
        let workspace = self.require_workspace(&args.workspace)?;
        if args.priority < 1 || args.priority > 4 {
            return Err("Priority must be 1 (Urgent), 2 (High), 3 (Medium), or 4 (Low)".into());
        }

        // Resolve from local DB to get the Linear UUID
        let local_issue = self
            .db
            .get_issue(&args.id)
            .map_err(|e| e.to_string())?
            .ok_or_else(|| format!("Issue '{}' not found", args.id))?;

        let client = self.client_for_workspace(&workspace)?;

        // Re-fetch from Linear to get the latest version
        let (issue, issue_relations, issue_label_ids) = client
            .fetch_single_issue(&local_issue.id)
            .await
            .map_err(|e| e.to_string())?;
        self.db.upsert_issue(&issue).map_err(|e| e.to_string())?;
        self.db
            .upsert_relations(&issue.id, &issue_relations)
            .map_err(|e| e.to_string())?;
        self.db
            .replace_issue_labels(&issue.id, &issue_label_ids)
            .map_err(|e| e.to_string())?;

        // If someone else already prioritized it, let the caller know
        if issue.priority != 0 {
            return Ok(serde_json::json!({
                "identifier": issue.identifier,
                "url": issue.url,
                "status": "already_triaged",
                "current_priority": issue.priority,
                "current_priority_label": issue.priority_label(),
                "message": format!(
                    "{} was already prioritized as {} — skipping",
                    issue.identifier, issue.priority_label()
                ),
            })
            .to_string());
        }

        // Flag if the issue was modified since we last saw it
        let was_modified = issue.content_hash != local_issue.content_hash;
        if was_modified {
            let mut changes = Vec::new();
            if issue.title != local_issue.title {
                changes.push(format!(
                    "title changed: \"{}\" → \"{}\"",
                    local_issue.title, issue.title
                ));
            }
            if issue.description != local_issue.description {
                changes.push("description was updated".to_string());
            }
            if issue.state_name != local_issue.state_name {
                changes.push(format!(
                    "state changed: {} → {}",
                    local_issue.state_name, issue.state_name
                ));
            }
            if issue.assignee_name != local_issue.assignee_name {
                changes.push(format!(
                    "assignee changed: {} → {}",
                    local_issue.assignee_name.as_deref().unwrap_or("unassigned"),
                    issue.assignee_name.as_deref().unwrap_or("unassigned")
                ));
            }
            // Re-embed with the updated content
            self.reembed_issue(&issue).await;

            return Ok(serde_json::json!({
                "identifier": issue.identifier,
                "url": issue.url,
                "status": "modified_since_queued",
                "changes": changes,
                "current_title": issue.title,
                "current_description": issue.description,
                "current_state": issue.state_name,
                "message": format!(
                    "{} was modified since the queue was fetched — review the latest version before triaging",
                    issue.identifier
                ),
            })
            .to_string());
        }

        // Resolve state name to ID if provided
        let state_id = if let Some(ref state_name) = args.state {
            Some(
                client
                    .get_state_id(&issue.team_key, state_name)
                    .await
                    .map_err(|e| e.to_string())?,
            )
        } else {
            None
        };

        let label_ids = if let Some(ref label_names) = args.labels {
            Some(self.resolve_labels_for_mutation(&workspace, &client, label_names).await?)
        } else {
            None
        };

        let mut project_id = if let Some(ref project_name) = args.project {
            if project_name.eq_ignore_ascii_case("none") {
                Some(String::new())
            } else {
                Some(
                    client
                        .get_project_id(project_name)
                        .await
                        .map_err(|e| e.to_string())?,
                )
            }
        } else {
            None
        };

        let project_milestone_id = if let Some(ref milestone_name) = args.project_milestone {
            if milestone_name.eq_ignore_ascii_case("none") {
                Some(String::new())
            } else {
                if project_id.as_deref() == Some("") {
                    return Err("Cannot assign a milestone while removing the issue's project.".into());
                }
                let owning_project_id = project_id
                    .as_deref()
                    .filter(|id| !id.is_empty())
                    .or(issue.project_id.as_deref());
                let milestone_id = client
                    .find_project_milestone(owning_project_id, milestone_name)
                    .await
                    .map_err(|e| e.to_string())?;
                let milestone = client
                    .fetch_project_milestone(&milestone_id, &workspace)
                    .await
                    .map_err(|e| e.to_string())?;
                if project_id.is_none() && issue.project_id.as_deref() != Some(&milestone.project_id) {
                    project_id = Some(milestone.project_id);
                }
                Some(milestone_id)
            }
        } else {
            None
        };

        let assignee_id: Option<String> = if let Some(ref a) = args.assignee {
            Some(client.resolve_assignee_id(a).await.map_err(|e| e.to_string())?)
        } else {
            None
        };

        // Preserve any image references from the original description
        let safe_description = args
            .description
            .as_ref()
            .map(|new_desc| match &issue.description {
                Some(original) => preserve_images(original, new_desc),
                None => new_desc.clone(),
            });

        client
            .update_issue(
                &issue.id,
                crate::linear::UpdateIssueInput {
                    title: args.title.as_deref(),
                    description: safe_description.as_deref(),
                    priority: Some(args.priority),
                    state_id: state_id.as_deref(),
                    label_ids: label_ids.as_deref(),
                    project_id: project_id.as_deref(),
                    assignee_id: assignee_id.as_deref(),
                    project_milestone_id: project_milestone_id.as_deref(),
                },
            )
            .await
            .map_err(|e| e.to_string())?;

        if let Some(ref comment_text) = args.comment {
            client
                .add_comment(&issue.id, comment_text)
                .await
                .map_err(|e| e.to_string())?;
            let _ = client
                .sync_issue_comments(&self.db, &issue.id, &workspace)
                .await;
        }

        let (mut updated, updated_relations, updated_label_ids) = client
            .fetch_single_issue(&issue.id)
            .await
            .map_err(|e| e.to_string())?;
        updated.workspace_id = workspace.clone();
        self.db.upsert_issue(&updated).map_err(|e| e.to_string())?;
        self.db
            .upsert_relations(&updated.id, &updated_relations)
            .map_err(|e| e.to_string())?;
        self.db
            .replace_issue_labels(&updated.id, &updated_label_ids)
            .map_err(|e| e.to_string())?;

        // Re-embed if title or description changed
        if args.title.is_some() || args.description.is_some() {
            self.reembed_issue(&updated).await;
        }

        let priority_label = match args.priority {
            1 => "Urgent",
            2 => "High",
            3 => "Medium",
            4 => "Low",
            _ => "Unknown",
        };

        Ok(serde_json::json!({
            "identifier": issue.identifier,
            "url": issue.url,
            "priority": args.priority,
            "priority_label": priority_label,
            "title": args.title.as_deref().unwrap_or(&issue.title),
            "status": "triaged",
        })
        .to_string())
    }

    #[tool(
        name = "manage_relation",
        description = "Add or remove a relation between two issues. Relation types: 'blocks', 'blocked_by', 'related', 'duplicate'. Use action 'add' to create or 'remove' to delete a relation."
    )]
    async fn manage_relation(
        &self,
        #[tool(aggr)] args: ManageRelationArgs,
    ) -> Result<String, String> {
        let workspace = self.require_workspace(&args.workspace)?;
        let valid_types = ["blocks", "blocked_by", "related", "duplicate"];
        if !valid_types.contains(&args.relation_type.as_str()) {
            return Err(format!(
                "Invalid relation_type '{}'. Must be one of: {}",
                args.relation_type,
                valid_types.join(", ")
            ));
        }

        let source = self
            .db
            .get_issue(&args.issue)
            .map_err(|e| e.to_string())?
            .ok_or_else(|| format!("Issue '{}' not found", args.issue))?;
        let target = self
            .db
            .get_issue(&args.related_issue)
            .map_err(|e| e.to_string())?
            .ok_or_else(|| format!("Issue '{}' not found", args.related_issue))?;

        let client = self.client_for_workspace(&workspace)?;

        match args.action.as_str() {
            "add" => {
                let relation_id = client
                    .create_relation(&source.id, &target.id, &args.relation_type)
                    .await
                    .map_err(|e| e.to_string())?;

                // Re-fetch to update local relations
                let (updated, relations, label_ids) = client
                    .fetch_single_issue(&source.id)
                    .await
                    .map_err(|e| e.to_string())?;
                self.db.upsert_issue(&updated).map_err(|e| e.to_string())?;
                self.db
                    .upsert_relations(&updated.id, &relations)
                    .map_err(|e| e.to_string())?;
                self.db
                    .replace_issue_labels(&updated.id, &label_ids)
                    .map_err(|e| e.to_string())?;

                Ok(serde_json::json!({
                    "status": "added",
                    "relation_id": relation_id,
                    "issue": source.identifier,
                    "related_issue": target.identifier,
                    "relation_type": args.relation_type,
                })
                .to_string())
            }
            "remove" => {
                // For blocked_by, the stored relation is reversed
                let (db_source, db_target, db_type) = if args.relation_type == "blocked_by" {
                    (&target.id, &source.id, "blocks")
                } else {
                    (&source.id, &target.id, args.relation_type.as_str())
                };

                let relation_id = self
                    .db
                    .find_relation_id(db_source, db_target, db_type)
                    .map_err(|e| e.to_string())?
                    .ok_or_else(|| {
                        format!(
                            "No '{}' relation found between {} and {}",
                            args.relation_type, args.issue, args.related_issue
                        )
                    })?;

                client
                    .delete_relation(&relation_id)
                    .await
                    .map_err(|e| e.to_string())?;

                // Re-fetch to update local relations
                let (updated, relations, label_ids) = client
                    .fetch_single_issue(&source.id)
                    .await
                    .map_err(|e| e.to_string())?;
                self.db.upsert_issue(&updated).map_err(|e| e.to_string())?;
                self.db
                    .upsert_relations(&updated.id, &relations)
                    .map_err(|e| e.to_string())?;
                self.db
                    .replace_issue_labels(&updated.id, &label_ids)
                    .map_err(|e| e.to_string())?;

                Ok(serde_json::json!({
                    "status": "removed",
                    "issue": source.identifier,
                    "related_issue": target.identifier,
                    "relation_type": args.relation_type,
                })
                .to_string())
            }
            _ => Err("action must be 'add' or 'remove'".into()),
        }
    }
}

impl RectilinearMcp {
    fn require_workspace(&self, workspace: &Option<String>) -> Result<String, String> {
        match workspace {
            Some(ws) if !ws.is_empty() => {
                let names = self.config.workspace_names();
                if !names.contains(ws) {
                    return Err(format!(
                        "Workspace '{}' not found. Use list_workspaces to see available workspaces. Available: {}",
                        ws, names.join(", ")
                    ));
                }
                Ok(ws.clone())
            }
            _ => Err(
                "workspace is required. Use list_workspaces to see available workspaces."
                    .to_string(),
            ),
        }
    }

    fn client_for_workspace(&self, workspace: &str) -> Result<LinearClient, String> {
        let api_key = self
            .config
            .workspace_api_key(workspace)
            .map_err(|e| e.to_string())?;
        Ok(LinearClient::with_api_key(&api_key))
    }

    async fn resolve_team_ids(
        &self,
        client: &LinearClient,
        values: &[String],
    ) -> Result<Vec<String>, String> {
        if values.is_empty() {
            return Err("At least one team is required.".into());
        }
        let teams = client.list_teams().await.map_err(|error| error.to_string())?;
        let mut ids = Vec::new();
        for value in values {
            let team = teams
                .iter()
                .find(|team| {
                    team.id == *value
                        || team.key.eq_ignore_ascii_case(value)
                        || team.name.eq_ignore_ascii_case(value)
                })
                .ok_or_else(|| {
                    format!(
                        "Team '{}' not found. Available: {}",
                        value,
                        teams
                            .iter()
                            .map(|team| format!("{} ({})", team.key, team.name))
                            .collect::<Vec<_>>()
                            .join(", ")
                    )
                })?;
            if !ids.contains(&team.id) {
                ids.push(team.id.clone());
            }
        }
        Ok(ids)
    }

    async fn resolve_member_ids(
        &self,
        client: &LinearClient,
        members: &[String],
    ) -> Result<Vec<String>, String> {
        let mut ids = Vec::new();
        for member in members {
            if member.eq_ignore_ascii_case("none") {
                return Err("Use an empty members list to remove all project members.".into());
            }
            let id = client
                .resolve_assignee_id(member)
                .await
                .map_err(|error| error.to_string())?;
            if !ids.contains(&id) {
                ids.push(id);
            }
        }
        Ok(ids)
    }

    async fn resolve_project_id(
        &self,
        client: &LinearClient,
        workspace: &str,
        id_or_name: &str,
    ) -> Result<String, String> {
        if let Some(project) = self
            .db
            .get_project(workspace, id_or_name)
            .map_err(|error| error.to_string())?
        {
            return Ok(project.id);
        }
        client
            .find_project_by_name(id_or_name)
            .await
            .map_err(|error| error.to_string())
    }

    async fn resolve_milestone_id(
        &self,
        client: &LinearClient,
        workspace: &str,
        project_id: Option<&str>,
        id_or_name: &str,
    ) -> Result<String, String> {
        if let Some(milestone) = self
            .db
            .get_project_milestone(workspace, id_or_name, project_id)
            .map_err(|error| error.to_string())?
        {
            return Ok(milestone.id);
        }
        client
            .find_project_milestone(project_id, id_or_name)
            .await
            .map_err(|error| error.to_string())
    }

    async fn cache_project_and_milestone(
        &self,
        client: &LinearClient,
        workspace: &str,
        milestone_id: &str,
    ) -> Result<(), String> {
        let milestone = client
            .fetch_project_milestone(milestone_id, workspace)
            .await
            .map_err(|error| error.to_string())?;
        let project = client
            .fetch_project(&milestone.project_id, workspace)
            .await
            .map_err(|error| error.to_string())?;
        self.db
            .upsert_project(&project)
            .map_err(|error| error.to_string())?;
        self.db
            .upsert_project_milestone(&milestone)
            .map_err(|error| error.to_string())?;
        Ok(())
    }

    async fn ensure_comments_synced_if_needed(
        &self,
        workspace: &str,
        issue_id: &str,
    ) -> Result<(), String> {
        let sync_state = self
            .db
            .get_comment_sync_state(issue_id)
            .map_err(|e| e.to_string())?;
        if sync_state.status != "not_synced" {
            return Ok(());
        }

        let client = self.client_for_workspace(workspace)?;
        let _ = client
            .sync_issue_comments(&self.db, issue_id, workspace)
            .await;
        Ok(())
    }

    /// Resolve label names to ids using the same logic as create_issue:
    /// - empty catalog → defer to remote query (fresh install).
    /// - non-empty catalog with unknowns → return user-facing error with did-you-mean.
    /// - non-empty catalog, all resolved → return resolved ids.
    async fn resolve_labels_for_mutation(
        &self,
        workspace: &str,
        client: &LinearClient,
        names: &[String],
    ) -> Result<Vec<String>, String> {
        let catalog_size = self.db
            .list_labels(workspace)
            .map_err(|e| e.to_string())?
            .len();
        if catalog_size == 0 {
            eprintln!(
                "info: labels catalog empty for workspace '{}', resolving via remote query",
                workspace
            );
            return client.get_label_ids(names).await.map_err(|e| e.to_string());
        }
        let (resolved, unknown) = self.db
            .resolve_label_ids_local(workspace, names)
            .map_err(|e| e.to_string())?;
        if !unknown.is_empty() {
            let suggestions = suggest_label_names(&self.db, workspace, &unknown);
            return Err(format!(
                "Label{} {} not found. {}Run list_labels for the full set.",
                if unknown.len() == 1 { "" } else { "s" },
                unknown.iter().map(|s| format!("'{}'", s)).collect::<Vec<_>>().join(", "),
                if suggestions.is_empty() { String::new() }
                else { format!("Did you mean: {}? ", suggestions.join(", ")) }
            ));
        }
        Ok(resolved)
    }

    /// Re-chunk and re-embed a single issue. Best-effort — failures are silently ignored.
    async fn reembed_issue(&self, issue: &crate::db::Issue) {
        let Ok(embedder) = Embedder::new(&self.config) else {
            return;
        };
        let chunks = embedding::chunk_text(
            &issue.title,
            issue.description.as_deref().unwrap_or(""),
            512,
            64,
        );
        if let Ok(embeddings) = embedder.embed_batch(&chunks).await {
            let chunk_data: Vec<(usize, String, Vec<u8>)> = chunks
                .into_iter()
                .zip(embeddings)
                .enumerate()
                .map(|(i, (text, emb))| (i, text, embedding::embedding_to_bytes(&emb)))
                .collect();
            let _ = self.db.upsert_chunks(&issue.id, &chunk_data);
        }
    }
}

#[tool(tool_box)]
impl ServerHandler for RectilinearMcp {
    fn get_info(&self) -> ServerInfo {
        ServerInfo {
            protocol_version: ProtocolVersion::V_2024_11_05,
            capabilities: ServerCapabilities {
                tools: Some(ToolsCapability {
                    list_changed: None,
                }),
                ..Default::default()
            },
            server_info: Implementation {
                name: "rectilinear".into(),
                version: env!("CARGO_PKG_VERSION").into(),
            },
            instructions: Some(
                "## Workspace Selection\n\
                 All tools (except list_workspaces) require a `workspace` parameter. Call list_workspaces first to discover available workspaces.\n\n\
                 Rectilinear provides Linear issue intelligence plus first-class project and milestone management.\n\n\
                 ## Project Hierarchy\n\
                 Use list/get/create/update/delete_project and the corresponding project_milestone tools for metadata CRUD. \
                 Use import_project or import_project_milestone when a downstream client needs one complete portable hierarchy with linked issues. \
                 update_issue and mark_triaged accept project_milestone in addition to project.\n\n\
                 ## Comment Evidence\n\
                 When get_issue(include_comments=true) or issue_context returns comments, always inspect comments_status. \
                 An empty comments array is only evidence that no Linear comments exist when comments_status is `none_found`. \
                 `not_synced` means comments were not fetched, and `permission_denied` or `unavailable` means Linear could not provide them; \
                 check comments_sync_error and comments_synced_at. A full sync_team run includes archived issues by default and refreshes comment sync state.\n\n\
                 ## Triage Workflow\n\
                 IMPORTANT: Present exactly ONE issue at a time. Wait for the user's response and call mark_triaged before presenting the next issue. \
                 Never batch multiple issues into a single message.\n\n\
                 When the user asks to triage issues:\n\
                 1. Call get_triage_queue with the team key. IMPORTANT: Always use get_triage_queue from rectilinear — \
                 never use Linear's list_issues as a substitute. If the user asks to include completed issues, \
                 pass include_completed: true.\n\
                 2. Take the FIRST issue from the queue. BEFORE presenting it to the user, use the code_search_hints field to explore the codebase. \
                 Search for the mentioned files, symbols, and keywords using Grep, Glob, Read, or Cuttlefish MCP tools (get_symbols, find_references, get_hover_info). \
                 Spend 2-4 tool calls understanding the current code state for THIS issue.\n\
                 3. Present a brief summary of the issue AND what you found in the code. \
                 Assume the perspective of a principal staff software engineer who has been tasked to implement this issue. \
                 Ask 2-4 thoughtful clarifying questions that would help elucidate any ambiguity or uncertainty in the issue description — \
                 the kind of questions an experienced engineer asks before writing code \
                 (e.g. \"I found WorktreeManager.cleanup() at src/worktree.rs:142 — it already handles orphaned worktrees. Is this issue about a gap in that logic, or something else entirely?\"). \
                 Suggest best-guess answers.\n\
                 4. WAIT for the user to respond. Based on their answers, propose: priority (1-4), improved title, \
                 triage comment (use the comment field for adding context, code references, and file paths — prefer comments over description changes to avoid losing images or formatting), \
                 state change if appropriate (e.g. Done, Cancelled, Duplicate), and any label or project changes. \
                 Only update the description if the original is genuinely wrong or missing key information.\n\
                 5. WAIT for user confirmation, then call mark_triaged with all agreed changes.\n\
                 6. Only after mark_triaged succeeds, move to the NEXT issue. Repeat from step 2. \
                 When the batch is exhausted, call get_triage_queue again with processed identifiers in exclude.\n\n\
                 ## Archival Mode\n\
                 To triage completed/canceled issues (for archival prioritization), pass include_completed: true to get_triage_queue. \
                 This surfaces Done/Canceled/Duplicate issues that have no priority set. The workflow is the same — set a priority for historical record.\n\n\
                 ## Priority Framework\n\
                 1=Urgent (production down, data loss, security)\n\
                 2=High (major feature broken, significant user impact, no workaround)\n\
                 3=Medium (degraded experience, workarounds exist)\n\
                 4=Low (minor polish, nice-to-have)\n\n\
                 ## Duplicate Handling\n\
                 If similar_issues show >0.8 similarity, flag as potential duplicate. Ask user whether to merge, close as dup, or keep separate. \
                 Use the state field in mark_triaged to set the status (e.g. state: \"Duplicate\", state: \"Done\", state: \"Cancelled\").\n\n\
                 ## Labels and Projects\n\
                 When triaging, consider whether the issue should be labeled or assigned to a project. \
                 Use the labels, project, and project_milestone fields in mark_triaged to set these. \
                 Pass project: \"none\" or project_milestone: \"none\" to remove the corresponding relationship.\n\n\
                 ## Issue Relations\n\
                 Issues may have relations (blocks, blocked_by, related, duplicate) visible in the `relations` field. \
                 When triaging, surface blocking relationships — they affect priority. Use manage_relation to add/remove relations. \
                 If an issue blocks or is blocked by another, always mention this prominently.\n\n\
                 ## Linear Links\n\
                 ALWAYS include the Linear issue URL (from the `url` field) as a clickable markdown link when presenting issues to the user. \
                 Format as [IDENTIFIER](url) so the user can click through to Linear directly. \
                 Do this for the main issue being discussed AND for any related, blocking, or similar issues referenced. \
                 Tool responses include a `referenced_issues` field that maps any issue identifiers found in descriptions/comments \
                 to their URLs and titles — use these to render all mentioned issues as clickable links.\n\n\
                 ## Progress Tracking\n\
                 Use TodoWrite to make progress visible to the user:\n\
                 - When triaging multiple issues from a get_triage_queue batch, create a TodoWrite list with one item per issue \
                 (e.g. \"Triage ENG-123: <title>\"). Mark each in_progress when you present it, completed after mark_triaged succeeds. \
                 This gives the user a visible remaining-work indicator across a long batch.\n\
                 - When a single issue needs multiple clarifying questions or decisions (refinement, priority, tradeoffs, \
                 related issues, label/project assignment), enumerate them as TodoWrite items before asking. Update the list as you go.\n\
                 - Skip TodoWrite for trivial one-shot interactions (a single search, a single create_issue with no ambiguity)."
                    .into(),
            ),
        }
    }
}

pub async fn serve(db: Database, config: Config) -> Result<()> {
    eprintln!("MCP server ready (stdio transport)");
    let handler = RectilinearMcp::new(db, config);
    let transport = rmcp::transport::io::stdio();
    let server = rmcp::serve_server(handler, transport).await?;
    server.waiting().await?;
    Ok(())
}

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

    #[test]
    fn test_extract_image_references() {
        let text = "Some text ![screenshot](https://uploads.linear.app/abc.png) more text";
        let images = extract_image_references(text);
        assert_eq!(
            images,
            vec!["![screenshot](https://uploads.linear.app/abc.png)"]
        );
    }

    #[test]
    fn test_extract_multiple_images() {
        let text = "![a](url1) text ![b](url2)";
        let images = extract_image_references(text);
        assert_eq!(images, vec!["![a](url1)", "![b](url2)"]);
    }

    #[test]
    fn test_extract_empty_alt() {
        let text = "![](https://example.com/img.png)";
        let images = extract_image_references(text);
        assert_eq!(images, vec!["![](https://example.com/img.png)"]);
    }

    #[test]
    fn test_no_images() {
        let text = "Just some regular text with [a link](url)";
        let images = extract_image_references(text);
        assert!(images.is_empty());
    }

    #[test]
    fn test_preserve_images_no_originals() {
        let result = preserve_images("no images here", "new description");
        assert_eq!(result, "new description");
    }

    #[test]
    fn test_preserve_images_keeps_missing() {
        let original = "Text ![img](https://uploads.linear.app/abc.png) more";
        let new_desc = "Rewritten description";
        let result = preserve_images(original, new_desc);
        assert!(result.starts_with("Rewritten description"));
        assert!(result.contains("![img](https://uploads.linear.app/abc.png)"));
    }

    #[test]
    fn test_preserve_images_already_present() {
        let original = "Text ![img](url)";
        let new_desc = "New text ![img](url)";
        let result = preserve_images(original, new_desc);
        assert_eq!(result, "New text ![img](url)");
    }
}