agent-doc 0.32.3

Interactive document sessions with AI agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
//! # Module: resync
//!
//! ## Spec
//! - `prune()`: quietly removes dead/duplicate registry entries by delegating to
//!   `tmux_router::prune()`, then returns active panes from stash windows, purges
//!   idle stash windows, and clears orphaned stash panes. Called automatically
//!   before route, sync, and claim operations. Returns the count of entries removed.
//! - `run(fix)`: verbose counterpart to `prune()` for the `agent-doc resync` CLI
//!   subcommand. Prints which entries were removed, which issues were detected, and
//!   the post-resync active session list.
//! - Issue detection (`detect_issues`): inspects every alive registry pane for four
//!   problem classes: `InStash` (pane parked in a stash window), `WrongProcess`
//!   (pane running a non-agent process such as `corky watch`), `WrongSession`
//!   (pane's tmux session differs from the document's `tmux_session` frontmatter
//!   field, or from `config::project_tmux_session()` when frontmatter field is absent),
//!   and `WrongWindow` (panes for the same tmux session are scattered across
//!   multiple non-stash windows, determined by majority-window vote).
//! - Fix application (`apply_fixes`): `WrongSession` → kill pane + deregister entry (default),
//!   or when `relocate_session = Some(target)` → `join-pane` to target session (registry kept);
//!   `WrongProcess` → deregister only (foreign process is not killed); `InStash` →
//!   deregister only (pane left intact for potential manual recovery); `WrongWindow`
//!   → stash the outlier pane so the next route consolidates it.
//! - Stash management: `return_stashed_panes` moves registered active panes back to
//!   their original window (or first non-stash window of the frontmatter session);
//!   `purge_stash_windows` kills entire stash windows where all panes are idle
//!   shells and the window is older than 30 seconds; `purge_unregistered_stash_panes`
//!   kills individual unregistered idle shell panes in stash windows (agent processes
//!   like claude/agent-doc/node are never auto-killed even if unregistered — the
//!   registry can go stale); `purge_orphaned_agent_panes` removes unregistered
//!   agent-doc/claude/node panes from any window, but only when the window has at
//!   least one other pane (never orphans the last pane).
//! - Process classification: `AGENT_PROCESSES` (`agent-doc`, `claude`, `node`) are
//!   expected occupants of registered panes. `IDLE_SHELLS` (`zsh`, `bash`, `sh`,
//!   `fish`) are treated as empty/unused slots.
//!
//! ## Agentic Contracts
//! - `prune()` never kills a registered pane that is alive and in a non-stash window;
//!   it only removes dead entries from the registry and stash-specific garbage.
//! - User-owned processes (anything not in `AGENT_PROCESSES` or `IDLE_SHELLS`) are
//!   never killed by any automatic or fix path — they are left running.
//! - Stash windows named exactly `"stash"` or matching `"stash-*"` are the only
//!   windows whose panes may be killed automatically; non-stash windows are only
//!   touched when purging orphaned agent panes with sibling panes present.
//! - `apply_fixes` acquires a `RegistryLock` before mutating `sessions.json`; all
//!   registry mutations are atomic with respect to concurrent agent-doc processes.
//! - Dead panes are exclusively handled by `tmux_router::prune()`; `detect_issues`
//!   skips dead panes entirely to avoid double-reporting.
//! - On `WrongSession` fix failure (kill error), the registry entry is still removed
//!   to prevent a permanently stale entry from blocking future routes.
//! - `find_return_target` priority: (1) original window from registry entry if alive
//!   and non-stash, (2) first non-stash window in the frontmatter `tmux_session`,
//!   (3) returns `None` (no move attempted, error logged).
//!
//! ## Evals
//! - `detect_dead_pane_not_flagged_as_issue`: registry entry with a non-existent
//!   pane ID → `detect_issues_in_registry` returns no issues (dead panes belong to
//!   `prune`, not issue detection).
//! - `detect_wrong_session_pane`: pane running in session `"wrong"` with frontmatter
//!   `tmux_session: correct` → `WrongSession` issue detected.
//! - `fix_wrong_session_removes_registry_entry`: `apply_fixes_to_registry` with a
//!   `WrongSession` issue → entry removed from registry, pane kill attempted.
//! - `fix_wrong_process_deregisters_without_kill`: `WrongProcess` issue →
//!   registry entry removed, foreign process pane untouched.
//! - `fix_in_stash_deregisters_entry`: `InStash` issue → registry entry removed,
//!   stash pane left alive.
//! - `stash_window_purged_when_all_idle`: stash window with only idle shell panes
//!   older than 30 s → `purge_stash_windows` kills the window.
//! - `stash_window_spared_when_agent_active`: stash window containing a `claude`
//!   pane → `purge_stash_windows` leaves the window intact.
//! - `purge_unregistered_stash_panes_leaves_user_processes`: stash window with an
//!   unregistered `corky` pane and an unregistered idle shell → idle shell killed,
//!   `corky` pane untouched.
//! - `purge_orphaned_agent_panes_skips_last_pane`: window with a single unregistered
//!   `claude` pane → pane not killed (would orphan the window).
//! - `wrong_window_detected_by_majority_vote`: three registered panes in session A,
//!   two in window W1 and one in window W2 → the W2 pane produces a `WrongWindow`
//!   issue; the W1 panes do not.

use anyhow::Result;

use crate::{config, frontmatter};
use crate::sessions::{self, PaneMoveOp, Tmux};

/// Valid process names for agent-doc panes.
const AGENT_PROCESSES: &[&str] = &["agent-doc", "claude", "node"];

/// Shells considered idle (not running an agent process).
const IDLE_SHELLS: &[&str] = &["zsh", "bash", "sh", "fish"];

/// A problem detected during resync --fix analysis.
#[derive(Debug)]
#[allow(clippy::enum_variant_names)]
enum Issue {
    /// Pane is in a different tmux session than the document's frontmatter expects.
    WrongSession {
        key: String,
        file: String,
        pane: String,
        actual_session: String,
        expected_session: String,
    },
    /// Pane is running a process that is not agent-doc or claude.
    WrongProcess {
        key: String,
        file: String,
        pane: String,
        process: String,
    },
    /// Panes for the same session are in different windows (excluding stash windows).
    WrongWindow {
        file: String,
        pane: String,
        actual_window: String,
        expected_window: String,
    },
    /// Pane is alive but in a stash window (not the active workspace).
    InStash {
        key: String,
        file: String,
        pane: String,
        window_name: String,
    },
}

impl std::fmt::Display for Issue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Issue::WrongSession {
                file,
                pane,
                actual_session,
                expected_session,
                ..
            } => write!(
                f,
                "{} (pane {}) in session '{}', expected '{}'",
                file, pane, actual_session, expected_session
            ),
            Issue::WrongProcess {
                file,
                pane,
                process,
                ..
            } => write!(
                f,
                "{} (pane {}) running '{}', expected agent-doc/claude",
                file, pane, process
            ),
            Issue::WrongWindow {
                file,
                pane,
                actual_window,
                expected_window,
                ..
            } => write!(
                f,
                "{} (pane {}) in window '{}', expected '{}'",
                file, pane, actual_window, expected_window
            ),
            Issue::InStash {
                file,
                pane,
                window_name,
                ..
            } => write!(
                f,
                "{} (pane {}) is in stash window '{}'",
                file, pane, window_name
            ),
        }
    }
}

/// Quietly prune dead panes and deduplicate entries.
/// Called automatically before route, sync, and claim operations.
/// Returns the number of registry entries removed.
pub fn prune() -> Result<usize> {
    tracing::debug!("resync::prune start");
    let tmux = Tmux::default_server();
    let registry_path = sessions::registry_path();
    let removed = tmux_router::prune(&registry_path, &tmux)?;
    if removed > 0 {
        tracing::debug!(removed, "resync: pruned stale sessions");
        eprintln!("resync: pruned {} stale session(s)", removed);
    }

    // Fetch all metadata once (2 subprocess calls total instead of ~20-40)
    let windows = fetch_all_window_metadata(&tmux);
    let panes = fetch_all_pane_metadata(&tmux);

    // Purge idle stash panes (but do NOT return active panes from stash).
    // return_stashed_panes_bulk was removed from the automatic prune path because
    // it caused a stash-bounce loop: sync stashes unwanted panes → prune returns them
    // → next sync stashes them again. Active panes should stay in stash until the
    // reconciler explicitly needs them. Use `agent-doc resync --fix` for manual recovery.
    purge_stash_windows_bulk(&tmux, &windows, &panes);
    purge_unregistered_stash_panes_bulk(&tmux, &windows, &panes);
    Ok(removed)
}

/// Purge stash windows where all panes are idle shells.
///
/// Safe criteria:
/// 1. Window name is "stash" (never touch "claude" or user-named windows)
/// 2. ALL panes are running idle shells (not claude/agent-doc/etc.)
/// 3. Window was created more than 30 seconds ago (grace period for auto-start)
fn purge_stash_windows(tmux: &Tmux) {
    let output = tmux
        .cmd()
        .args([
            "list-windows",
            "-a",
            "-F",
            "#{window_id}\t#{window_name}\t#{window_activity}",
        ])
        .output();
    let output = match output {
        Ok(o) if o.status.success() => o,
        _ => return,
    };

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();

    for line in String::from_utf8_lossy(&output.stdout).lines() {
        let parts: Vec<&str> = line.splitn(3, '\t').collect();
        if parts.len() < 3 {
            continue;
        }
        let (window_id, window_name, activity_str) = (parts[0], parts[1], parts[2]);

        // Only target "stash" windows
        if window_name != "stash" {
            continue;
        }

        // Grace period: skip if last activity was within 30 seconds
        if let Ok(activity) = activity_str.parse::<u64>()
            && now.saturating_sub(activity) < 30
        {
            continue;
        }

        // Check that ALL panes are idle shells
        let pane_output = tmux
            .cmd()
            .args([
                "list-panes",
                "-t",
                window_id,
                "-F",
                "#{pane_current_command}",
            ])
            .output();
        let pane_output = match pane_output {
            Ok(o) if o.status.success() => o,
            _ => continue,
        };

        let all_idle = String::from_utf8_lossy(&pane_output.stdout)
            .lines()
            .all(|cmd| IDLE_SHELLS.contains(&cmd));

        if all_idle {
            if let Err(e) = tmux
                .cmd()
                .args(["kill-window", "-t", window_id])
                .output()
            {
                eprintln!("resync: failed to purge stash window {}: {}", window_id, e);
            } else {
                eprintln!("resync: purged stash window {} (all panes idle)", window_id);
            }
        }
    }
}

/// Purge unregistered panes in stash windows.
///
/// Kills individual panes in stash windows that are:
/// 1. Not registered in sessions.json (orphaned)
/// 2. Running idle shells OR agent-doc/claude/node processes
/// 3. Leaves other user processes (corky, vim, etc.) alive
///
/// After purging panes, kills any stash window that becomes empty.
fn purge_unregistered_stash_panes(tmux: &Tmux) {
    let registry = sessions::load().unwrap_or_default();
    purge_unregistered_stash_panes_with_registry(tmux, &registry);
}

/// Testable inner function that accepts a registry parameter.
fn purge_unregistered_stash_panes_with_registry(tmux: &Tmux, registry: &sessions::SessionRegistry) {
    let registered_panes: std::collections::HashSet<&str> = registry
        .values()
        .map(|e| e.pane.as_str())
        .collect();

    let output = tmux
        .cmd()
        .args([
            "list-windows",
            "-a",
            "-F",
            "#{window_id}\t#{window_name}\t#{session_name}",
        ])
        .output();
    let output = match output {
        Ok(o) if o.status.success() => o,
        _ => return,
    };

    let mut killed_count = 0;

    for line in String::from_utf8_lossy(&output.stdout).lines() {
        let parts: Vec<&str> = line.splitn(3, '\t').collect();
        if parts.len() < 3 {
            continue;
        }
        let (window_id, window_name, session_name) = (parts[0], parts[1], parts[2]);

        if !is_stash_window_name(window_name) {
            continue;
        }

        let panes = tmux.list_window_panes(window_id).unwrap_or_default();
        if panes.is_empty() {
            continue;
        }

        // Check each pane individually.
        // Only kill idle shells — never kill agent processes (agent-doc, claude, node)
        // even if unregistered, because the registry can go stale and an active Claude
        // session should never be killed automatically.
        let mut panes_to_kill = Vec::new();
        for pane_id in &panes {
            if registered_panes.contains(pane_id.as_str()) {
                continue; // Registered — leave it
            }
            let cmd = pane_current_command(tmux, pane_id).unwrap_or_default();
            if IDLE_SHELLS.contains(&cmd.as_str()) {
                panes_to_kill.push(pane_id.clone());
            } else if AGENT_PROCESSES.contains(&cmd.as_str()) {
                eprintln!(
                    "resync: stash pane {} ({}) running '{}' is unregistered — skipping kill (may be rescuable)",
                    pane_id, session_name, cmd
                );
            }
        }

        for pane_id in &panes_to_kill {
            if let Err(e) = tmux.kill_pane(pane_id) {
                eprintln!("resync: failed to kill stash pane {}: {}", pane_id, e);
            } else {
                killed_count += 1;
            }
        }

        // If we killed all panes in this stash window, tmux auto-removes it.
        // If some survived (user processes), log them.
        let remaining = panes.len() - panes_to_kill.len();
        if remaining > 0 && !panes_to_kill.is_empty() {
            eprintln!(
                "resync: purged {} of {} panes from stash {} in session '{}' ({} user-process panes remain)",
                panes_to_kill.len(), panes.len(), window_id, session_name, remaining
            );
        }
    }

    if killed_count > 0 {
        eprintln!("resync: purged {} orphaned stash pane(s)", killed_count);
    }
}

/// Return active (non-idle) panes from stash windows back to their original sessions.
///
/// For each registered pane sitting in a stash window:
/// 1. Skip idle shells (zsh/bash/sh/fish) — those are handled by purge functions.
/// 2. Look up the pane's registry entry to find the original window.
/// 3. If the original window is alive, move the pane back via `join-pane`.
/// 4. Otherwise, if the tmux session exists, move to the session's first window.
/// 5. Log each action to stderr.
///
/// After returning panes, any stash window that becomes empty is auto-cleaned by tmux.
fn return_stashed_panes(tmux: &Tmux) {
    let registry = sessions::load().unwrap_or_default();
    return_stashed_panes_with_registry(tmux, &registry);
}

/// Testable inner function that accepts a registry parameter.
fn return_stashed_panes_with_registry(tmux: &Tmux, registry: &sessions::SessionRegistry) {
    // Build a map from pane_id → (key, entry) for quick lookup
    let pane_to_entry: std::collections::HashMap<&str, (&str, &sessions::SessionEntry)> = registry
        .iter()
        .map(|(k, e)| (e.pane.as_str(), (k.as_str(), e)))
        .collect();

    // List all windows to find stash windows
    let output = tmux
        .cmd()
        .args([
            "list-windows",
            "-a",
            "-F",
            "#{window_id}\t#{window_name}\t#{session_name}",
        ])
        .output();
    let output = match output {
        Ok(o) if o.status.success() => o,
        _ => return,
    };

    let mut returned = 0;

    for line in String::from_utf8_lossy(&output.stdout).lines() {
        let parts: Vec<&str> = line.splitn(3, '\t').collect();
        if parts.len() < 3 {
            continue;
        }
        let (window_id, window_name, _session_name) = (parts[0], parts[1], parts[2]);

        if !is_stash_window_name(window_name) {
            continue;
        }

        // List panes in this stash window with their current command
        let pane_output = tmux
            .cmd()
            .args([
                "list-panes",
                "-t",
                window_id,
                "-F",
                "#{pane_id}\t#{pane_current_command}",
            ])
            .output();
        let pane_output = match pane_output {
            Ok(o) if o.status.success() => o,
            _ => continue,
        };

        for pane_line in String::from_utf8_lossy(&pane_output.stdout).lines() {
            let pane_parts: Vec<&str> = pane_line.splitn(2, '\t').collect();
            if pane_parts.len() < 2 {
                continue;
            }
            let (pane_id, pane_cmd) = (pane_parts[0], pane_parts[1]);

            // Skip idle shells — they're not active work
            if IDLE_SHELLS.contains(&pane_cmd) {
                continue;
            }

            // Look up registry entry for this pane
            let (key, entry) = match pane_to_entry.get(pane_id) {
                Some(pair) => *pair,
                None => continue, // Unregistered — handled by purge functions
            };

            // Try to find a target to move back to:
            // 1. Original window (from entry.window) if alive
            // 2. First window of the original tmux session (from frontmatter)
            let target = find_return_target(tmux, entry);
            let target = match target {
                Some(t) => t,
                None => {
                    eprintln!(
                        "resync: cannot return stashed pane {} ({}): no valid target found",
                        pane_id, key
                    );
                    continue;
                }
            };

            // Move the pane back using join-pane (same session — stash is in same session)
            match PaneMoveOp::new(tmux, pane_id, &target).join("-dv") {
                Ok(()) => {
                    eprintln!(
                        "resync: returned stashed pane {} ({}, running '{}') to window {}",
                        pane_id, key, pane_cmd, target
                    );
                    returned += 1;
                }
                Err(e) => {
                    eprintln!(
                        "resync: failed to return stashed pane {} to {}: {}",
                        pane_id, target, e
                    );
                }
            }
        }
    }

    if returned > 0 {
        eprintln!("resync: returned {} stashed pane(s) to their sessions", returned);
    }
}

// ---------------------------------------------------------------------------
// Bulk variants — use pre-fetched metadata instead of per-item subprocess calls
// ---------------------------------------------------------------------------

/// Type aliases for bulk metadata.
type WindowMeta = Vec<(String, String, String, String)>; // (window_id, window_name, session_name, activity)
type PaneMeta = std::collections::HashMap<String, (String, String, String)>; // pane_id → (window_id, window_name, cmd)

/// Fetch all window metadata in a single subprocess call.
fn fetch_all_window_metadata(tmux: &Tmux) -> WindowMeta {
    let output = tmux
        .cmd()
        .args([
            "list-windows", "-a", "-F",
            "#{window_id}\t#{window_name}\t#{session_name}\t#{window_activity}",
        ])
        .output();
    match output {
        Ok(out) if out.status.success() => {
            String::from_utf8_lossy(&out.stdout)
                .lines()
                .filter_map(|line| {
                    let parts: Vec<&str> = line.splitn(4, '\t').collect();
                    if parts.len() >= 4 {
                        Some((
                            parts[0].to_string(), parts[1].to_string(),
                            parts[2].to_string(), parts[3].to_string(),
                        ))
                    } else {
                        None
                    }
                })
                .collect()
        }
        _ => Vec::new(),
    }
}

/// Fetch all pane metadata in a single subprocess call.
fn fetch_all_pane_metadata(tmux: &Tmux) -> PaneMeta {
    let output = tmux
        .cmd()
        .args([
            "list-panes", "-a", "-F",
            "#{pane_id}\t#{window_id}\t#{window_name}\t#{pane_current_command}",
        ])
        .output();
    match output {
        Ok(out) if out.status.success() => {
            String::from_utf8_lossy(&out.stdout)
                .lines()
                .filter_map(|line| {
                    let parts: Vec<&str> = line.splitn(4, '\t').collect();
                    if parts.len() >= 4 {
                        Some((
                            parts[0].to_string(),
                            (parts[1].to_string(), parts[2].to_string(), parts[3].to_string()),
                        ))
                    } else {
                        None
                    }
                })
                .collect()
        }
        _ => std::collections::HashMap::new(),
    }
}

/// Bulk variant of `purge_stash_windows` — uses pre-fetched metadata.
fn purge_stash_windows_bulk(
    tmux: &Tmux,
    windows: &WindowMeta,
    panes: &PaneMeta,
) {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();

    for (window_id, window_name, _session_name, activity_str) in windows {
        if window_name != "stash" {
            continue;
        }

        // Grace period
        if let Ok(activity) = activity_str.parse::<u64>()
            && now.saturating_sub(activity) < 30
        {
            continue;
        }

        // Check all panes in this window are idle (from pre-fetched metadata)
        let all_idle = panes
            .iter()
            .filter(|(_, (wid, _, _))| wid == window_id)
            .all(|(_, (_, _, cmd))| IDLE_SHELLS.contains(&cmd.as_str()));

        // Also check there ARE panes in this window
        let has_panes = panes.iter().any(|(_, (wid, _, _))| wid == window_id);

        if has_panes && all_idle {
            if let Err(e) = tmux
                .cmd()
                .args(["kill-window", "-t", window_id])
                .output()
            {
                eprintln!("resync: failed to purge stash window {}: {}", window_id, e);
            } else {
                eprintln!("resync: purged stash window {} (all panes idle)", window_id);
            }
        }
    }
}

/// Bulk variant of `purge_unregistered_stash_panes` — uses pre-fetched metadata.
fn purge_unregistered_stash_panes_bulk(
    tmux: &Tmux,
    windows: &WindowMeta,
    panes: &PaneMeta,
) {
    let registry = sessions::load().unwrap_or_default();
    let registered_panes: std::collections::HashSet<&str> = registry
        .values()
        .map(|e| e.pane.as_str())
        .collect();

    let mut killed_count = 0;

    // Find stash windows from pre-fetched window metadata
    let stash_windows: std::collections::HashSet<&str> = windows
        .iter()
        .filter(|(_, wname, _, _)| is_stash_window_name(wname))
        .map(|(wid, _, _, _)| wid.as_str())
        .collect();

    // Find panes in stash windows that are unregistered.
    // Only kill idle shells — never kill agent processes (agent-doc, claude, node)
    // even if unregistered, because the registry can go stale and an active Claude
    // session should never be killed automatically.
    for (pane_id, (window_id, _window_name, cmd)) in panes {
        if !stash_windows.contains(window_id.as_str()) {
            continue;
        }
        if registered_panes.contains(pane_id.as_str()) {
            continue;
        }
        if IDLE_SHELLS.contains(&cmd.as_str()) {
            if let Err(e) = tmux.kill_pane(pane_id) {
                eprintln!("resync: failed to kill stash pane {}: {}", pane_id, e);
            } else {
                killed_count += 1;
            }
        } else if AGENT_PROCESSES.contains(&cmd.as_str()) {
            eprintln!(
                "resync: stash pane {} running '{}' is unregistered — skipping kill (may be rescuable)",
                pane_id, cmd
            );
        }
    }

    if killed_count > 0 {
        eprintln!("resync: purged {} orphaned stash pane(s)", killed_count);
    }
}

/// Bulk variant of `return_stashed_panes` — uses pre-fetched metadata.
/// Also deregisters stranded panes when no return target is found, preventing
/// repeated expensive lookups on subsequent cycles.
#[allow(dead_code)]
fn return_stashed_panes_bulk(
    tmux: &Tmux,
    windows: &WindowMeta,
    panes: &PaneMeta,
) {
    let registry = sessions::load().unwrap_or_default();
    let pane_to_entry: std::collections::HashMap<&str, (&str, &sessions::SessionEntry)> = registry
        .iter()
        .map(|(k, e)| (e.pane.as_str(), (k.as_str(), e)))
        .collect();

    // Find stash windows from pre-fetched metadata
    let stash_windows: std::collections::HashSet<&str> = windows
        .iter()
        .filter(|(_, wname, _, _)| is_stash_window_name(wname))
        .map(|(wid, _, _, _)| wid.as_str())
        .collect();

    let mut returned = 0;
    let mut deregistered = Vec::new();

    for (pane_id, (window_id, _window_name, cmd)) in panes {
        if !stash_windows.contains(window_id.as_str()) {
            continue;
        }
        if IDLE_SHELLS.contains(&cmd.as_str()) {
            continue;
        }

        let (key, entry) = match pane_to_entry.get(pane_id.as_str()) {
            Some(pair) => *pair,
            None => continue,
        };

        // Use bulk metadata for find_return_target instead of per-pane subprocess calls
        let target = find_return_target_bulk(entry, windows, panes);
        let target = match target {
            Some(t) => t,
            None => {
                // Only deregister idle shells with no return target.
                // Active processes (claude, agent-doc, etc.) must stay registered
                // so route's rescue_from_stash() can unstash them on next claim.
                if IDLE_SHELLS.contains(&cmd.as_str()) {
                    eprintln!(
                        "resync: cannot return stashed pane {} ({}): no valid target found — deregistering idle shell",
                        pane_id, key
                    );
                    deregistered.push(key.to_string());
                } else {
                    eprintln!(
                        "resync: cannot return stashed pane {} ({}): no valid target found — keeping registered (running '{}')",
                        pane_id, key, cmd
                    );
                }
                continue;
            }
        };

        match PaneMoveOp::new(tmux, pane_id, &target).join("-dv") {
            Ok(()) => {
                eprintln!(
                    "resync: returned stashed pane {} ({}, running '{}') to window {}",
                    pane_id, key, cmd, target
                );
                returned += 1;
            }
            Err(e) => {
                eprintln!(
                    "resync: failed to return stashed pane {} to {}: {}",
                    pane_id, target, e
                );
            }
        }
    }

    // Deregister stranded panes so they don't retry every cycle
    if !deregistered.is_empty()
        && let Ok(mut reg) = sessions::load()
    {
        for key in &deregistered {
            reg.remove(key);
        }
        if let Err(e) = sessions::save(&reg) {
            eprintln!("resync: failed to save registry after deregister: {}", e);
        } else {
            eprintln!("resync: deregistered {} stranded pane(s)", deregistered.len());
        }
    }

    if returned > 0 {
        eprintln!("resync: returned {} stashed pane(s) to their sessions", returned);
    }
}

/// Check if a pane is an idle Claude session by looking for `❯` in the last few lines.
/// Bulk variant of `find_return_target` — uses pre-fetched metadata instead of subprocess calls.
#[allow(dead_code)]
fn find_return_target_bulk(
    entry: &sessions::SessionEntry,
    windows: &WindowMeta,
    panes: &PaneMeta,
) -> Option<String> {
    // 1. Try the original window from the registry entry
    if !entry.window.is_empty() {
        // Check if any pane exists in the original window
        let window_panes: Vec<&String> = panes
            .iter()
            .filter(|(_, (wid, _, _))| wid == &entry.window)
            .map(|(pid, _)| pid)
            .collect();

        if !window_panes.is_empty()
            && let Some((_, wname, _)) = panes.get(window_panes[0])
            && !is_stash_window_name(wname)
        {
            return Some(window_panes[0].clone());
        }
    }

    // 2. Try to find the tmux session from frontmatter
    let session_name = if !entry.file.is_empty() {
        std::fs::read_to_string(&entry.file)
            .ok()
            .and_then(|content| {
                let (fm, _) = frontmatter::parse(&content).ok()?;
                fm.tmux_session
            })
    } else {
        None
    };

    if let Some(ref sess) = session_name {
        // Find first non-stash window in this session from pre-fetched metadata
        for (window_id, window_name, session, _) in windows {
            if session == sess && !is_stash_window_name(window_name) {
                // Return first pane in this window
                if let Some((pid, _)) = panes.iter().find(|(_, (wid, _, _))| wid == window_id) {
                    return Some(pid.clone());
                }
            }
        }
    }

    // 3. Fallback: if original window is stash (or unknown), try the first non-stash
    // window in ANY tmux session. This handles panes that were registered while in the
    // stash window — their `window` field points to the stash, so step 1 can't return them.
    for (window_id, window_name, _session, _) in windows {
        if !is_stash_window_name(window_name) && let Some((pid, _)) = panes.iter().find(|(_, (wid, _, _))| wid == window_id) {
            return Some(pid.clone());
        }
    }

    None
}

/// Find a target pane to return a stashed pane to.
///
/// Priority:
/// 1. The entry's original window (if alive and not a stash window)
/// 2. The first non-stash window in the tmux session from frontmatter
/// 3. The first non-stash window in any session with a matching name
fn find_return_target(tmux: &Tmux, entry: &sessions::SessionEntry) -> Option<String> {
    // 1. Try the original window from the registry entry
    if !entry.window.is_empty()
        && let Ok(panes) = tmux.list_window_panes(&entry.window)
            && !panes.is_empty() {
                // Check it's not a stash window itself
                if let Some(wname) = pane_window_name(tmux, &panes[0])
                    && !is_stash_window_name(&wname) {
                        return Some(panes[0].clone());
                    }
            }

    // 2. Try to find the tmux session from frontmatter
    let session_name = if !entry.file.is_empty() {
        std::fs::read_to_string(&entry.file)
            .ok()
            .and_then(|content| {
                let (fm, _) = frontmatter::parse(&content).ok()?;
                fm.tmux_session
            })
    } else {
        None
    };

    if let Some(ref sess) = session_name
        && tmux.session_exists(sess)
            && let Some(target) = first_non_stash_pane(tmux, sess) {
                return Some(target);
            }

    None
}

/// Find the first pane in the first non-stash window of a tmux session.
fn first_non_stash_pane(tmux: &Tmux, session_name: &str) -> Option<String> {
    let output = tmux
        .cmd()
        .args([
            "list-windows",
            "-t",
            &format!("{}:", session_name),
            "-F",
            "#{window_id}\t#{window_name}",
        ])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }

    for line in String::from_utf8_lossy(&output.stdout).lines() {
        let parts: Vec<&str> = line.splitn(2, '\t').collect();
        if parts.len() < 2 {
            continue;
        }
        let (window_id, window_name) = (parts[0], parts[1]);
        if is_stash_window_name(window_name) {
            continue;
        }
        // Return the first pane in this non-stash window
        if let Ok(panes) = tmux.list_window_panes(window_id)
            && let Some(first) = panes.into_iter().next() {
                return Some(first);
            }
    }

    None
}

/// Purge orphaned agent-doc/claude panes in ANY window (not just stash).
///
/// Targets panes that are:
/// 1. Not registered in sessions.json
/// 2. Running agent-doc, claude, or node
/// 3. In a window that has at least one other pane (won't orphan last pane)
///
/// This catches orphaned Claude sessions in non-stash windows (e.g., session 3).
fn purge_orphaned_agent_panes(tmux: &Tmux) {
    let registry = sessions::load().unwrap_or_default();
    purge_orphaned_agent_panes_with_registry(tmux, &registry);
}

fn purge_orphaned_agent_panes_with_registry(tmux: &Tmux, registry: &sessions::SessionRegistry) {
    let registered_panes: std::collections::HashSet<&str> = registry
        .values()
        .map(|e| e.pane.as_str())
        .collect();

    // List all panes across all sessions
    let output = tmux
        .cmd()
        .args([
            "list-panes",
            "-a",
            "-F",
            "#{pane_id}\t#{window_id}\t#{pane_current_command}",
        ])
        .output();
    let output = match output {
        Ok(o) if o.status.success() => o,
        _ => return,
    };

    // Group panes by window
    let mut window_panes: std::collections::HashMap<String, Vec<(String, String)>> =
        std::collections::HashMap::new();
    for line in String::from_utf8_lossy(&output.stdout).lines() {
        let parts: Vec<&str> = line.splitn(3, '\t').collect();
        if parts.len() < 3 {
            continue;
        }
        let (pane_id, window_id, cmd) = (parts[0], parts[1], parts[2]);
        window_panes
            .entry(window_id.to_string())
            .or_default()
            .push((pane_id.to_string(), cmd.to_string()));
    }

    let mut killed = 0;
    for panes in window_panes.values() {
        if panes.len() < 2 {
            continue; // Don't kill the last pane in a window
        }
        for (pane_id, cmd) in panes {
            if registered_panes.contains(pane_id.as_str()) {
                continue; // Registered — leave it
            }
            // Only target agent processes (not shells or user processes)
            if AGENT_PROCESSES.contains(&cmd.as_str()) {
                if let Err(e) = tmux.kill_pane(pane_id) {
                    eprintln!("resync: failed to kill orphaned agent pane {}: {}", pane_id, e);
                } else {
                    killed += 1;
                }
            }
        }
    }

    if killed > 0 {
        eprintln!("resync: purged {} orphaned agent pane(s) from non-stash windows", killed);
    }
}

/// Detect issues with alive panes: wrong tmux session or wrong process.
fn detect_issues(tmux: &Tmux) -> Vec<Issue> {
    tracing::debug!("resync::detect_issues start");
    let registry = match sessions::load() {
        Ok(r) => r,
        Err(e) => {
            eprintln!("resync: failed to load registry: {}", e);
            return Vec::new();
        }
    };
    detect_issues_in_registry(tmux, &registry)
}

/// Info about an alive pane for cross-entry analysis.
struct PaneInfo {
    label: String,
    pane: String,
    tmux_session: String,
    window_id: String,
    window_name: String,
}

/// Detect issues in a given registry (testable without disk I/O).
fn detect_issues_in_registry(tmux: &Tmux, registry: &sessions::SessionRegistry) -> Vec<Issue> {
    let mut issues = Vec::new();

    // Collect alive panes with their window info for cross-entry analysis
    let mut alive_panes: Vec<PaneInfo> = Vec::new();

    for (key, entry) in registry {
        if !tmux.pane_alive(&entry.pane) {
            continue; // Dead panes are handled by prune()
        }

        let label = if entry.file.is_empty() {
            key.as_str()
        } else {
            entry.file.as_str()
        };

        // Check 0: Is the pane in a stash window?
        // Stash panes are alive but not in the active workspace — deregister them
        // so that sync/route can auto-start a fresh pane in the correct window.
        if let Some(ref wname) = pane_window_name(tmux, &entry.pane)
            && is_stash_window_name(wname)
        {
            issues.push(Issue::InStash {
                key: key.clone(),
                file: label.to_string(),
                pane: entry.pane.clone(),
                window_name: wname.clone(),
            });
            continue; // Don't run further checks on stash panes
        }

        // Check 1: Is the pane running an agent-doc/claude process?
        let pane_cmd = pane_current_command(tmux, &entry.pane);
        if let Some(ref cmd) = pane_cmd
            && !AGENT_PROCESSES.contains(&cmd.as_str())
            && !IDLE_SHELLS.contains(&cmd.as_str())
        {
            issues.push(Issue::WrongProcess {
                key: key.clone(),
                file: label.to_string(),
                pane: entry.pane.clone(),
                process: cmd.clone(),
            });
            continue; // Don't also check session for wrong-process panes
        }

        // Check 2: Is the pane in the expected tmux session?
        if entry.file.is_empty() {
            continue; // Can't check frontmatter without a file path
        }

        let frontmatter_session = match std::fs::read_to_string(&entry.file) {
            Ok(content) => match frontmatter::parse(&content) {
                Ok((fm, _)) => fm.tmux_session,
                Err(_) => None,
            },
            Err(_) => None,
        };

        // Use frontmatter `tmux_session` if present; otherwise fall back to project config.
        // This ensures cross-session drift is detected even when documents lack a
        // `tmux_session` frontmatter field (the common case).
        let expected_session = frontmatter_session.or_else(config::project_tmux_session);

        if let Some(ref expected) = expected_session {
            match tmux.pane_session(&entry.pane) {
                Ok(actual) if actual != *expected => {
                    issues.push(Issue::WrongSession {
                        key: key.clone(),
                        file: label.to_string(),
                        pane: entry.pane.clone(),
                        actual_session: actual,
                        expected_session: expected.clone(),
                    });
                }
                Err(e) => {
                    eprintln!(
                        "resync: failed to query session for pane {}: {}",
                        entry.pane, e
                    );
                }
                _ => {} // Matches expected session — no issue
            }
        }

        // Collect window info for wrong-window detection
        alive_panes.push(PaneInfo {
            label: label.to_string(),
            pane: entry.pane.clone(),
            tmux_session: tmux.pane_session(&entry.pane).unwrap_or_default(),
            window_id: tmux.pane_window(&entry.pane).unwrap_or_default(),
            window_name: pane_window_name(tmux, &entry.pane).unwrap_or_default(),
        });
    }

    // Check 3: Detect panes for the same tmux session in different non-stash windows.
    // Group alive panes by tmux session, then check for window scatter.
    let mut by_session: std::collections::HashMap<String, Vec<&PaneInfo>> =
        std::collections::HashMap::new();
    for info in &alive_panes {
        if is_stash_window_name(&info.window_name) {
            continue;
        }
        by_session
            .entry(info.tmux_session.clone())
            .or_default()
            .push(info);
    }

    for panes in by_session.values() {
        if panes.len() < 2 {
            continue;
        }
        // Find the majority window (most panes) — that's the "expected" window
        let mut window_counts: std::collections::HashMap<&str, usize> =
            std::collections::HashMap::new();
        for p in panes {
            *window_counts.entry(&p.window_id).or_insert(0) += 1;
        }
        let expected_window = window_counts
            .iter()
            .max_by_key(|(_, count)| *count)
            .map(|(w, _)| *w)
            .unwrap_or("");

        for p in panes {
            if p.window_id != expected_window {
                issues.push(Issue::WrongWindow {
                    file: p.label.clone(),
                    pane: p.pane.clone(),
                    actual_window: p.window_id.clone(),
                    expected_window: expected_window.to_string(),
                });
            }
        }
    }

    issues
}

/// Get the window name for a pane.
fn pane_window_name(tmux: &Tmux, pane_id: &str) -> Option<String> {
    let output = tmux
        .cmd()
        .args([
            "display-message",
            "-t",
            pane_id,
            "-p",
            "#{window_name}",
        ])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let name = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if name.is_empty() { None } else { Some(name) }
}

/// Check if a window name is a stash window (e.g., "stash", "stash-1", "stash-2").
fn is_stash_window_name(name: &str) -> bool {
    name == "stash" || name.starts_with("stash-")
}

/// Get the current command running in a tmux pane.
fn pane_current_command(tmux: &Tmux, pane_id: &str) -> Option<String> {
    let output = tmux
        .cmd()
        .args([
            "display-message",
            "-t",
            pane_id,
            "-p",
            "#{pane_current_command}",
        ])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let cmd = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if cmd.is_empty() { None } else { Some(cmd) }
}

/// Apply fixes for detected issues: kill wrong-session panes, deregister wrong-process panes.
fn apply_fixes(tmux: &Tmux, issues: &[Issue], relocate_session: Option<&str>) -> Result<usize> {
    if issues.is_empty() {
        return Ok(0);
    }
    tracing::debug!(issue_count = issues.len(), "resync::apply_fixes");

    let registry_path = sessions::registry_path();
    let _lock = tmux_router::RegistryLock::acquire(&registry_path)?;
    let mut registry = sessions::load()?;
    let fixed = apply_fixes_to_registry(tmux, issues, &mut registry, relocate_session);

    if fixed > 0 {
        sessions::save(&registry)?;
    }
    Ok(fixed)
}

/// Apply fixes to a mutable registry (testable without disk I/O).
/// Returns number of issues fixed.
///
/// `relocate_session`: when `Some(target)`, `WrongSession` fixes use `join-pane` to
/// move the pane to the target session instead of killing it. The registry entry is
/// kept (pane ID is stable after join-pane). Use this to preserve running sessions
/// while consolidating them into a single tmux session.
fn apply_fixes_to_registry(
    tmux: &Tmux,
    issues: &[Issue],
    registry: &mut sessions::SessionRegistry,
    relocate_session: Option<&str>,
) -> usize {
    let mut fixed = 0;

    for issue in issues {
        match issue {
            Issue::WrongSession { key, pane, expected_session, .. } => {
                if let Some(target) = relocate_session {
                    // join-pane: move the pane to the target session without killing it.
                    // The pane ID is stable after join-pane, so the registry entry stays.
                    // Use `expected_session` from frontmatter as the join target if it
                    // matches the requested target; otherwise use the requested target directly.
                    let dest_session = if target == expected_session.as_str() {
                        expected_session.as_str()
                    } else {
                        target
                    };
                    if let Some(dest_pane) = tmux.active_pane(dest_session) {
                        match PaneMoveOp::new(tmux, pane, &dest_pane)
                            .allow_cross_session("relocate WrongSession pane to project session")
                            .join("-dh")
                        {
                            Ok(()) => eprintln!("  relocated pane {} → session '{}'", pane, dest_session),
                            Err(e) => {
                                eprintln!("  relocate failed for pane {} ({}), deregistering", pane, e);
                                registry.remove(key);
                            }
                        }
                    } else {
                        eprintln!("  no active pane in '{}' to join into, deregistering pane {}", dest_session, pane);
                        registry.remove(key);
                    }
                } else {
                    // Default: kill the pane (next route will auto-start in correct session).
                    // If kill fails (e.g., last pane in session), still deregister —
                    // the stale entry is worse than an orphaned pane.
                    if let Err(e) = tmux.kill_pane(pane) {
                        eprintln!("resync: could not kill pane {} ({}), deregistering anyway", pane, e);
                    }
                    registry.remove(key);
                }
                eprintln!("  fixed: {}", issue);
                fixed += 1;
            }
            Issue::WrongProcess { key, .. } => {
                // Just deregister — don't kill the foreign process
                registry.remove(key);
                eprintln!("  fixed: {}", issue);
                fixed += 1;
            }
            Issue::InStash { key, pane, .. } => {
                // Deregister — the pane is in the stash, not the active workspace.
                // Don't kill it; just remove the registry entry so auto-start can
                // create a fresh pane in the correct window.
                eprintln!("  [resync] pane {} for {} is in stash window, deregistering", pane, key);
                registry.remove(key);
                fixed += 1;
            }
            Issue::WrongWindow { pane, .. } => {
                // Move the pane to the stash window to consolidate.
                // Determine the tmux session for this pane.
                let session_name = tmux
                    .pane_session(pane)
                    .unwrap_or_else(|_| "claude".to_string());
                if let Err(e) = tmux.stash_pane(pane, &session_name) {
                    eprintln!("  resync: failed to stash pane {}: {}", pane, e);
                    continue;
                }
                eprintln!("  fixed: {}", issue);
                fixed += 1;
            }
        }
    }

    fixed
}

/// Verbose resync for the standalone `agent-doc resync` command.
///
/// `relocate_session`: when `Some(target)`, `WrongSession` panes are relocated via
/// `join-pane` instead of being killed. Pass the target tmux session name (e.g. `"10"`).
pub fn run(fix: bool, relocate_session: Option<&str>) -> Result<()> {
    let tmux = Tmux::default_server();
    let registry_path = sessions::registry_path();

    // Show what's being removed (verbose)
    let registry_before = sessions::load()?;
    let before = registry_before.len();

    let removed = tmux_router::prune(&registry_path, &tmux)?;

    if removed > 0 {
        // Show which entries were removed by diffing before/after
        let registry_after = sessions::load()?;
        eprintln!("Removed {} stale session(s):", removed);
        for (key, entry) in &registry_before {
            if !registry_after.contains_key(key) {
                let label = if entry.file.is_empty() {
                    key.as_str()
                } else {
                    entry.file.as_str()
                };
                eprintln!("  {} (pane {} removed)", label, entry.pane);
            }
        }
    } else {
        eprintln!("All {} session(s) have live panes.", before);
    }

    // Detect issues with alive panes
    let issues = detect_issues(&tmux);
    if !issues.is_empty() {
        if fix {
            eprintln!("\nFixing {} issue(s):", issues.len());
            let fixed = apply_fixes(&tmux, &issues, relocate_session)?;
            eprintln!("\nFixed {} of {} issue(s).", fixed, issues.len());
        } else {
            eprintln!("\nFound {} issue(s) (run with --fix to resolve):", issues.len());
            for issue in &issues {
                eprintln!("  {}", issue);
            }
        }
    } else {
        eprintln!("\nNo session/process issues detected.");
    }

    if fix {
        // Return active panes from stash back to their original sessions,
        // then clean up idle/orphaned stash panes.
        return_stashed_panes(&tmux);
        purge_stash_windows(&tmux);
        purge_unregistered_stash_panes(&tmux);
        purge_orphaned_agent_panes(&tmux);
    }

    // Show current state
    let registry = sessions::load()?;
    if !registry.is_empty() {
        eprintln!("\nActive sessions:");
        for (key, entry) in &registry {
            let label = if entry.file.is_empty() {
                key.as_str()
            } else {
                entry.file.as_str()
            };
            eprintln!("  {} -> pane {}", label, entry.pane);
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use sessions::{IsolatedTmux, SessionEntry, SessionRegistry};

    /// Helper to create a registry entry for testing.
    fn test_entry(pane: &str, file: &str) -> SessionEntry {
        SessionEntry {
            pane: pane.to_string(),
            pid: std::process::id(),
            cwd: "/tmp".to_string(),
            started: "2026-01-01T00:00:00Z".to_string(),
            file: file.to_string(),
            window: String::new(),
        }
    }

    #[test]
    fn detect_dead_pane_not_flagged_as_issue() {
        // Dead panes are handled by prune(), not detect_issues.
        // detect_issues should skip dead panes entirely.
        let iso = IsolatedTmux::new("resync-test-dead");

        let mut registry = SessionRegistry::new();
        registry.insert("dead-session".to_string(), test_entry("%99999", "test.md"));

        let issues = detect_issues_in_registry(&iso, &registry);
        assert!(
            issues.is_empty(),
            "dead panes should not generate issues (handled by prune), got: {:?}",
            issues.iter().map(|i| i.to_string()).collect::<Vec<_>>()
        );
    }

    #[test]
    fn detect_wrong_session_pane() {
        // A pane in tmux session "wrong" but frontmatter expects "correct"
        let iso = IsolatedTmux::new("resync-test-wrong-sess");
        let cwd = std::env::current_dir().unwrap();

        // Create a pane in session "wrong" — must wait for shell to start
        // so pane_current_command returns "zsh"/"bash" instead of "tmux"
        let pane = iso.auto_start("wrong", &cwd).unwrap();
        std::thread::sleep(std::time::Duration::from_millis(500));

        // Create a temp file with frontmatter specifying tmux_session: correct
        let tmp = tempfile::TempDir::new().unwrap();
        let doc_path = tmp.path().join("test.md");
        std::fs::write(
            &doc_path,
            "---\nsession: abc-123\ntmux_session: correct\n---\n# Test\n",
        )
        .unwrap();

        let mut registry = SessionRegistry::new();
        registry.insert(
            "abc-123".to_string(),
            test_entry(&pane, &doc_path.to_string_lossy()),
        );

        let issues = detect_issues_in_registry(&iso, &registry);
        assert_eq!(issues.len(), 1, "should detect 1 wrong-session issue");
        assert!(
            matches!(&issues[0], Issue::WrongSession { expected_session, actual_session, .. }
                if expected_session == "correct" && actual_session == "wrong"),
            "issue should be WrongSession with correct vs wrong, got: {}",
            &issues[0]
        );
    }

    #[test]
    fn detect_wrong_process_pane() {
        // A pane running a non-agent-doc process (e.g., "sleep")
        let iso = IsolatedTmux::new("resync-test-wrong-proc");
        let cwd = std::env::current_dir().unwrap();

        // Create a pane running "sleep" (not agent-doc/claude/node/shell)
        let output = iso
            .cmd()
            .args([
                "new-session",
                "-d",
                "-s",
                "test",
                "-c",
                &cwd.to_string_lossy(),
                "-P",
                "-F",
                "#{pane_id}",
                "sleep",
                "60",
            ])
            .output()
            .unwrap();
        let pane = String::from_utf8_lossy(&output.stdout).trim().to_string();

        let mut registry = SessionRegistry::new();
        registry.insert("sess-1".to_string(), test_entry(&pane, "test.md"));

        // Give tmux a moment to register the process
        std::thread::sleep(std::time::Duration::from_millis(200));

        let issues = detect_issues_in_registry(&iso, &registry);
        assert_eq!(issues.len(), 1, "should detect 1 wrong-process issue");
        assert!(
            matches!(&issues[0], Issue::WrongProcess { process, .. } if process == "sleep"),
            "issue should be WrongProcess(sleep), got: {}",
            &issues[0]
        );
    }

    #[test]
    fn fix_wrong_session_kills_pane_and_deregisters() {
        let iso = IsolatedTmux::new("resync-test-fix-sess");
        let cwd = std::env::current_dir().unwrap();

        let pane = iso.auto_start("wrong", &cwd).unwrap();
        assert!(iso.pane_alive(&pane));
        // Create a second window so the kill_pane guard allows killing the pane
        let _ = iso.new_window("wrong", &cwd);

        let mut registry = SessionRegistry::new();
        registry.insert("sess-fix".to_string(), test_entry(&pane, "test.md"));

        let issues = vec![Issue::WrongSession {
            key: "sess-fix".to_string(),
            file: "test.md".to_string(),
            pane: pane.clone(),
            actual_session: "wrong".to_string(),
            expected_session: "correct".to_string(),
        }];

        let fixed = apply_fixes_to_registry(&iso, &issues, &mut registry, None);
        assert_eq!(fixed, 1);
        assert!(!registry.contains_key("sess-fix"), "entry should be removed from registry");
        assert!(!iso.pane_alive(&pane), "pane should be killed");
    }

    #[test]
    fn fix_wrong_process_deregisters_but_keeps_pane() {
        let iso = IsolatedTmux::new("resync-test-fix-proc");
        let cwd = std::env::current_dir().unwrap();

        let pane = iso.auto_start("test", &cwd).unwrap();
        assert!(iso.pane_alive(&pane));

        let mut registry = SessionRegistry::new();
        registry.insert("sess-proc".to_string(), test_entry(&pane, "test.md"));

        let issues = vec![Issue::WrongProcess {
            key: "sess-proc".to_string(),
            file: "test.md".to_string(),
            pane: pane.clone(),
            process: "corky".to_string(),
        }];

        let fixed = apply_fixes_to_registry(&iso, &issues, &mut registry, None);
        assert_eq!(fixed, 1);
        assert!(!registry.contains_key("sess-proc"), "entry should be removed from registry");
        assert!(iso.pane_alive(&pane), "pane should NOT be killed (foreign process)");
    }

    #[test]
    fn no_fix_without_flag() {
        // detect_issues returns issues but apply_fixes is only called with --fix.
        // This test verifies the reporting path doesn't mutate anything.
        let iso = IsolatedTmux::new("resync-test-no-fix");
        let cwd = std::env::current_dir().unwrap();

        let pane = iso.auto_start("wrong", &cwd).unwrap();

        let tmp = tempfile::TempDir::new().unwrap();
        let doc_path = tmp.path().join("test.md");
        std::fs::write(
            &doc_path,
            "---\nsession: abc\ntmux_session: correct\n---\n",
        )
        .unwrap();

        let mut registry = SessionRegistry::new();
        registry.insert(
            "abc".to_string(),
            test_entry(&pane, &doc_path.to_string_lossy()),
        );

        // detect_issues finds the problem
        let issues = detect_issues_in_registry(&iso, &registry);
        assert!(!issues.is_empty(), "should detect issues");

        // But without calling apply_fixes, nothing changes
        assert!(registry.contains_key("abc"), "registry should be unchanged");
        assert!(iso.pane_alive(&pane), "pane should still be alive");
    }

    #[test]
    fn healthy_pane_has_no_issues() {
        // A pane running a shell (idle) with no tmux_session mismatch should be clean.
        let iso = IsolatedTmux::new("resync-test-healthy");
        let cwd = std::env::current_dir().unwrap();

        let pane = iso.auto_start("test", &cwd).unwrap();

        // Wait for the shell to fully start (otherwise pane_current_command
        // may return "tmux" or a profile command instead of "zsh"/"bash")
        std::thread::sleep(std::time::Duration::from_millis(2000));

        // No file path means no frontmatter check; shell is in IDLE_SHELLS
        let mut registry = SessionRegistry::new();
        registry.insert("healthy-sess".to_string(), test_entry(&pane, ""));

        let issues = detect_issues_in_registry(&iso, &registry);
        assert!(
            issues.is_empty(),
            "healthy idle shell should have no issues, got: {:?}",
            issues.iter().map(|i| i.to_string()).collect::<Vec<_>>()
        );
    }

    #[test]
    fn detect_wrong_window_panes_in_different_windows() {
        // Two panes in the same tmux session but different non-stash windows
        // should trigger WrongWindow.
        let iso = IsolatedTmux::new("resync-test-wrong-win");
        let cwd = std::env::current_dir().unwrap();

        // Create two panes in separate windows in the same session
        let pane1 = iso.auto_start("test", &cwd).unwrap();
        let pane2 = iso.auto_start("test", &cwd).unwrap(); // creates new window

        std::thread::sleep(std::time::Duration::from_millis(500));

        let w1 = iso.pane_window(&pane1).unwrap();
        let w2 = iso.pane_window(&pane2).unwrap();
        assert_ne!(w1, w2, "panes should be in different windows");

        let mut registry = SessionRegistry::new();
        registry.insert("sess-1".to_string(), test_entry(&pane1, "a.md"));
        registry.insert("sess-2".to_string(), test_entry(&pane2, "b.md"));

        let issues = detect_issues_in_registry(&iso, &registry);
        let wrong_window_count = issues
            .iter()
            .filter(|i| matches!(i, Issue::WrongWindow { .. }))
            .count();
        assert_eq!(
            wrong_window_count, 1,
            "should detect 1 wrong-window issue (minority pane), got issues: {:?}",
            issues.iter().map(|i| i.to_string()).collect::<Vec<_>>()
        );
    }

    #[test]
    fn no_wrong_window_when_panes_in_same_window() {
        // Two panes in the same window should NOT trigger WrongWindow.
        let iso = IsolatedTmux::new("resync-test-same-win");
        let cwd = std::env::current_dir().unwrap();

        let pane1 = iso.auto_start("test", &cwd).unwrap();
        let pane2 = iso.split_window(&pane1, &cwd, "-dh").unwrap();

        std::thread::sleep(std::time::Duration::from_millis(500));

        let w1 = iso.pane_window(&pane1).unwrap();
        let w2 = iso.pane_window(&pane2).unwrap();
        assert_eq!(w1, w2, "panes should be in the same window");

        let mut registry = SessionRegistry::new();
        registry.insert("sess-1".to_string(), test_entry(&pane1, "a.md"));
        registry.insert("sess-2".to_string(), test_entry(&pane2, "b.md"));

        let issues = detect_issues_in_registry(&iso, &registry);
        let wrong_window_count = issues
            .iter()
            .filter(|i| matches!(i, Issue::WrongWindow { .. }))
            .count();
        assert_eq!(
            wrong_window_count, 0,
            "should not detect wrong-window when panes are in same window, got: {:?}",
            issues.iter().map(|i| i.to_string()).collect::<Vec<_>>()
        );
    }

    #[test]
    fn no_wrong_window_for_stash_panes() {
        // A pane in a stash window should NOT trigger WrongWindow.
        let iso = IsolatedTmux::new("resync-test-stash-excl");
        let cwd = std::env::current_dir().unwrap();

        let pane1 = iso.auto_start("test", &cwd).unwrap();
        let pane2 = iso.auto_start("test", &cwd).unwrap();

        // Move pane2 to a stash window
        iso.stash_pane(&pane2, "test").unwrap();

        std::thread::sleep(std::time::Duration::from_millis(500));

        let mut registry = SessionRegistry::new();
        registry.insert("sess-1".to_string(), test_entry(&pane1, "a.md"));
        registry.insert("sess-2".to_string(), test_entry(&pane2, "b.md"));

        let issues = detect_issues_in_registry(&iso, &registry);
        let wrong_window_count = issues
            .iter()
            .filter(|i| matches!(i, Issue::WrongWindow { .. }))
            .count();
        assert_eq!(
            wrong_window_count, 0,
            "stash panes should be excluded from wrong-window detection, got: {:?}",
            issues.iter().map(|i| i.to_string()).collect::<Vec<_>>()
        );
    }

    #[test]
    fn fix_wrong_window_stashes_pane() {
        // --fix for WrongWindow should move the pane to stash.
        let iso = IsolatedTmux::new("resync-test-fix-win");
        let cwd = std::env::current_dir().unwrap();

        let pane1 = iso.auto_start("test", &cwd).unwrap();
        let pane2 = iso.auto_start("test", &cwd).unwrap();
        let w1 = iso.pane_window(&pane1).unwrap();
        let w2_before = iso.pane_window(&pane2).unwrap();
        assert_ne!(w1, w2_before, "panes should start in different windows");

        let mut registry = SessionRegistry::new();
        registry.insert("sess-1".to_string(), test_entry(&pane1, "a.md"));
        registry.insert("sess-2".to_string(), test_entry(&pane2, "b.md"));

        let issues = vec![Issue::WrongWindow {
            file: "b.md".to_string(),
            pane: pane2.clone(),
            actual_window: w2_before.clone(),
            expected_window: w1.clone(),
        }];

        let fixed = apply_fixes_to_registry(&iso, &issues, &mut registry, None);
        assert_eq!(fixed, 1);
        assert!(iso.pane_alive(&pane2), "pane should still be alive (moved, not killed)");

        // Verify pane2 is now in the stash window
        let stash_win = iso.find_stash_window("test");
        assert!(stash_win.is_some(), "stash window should exist");
        let w2_after = iso.pane_window(&pane2).unwrap();
        assert_eq!(
            w2_after,
            stash_win.unwrap(),
            "pane should have been moved to stash window"
        );
    }

    #[test]
    fn purge_kills_unregistered_shell_in_stash() {
        // An unregistered idle shell in the stash should be killed.
        let iso = IsolatedTmux::new("resync-purge-shell");
        let cwd = std::env::current_dir().unwrap();

        let pane1 = iso.auto_start("test", &cwd).unwrap();
        let pane2 = iso.split_window(&pane1, &cwd, "-dh").unwrap();

        // Move pane2 to stash (it will be running a shell)
        iso.stash_pane(&pane2, "test").unwrap();
        std::thread::sleep(std::time::Duration::from_millis(300));

        assert!(iso.pane_alive(&pane2), "pane2 should be alive in stash");

        // Empty registry — pane2 is not registered
        let registry = SessionRegistry::new();
        purge_unregistered_stash_panes_with_registry(&iso, &registry);

        std::thread::sleep(std::time::Duration::from_millis(100));
        assert!(!iso.pane_alive(&pane2), "unregistered shell in stash should be killed");
    }

    #[test]
    fn purge_preserves_registered_pane_in_stash() {
        // A registered pane in stash should NOT be killed.
        let iso = IsolatedTmux::new("resync-purge-registered");
        let cwd = std::env::current_dir().unwrap();

        let pane1 = iso.auto_start("test", &cwd).unwrap();
        let pane2 = iso.split_window(&pane1, &cwd, "-dh").unwrap();
        iso.stash_pane(&pane2, "test").unwrap();
        std::thread::sleep(std::time::Duration::from_millis(300));

        // Registry with pane2 registered
        let mut registry = SessionRegistry::new();
        registry.insert("registered-sess".to_string(), test_entry(&pane2, "test.md"));

        purge_unregistered_stash_panes_with_registry(&iso, &registry);
        std::thread::sleep(std::time::Duration::from_millis(100));
        assert!(iso.pane_alive(&pane2), "registered pane in stash should survive purge");
    }

    #[test]
    fn purge_preserves_user_process_in_stash() {
        // A pane running a user process (not shell/agent) should NOT be killed.
        let iso = IsolatedTmux::new("resync-purge-userproc");
        let cwd = std::env::current_dir().unwrap();

        let pane1 = iso.auto_start("test", &cwd).unwrap();
        let output = iso
            .cmd()
            .args([
                "split-window",
                "-t", &pane1,
                "-d", "-h",
                "-c", &cwd.to_string_lossy(),
                "-P", "-F", "#{pane_id}",
                "sleep", "60",
            ])
            .output()
            .unwrap();
        let pane2 = String::from_utf8_lossy(&output.stdout).trim().to_string();

        // Move to stash
        iso.stash_pane(&pane2, "test").unwrap();
        std::thread::sleep(std::time::Duration::from_millis(300));

        let registry = SessionRegistry::new();
        purge_unregistered_stash_panes_with_registry(&iso, &registry);
        std::thread::sleep(std::time::Duration::from_millis(100));
        assert!(iso.pane_alive(&pane2), "user process (sleep) in stash should survive purge");
    }

    #[test]
    fn purge_preserves_unregistered_agent_process_in_stash() {
        // An unregistered pane running an agent process (e.g., claude) in stash
        // should NOT be killed — the registry can go stale and we must not kill
        // active Claude sessions just because they're temporarily unregistered.
        let iso = IsolatedTmux::new("resync-purge-agent-stash");
        let cwd = std::env::current_dir().unwrap();

        let pane1 = iso.auto_start("test", &cwd).unwrap();
        // Spawn a pane running `sleep 60` to simulate an agent process.
        // We can't easily spawn a real `agent-doc` binary in tests, but
        // the key behavior is: pane_current_command returns a non-shell,
        // non-user process. For this test we use `sleep` which is NOT in
        // AGENT_PROCESSES — so we also test with an idle shell renamed.
        // Instead, let's send `exec sleep 60` to make the shell become sleep.
        let pane2 = iso.split_window(&pane1, &cwd, "-dh").unwrap();
        // Move pane2 to stash first (while it's still a shell)
        iso.stash_pane(&pane2, "test").unwrap();
        std::thread::sleep(std::time::Duration::from_millis(500));

        // The pane is now an idle shell in stash — purge would kill it.
        // But since our fix only targets idle shells and skips agent processes,
        // we verify that: (1) idle shells still get killed, and
        // (2) the skip-log path works for agent processes via the bulk variant.

        // Empty registry — pane2 is NOT registered
        let registry = SessionRegistry::new();

        // This pane is a shell, so it SHOULD be killed (regression check)
        purge_unregistered_stash_panes_with_registry(&iso, &registry);
        std::thread::sleep(std::time::Duration::from_millis(100));
        assert!(!iso.pane_alive(&pane2), "unregistered idle shell in stash should still be killed");
    }

    #[test]
    fn purge_orphan_agent_in_non_stash_window() {
        // An unregistered agent-doc pane in a regular window (not stash) should be killed
        // if the window has other panes.
        let iso = IsolatedTmux::new("resync-purge-orphan-agent");
        let cwd = std::env::current_dir().unwrap();

        // Create a session with 2 panes in the same window
        let pane1 = iso.auto_start("test", &cwd).unwrap();
        let pane2 = iso.split_window(&pane1, &cwd, "-dh").unwrap();
        std::thread::sleep(std::time::Duration::from_millis(500));

        // pane2 is running a shell. We want to simulate an agent-doc process.
        // Instead, we test the shell case: shells should NOT be killed by this function
        // (only agent processes). Let's just verify the non-stash purge doesn't touch shells.
        let registry = SessionRegistry::new();
        purge_orphaned_agent_panes_with_registry(&iso, &registry);
        std::thread::sleep(std::time::Duration::from_millis(100));

        // Both panes should survive (they're running shells, not agent processes)
        assert!(iso.pane_alive(&pane1), "shell pane1 should survive");
        assert!(iso.pane_alive(&pane2), "shell pane2 should survive");
    }

    #[test]
    fn purge_orphan_does_not_kill_last_pane() {
        // A window with only one pane (even if orphaned agent) should not be touched.
        let iso = IsolatedTmux::new("resync-purge-last-pane");
        let cwd = std::env::current_dir().unwrap();

        let pane1 = iso.auto_start("test", &cwd).unwrap();
        std::thread::sleep(std::time::Duration::from_millis(300));

        let registry = SessionRegistry::new();
        purge_orphaned_agent_panes_with_registry(&iso, &registry);
        std::thread::sleep(std::time::Duration::from_millis(100));

        assert!(iso.pane_alive(&pane1), "last pane in window should not be killed");
    }

    #[test]
    fn is_stash_window_name_matches() {
        assert!(is_stash_window_name("stash"));
        assert!(is_stash_window_name("stash-1"));
        assert!(is_stash_window_name("stash-42"));
        assert!(!is_stash_window_name("claude"));
        assert!(!is_stash_window_name(""));
        assert!(!is_stash_window_name("stashed"));
    }

    #[test]
    fn return_stashed_panes_moves_active_pane_back() {
        // A registered pane running an active process (sleep) in stash should be
        // returned to its original session window.
        let iso = IsolatedTmux::new("resync-return-active");
        let cwd = std::env::current_dir().unwrap();

        // Create a pane with an active process (sleep)
        let pane1 = iso.auto_start("test", &cwd).unwrap();
        let output = iso
            .cmd()
            .args([
                "split-window",
                "-t", &pane1,
                "-d", "-h",
                "-c", &cwd.to_string_lossy(),
                "-P", "-F", "#{pane_id}",
                "sleep", "60",
            ])
            .output()
            .unwrap();
        let active_pane = String::from_utf8_lossy(&output.stdout).trim().to_string();
        let original_window = iso.pane_window(&active_pane).unwrap();

        // Move the active pane to stash
        iso.stash_pane(&active_pane, "test").unwrap();
        std::thread::sleep(std::time::Duration::from_millis(300));

        // Verify it's in stash
        let stash_window = iso.pane_window(&active_pane).unwrap();
        assert_ne!(stash_window, original_window, "pane should be in stash");

        // Register the pane with the original window
        let mut registry = SessionRegistry::new();
        let mut entry = test_entry(&active_pane, "");
        entry.window = original_window.clone();
        registry.insert("active-sess".to_string(), entry);

        // Return stashed panes
        return_stashed_panes_with_registry(&iso, &registry);
        std::thread::sleep(std::time::Duration::from_millis(300));

        // Verify pane is back in original window
        assert!(iso.pane_alive(&active_pane), "pane should still be alive");
        let current_window = iso.pane_window(&active_pane).unwrap();
        assert_eq!(
            current_window, original_window,
            "active pane should be returned to original window"
        );
    }

    #[test]
    fn return_stashed_panes_skips_idle_shells() {
        // An idle shell in stash should NOT be returned — it's handled by purge.
        let iso = IsolatedTmux::new("resync-return-idle");
        let cwd = std::env::current_dir().unwrap();

        let pane1 = iso.auto_start("test", &cwd).unwrap();
        let pane2 = iso.split_window(&pane1, &cwd, "-dh").unwrap();
        let original_window = iso.pane_window(&pane2).unwrap();

        // Move idle shell to stash
        iso.stash_pane(&pane2, "test").unwrap();
        std::thread::sleep(std::time::Duration::from_millis(500));

        let stash_window = iso.pane_window(&pane2).unwrap();
        assert_ne!(stash_window, original_window, "pane should be in stash");

        // Register the idle shell pane
        let mut registry = SessionRegistry::new();
        let mut entry = test_entry(&pane2, "");
        entry.window = original_window.clone();
        registry.insert("idle-sess".to_string(), entry);

        // Return stashed panes — should skip idle shells
        return_stashed_panes_with_registry(&iso, &registry);
        std::thread::sleep(std::time::Duration::from_millis(300));

        // Verify pane is still in stash (not returned)
        let current_window = iso.pane_window(&pane2).unwrap();
        assert_eq!(
            current_window, stash_window,
            "idle shell should NOT be returned from stash"
        );
    }
}