muster-workspace 0.3.1

A terminal workspace for running CLI agents and dev processes side by side
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
use std::{
    env, fs,
    io::{Read, Write},
    path::{Path, PathBuf},
};

use atomic_write_file::AtomicWriteFile;
use directories::BaseDirs;
use getset::{CopyGetters, Getters};
use serde_json::{Map, Value, json};
use strum::Display;
use thiserror::Error;
use toml_edit::{ArrayOfTables, DocumentMut, Item, Table};
use typed_builder::TypedBuilder;

use crate::{
    constants::MUSTER_AGENT_SESSION_ENV,
    domain::{
        agent_session::{AgentProcessId, AgentSessionId, NativeSessionId},
        port::AgentSessionStore,
        process::{AGENT_PROTOCOL_VERSION, AgentTool},
    },
};

/// Claude Code user settings relative to the user's home directory.
const CLAUDE_SETTINGS: &str = ".claude/settings.json";
/// Default Codex configuration directory relative to the user's home directory.
const CODEX_CONFIG_DIR: &str = ".codex";
/// Codex hook configuration file relative to the Codex configuration directory.
const CODEX_HOOKS_FILE: &str = "hooks.json";
/// Environment variable overriding Codex's configuration directory.
const CODEX_HOME_ENV: &str = "CODEX_HOME";
/// Gemini CLI user settings relative to the user's home directory.
const GEMINI_SETTINGS: &str = ".gemini/settings.json";
/// Copilot CLI's dedicated Muster hook relative to the user's home directory.
const COPILOT_HOOK: &str = ".copilot/hooks/muster.json";
/// Kimi Code configuration relative to the user's home directory.
const KIMI_CONFIG: &str = ".kimi-code/config.toml";
/// Amp's dedicated Muster plugin relative to the platform config directory.
const AMP_PLUGIN: &str = "amp/plugins/muster.ts";
/// OpenCode's dedicated Muster plugin relative to its XDG config directory.
const OPENCODE_PLUGIN: &str = "opencode/plugins/muster.js";
/// Environment variable controlling the XDG configuration root.
const XDG_CONFIG_HOME_ENV: &str = "XDG_CONFIG_HOME";
/// XDG configuration root used when the environment does not override it.
const XDG_CONFIG_HOME_DEFAULT: &str = ".config";
/// Lifecycle event used by JSON-configured providers.
const SESSION_START_EVENT: &str = "SessionStart";
/// Lifecycle event used by Copilot's camel-case hook format.
const COPILOT_SESSION_START_EVENT: &str = "sessionStart";
/// Copilot hook key holding the PowerShell command.
#[cfg(windows)]
const COPILOT_POWERSHELL_KEY: &str = "powershell";
/// Copilot hook key holding the POSIX shell command.
#[cfg(not(windows))]
const COPILOT_BASH_KEY: &str = "bash";
/// Kimi lifecycle matcher covering new, resumed, and reset sessions.
const KIMI_SESSION_MATCHER: &str = "startup|resume|clear";
/// Canonical lifecycle event accepted by the versioned wire protocol.
const PROTOCOL_SESSION_STARTED: &str = "session_started";
/// Hidden CLI subcommand containing provider lifecycle commands.
const HOOK_SUBCOMMAND: &str = "hook";
/// Hidden CLI action that records a provider lifecycle event.
const CAPTURE_SUBCOMMAND: &str = "capture";
/// Forms the `hook capture` invocation takes in configs: the shell command
/// pair and the JSON argument-array pair, used to tell Stale from Missing.
const STALE_MARKERS: [&str; 2] = ["hook capture", "\"hook\",\"capture\""];
/// CLI argument identifying the provider that emitted a lifecycle event.
const CAPTURE_PROVIDER_ARGUMENT: &str = "--provider";
/// CLI argument identifying the provider process that invoked a capture hook.
const CAPTURE_PROCESS_ID_ARGUMENT: &str = "--process-id";
/// CLI argument identifying the provider process's immediate parent.
const CAPTURE_PARENT_PROCESS_ID_ARGUMENT: &str = "--parent-process-id";
/// Line-comment prefixes across provider config formats (TOML/shell-style
/// and JS/TS), used to skip hooks the provider never evaluates.
const COMMENT_PREFIXES: [&str; 2] = ["#", "//"];
/// Maximum provider-config symlinks followed before treating the path as a
/// cycle or an unreasonable chain.
const MAX_PROVIDER_CONFIG_SYMLINKS: usize = 40;

/// Failures while installing or receiving provider lifecycle integrations.
#[derive(Debug, Error)]
pub enum HookError {
    /// No user directories could be resolved on this platform.
    #[error("no user configuration directory is available")]
    NoUserDirs,
    /// The running executable path cannot be represented in provider config.
    #[error("the muster executable path is not valid UTF-8")]
    InvalidExecutable,
    /// A hook payload did not contain a usable provider session identity.
    #[error("the hook payload does not contain a session ID")]
    MissingSessionId,
    /// A hook did not report a valid parent provider process ID.
    #[error("the hook did not report a valid provider process ID")]
    MissingProviderProcessId,
    /// A canonical event uses a protocol version this binary does not support.
    #[error("unsupported agent protocol version {0}")]
    UnsupportedProtocolVersion(u64),
    /// A canonical event name is not part of the supported protocol version.
    #[error("unsupported agent protocol event {0}")]
    UnsupportedProtocolEvent(String),
    /// A versioned event omitted its required event name.
    #[error("the agent protocol event name is missing")]
    MissingProtocolEvent,
    /// A file could not be read.
    #[error("could not read hook config {path}: {source}")]
    Read {
        /// File that failed to load.
        path: PathBuf,
        /// Underlying I/O error.
        source: std::io::Error,
    },
    /// A file could not be written.
    #[error("could not write hook config {path}: {source}")]
    Write {
        /// File that failed to update.
        path: PathBuf,
        /// Underlying I/O error.
        source: std::io::Error,
    },
    /// Existing JSON configuration is invalid.
    #[error("could not parse hook config {path}: {source}")]
    Json {
        /// Invalid configuration file.
        path: PathBuf,
        /// JSON parse failure.
        source: serde_json::Error,
    },
    /// Existing TOML configuration is invalid.
    #[error("could not parse hook config {path}: {source}")]
    Toml {
        /// Invalid configuration file.
        path: PathBuf,
        /// TOML parse failure.
        source: toml_edit::TomlError,
    },
    /// Existing configuration has an incompatible field shape.
    #[error("hook config {0} has an incompatible schema")]
    Schema(PathBuf),
    /// Reading hook JSON from stdin failed.
    #[error("could not read the provider hook payload: {0}")]
    PayloadRead(#[from] std::io::Error),
    /// The provider hook payload is invalid JSON.
    #[error("could not parse the provider hook payload: {0}")]
    PayloadJson(#[from] serde_json::Error),
    /// Encoding an owned provider plugin failed.
    #[error("could not encode a provider integration: {0}")]
    PluginEncoding(serde_json::Error),
    /// A provider configuration path contains a symlink cycle or excessive
    /// indirection.
    #[error("provider hook config symlink chain is too deep at {0}")]
    SymlinkDepth(PathBuf),
    /// A provider without a managed integration file was asked for status.
    #[error("provider {0} has no managed hook integration")]
    UnmanagedProvider(AgentTool),
}

/// Installation state of one provider integration file.
#[derive(Clone, Copy, Debug, Display, PartialEq, Eq)]
#[strum(serialize_all = "lowercase")]
pub enum HookState {
    /// No muster entry exists in the provider's config.
    Missing,
    /// A muster entry exists but references another muster binary.
    Stale,
    /// The muster entry references the given executable.
    Installed,
}

/// One provider integration's location and state.
#[derive(Debug, Getters, CopyGetters, TypedBuilder)]
pub struct HookStatus {
    /// The provider this integration belongs to.
    #[getset(get_copy = "pub")]
    provider: AgentTool,
    /// The config or plugin file the integration lives in.
    #[getset(get = "pub")]
    path: PathBuf,
    /// Whether the integration is present and current.
    #[getset(get_copy = "pub")]
    state: HookState,
}

/// The exact artifact setup writes for one provider, compared verbatim when
/// deciding Installed.
enum ExpectedHook {
    /// Command string in the grouped `SessionStart` JSON schema.
    GroupedCommand(String),
    /// Command string under Copilot's platform command key.
    CopilotCommand(String),
    /// Command string in a Kimi `[[hooks]]` table.
    KimiCommand(String),
    /// The complete plugin file contents.
    Plugin(String),
}

/// Installs opt-in provider integrations and receives their session identities.
pub struct ProviderHooks;

impl ProviderHooks {
    /// Installs idempotent user-level hooks/plugins for every supported provider.
    /// Returns the paths checked or updated.
    ///
    /// # Errors
    /// Returns a [`HookError`] without overwriting malformed existing configs.
    pub fn setup(executable: &Path) -> Result<Vec<PathBuf>, HookError> {
        let dirs = BaseDirs::new().ok_or(HookError::NoUserDirs)?;
        let xdg_config = Self::xdg_config_dir(dirs.home_dir());
        let codex_home = env::var_os(CODEX_HOME_ENV)
            .map(PathBuf::from)
            .filter(|path| path.is_absolute())
            .unwrap_or_else(|| dirs.home_dir().join(CODEX_CONFIG_DIR));
        Self::setup_in_with_codex(
            executable,
            dirs.home_dir(),
            dirs.config_dir(),
            &xdg_config,
            &codex_home,
        )
    }

    /// Captures a provider session ID from hook JSON. Hooks outside a
    /// Muster-owned agent process are deliberately ignored.
    ///
    /// # Errors
    /// Returns a [`HookError`] for malformed payloads and a config error when the
    /// session store cannot record the identity.
    pub fn capture(
        store: &dyn AgentSessionStore,
        provider: AgentTool,
        process_id: u32,
        parent_process_id: Option<u32>,
        mut input: impl Read,
    ) -> Result<bool, crate::error::MusterError> {
        let Some(internal) = std::env::var_os(MUSTER_AGENT_SESSION_ENV) else {
            return Ok(false);
        };
        let Some(internal) = internal.to_str() else {
            return Err(HookError::MissingSessionId.into());
        };
        let internal =
            AgentSessionId::try_new(internal).map_err(|_| HookError::MissingSessionId)?;
        let process_id =
            AgentProcessId::try_new(process_id).map_err(|_| HookError::MissingProviderProcessId)?;
        let parent_process_id = parent_process_id
            .map(AgentProcessId::try_new)
            .transpose()
            .map_err(|_| HookError::MissingProviderProcessId)?;
        let mut raw = String::new();
        input.read_to_string(&mut raw).map_err(HookError::from)?;
        let payload: Value = serde_json::from_str(&raw).map_err(HookError::from)?;
        let native = Self::native_id(&payload)?;
        store.capture_native_id(&internal, provider, process_id, parent_process_id, native)?;
        Ok(true)
    }

    /// Resolves OpenCode's XDG configuration root independently of the
    /// platform-native configuration directory.
    fn xdg_config_dir(home: &Path) -> PathBuf {
        env::var_os(XDG_CONFIG_HOME_ENV)
            .map(PathBuf::from)
            .filter(|path| path.is_absolute())
            .unwrap_or_else(|| home.join(XDG_CONFIG_HOME_DEFAULT))
    }

    /// The provider hook/plugin file locations paired with their provider, in installation order.
    fn provider_paths(
        home: &Path,
        config: &Path,
        xdg_config: &Path,
        codex_home: &Path,
    ) -> [(AgentTool, PathBuf); 7] {
        [
            (AgentTool::Claude, home.join(CLAUDE_SETTINGS)),
            (AgentTool::Codex, codex_home.join(CODEX_HOOKS_FILE)),
            (AgentTool::Gemini, home.join(GEMINI_SETTINGS)),
            (AgentTool::Copilot, home.join(COPILOT_HOOK)),
            (AgentTool::Kimi, home.join(KIMI_CONFIG)),
            (AgentTool::Amp, config.join(AMP_PLUGIN)),
            (AgentTool::Opencode, xdg_config.join(OPENCODE_PLUGIN)),
        ]
    }

    /// Reports each provider integration's state for `executable`, without
    /// modifying anything. Detection is textual: a file that mentions the
    /// executable's path is installed; one that mentions the capture
    /// subcommand without that path was installed by another muster binary.
    ///
    /// # Errors
    /// Returns a [`HookError`] when the user's directories cannot be resolved
    /// or the executable path is not valid UTF-8.
    pub fn status(executable: &Path) -> Result<Vec<HookStatus>, HookError> {
        let dirs = BaseDirs::new().ok_or(HookError::NoUserDirs)?;
        let xdg_config = Self::xdg_config_dir(dirs.home_dir());
        let codex_home = env::var_os(CODEX_HOME_ENV)
            .map(PathBuf::from)
            .filter(|path| path.is_absolute())
            .unwrap_or_else(|| dirs.home_dir().join(CODEX_CONFIG_DIR));
        Self::status_in(
            executable,
            dirs.home_dir(),
            dirs.config_dir(),
            &xdg_config,
            &codex_home,
        )
    }

    /// Directory-injected form of [`Self::status`], used directly in tests.
    ///
    /// # Errors
    /// Returns a [`HookError`] when the executable path is not valid UTF-8.
    fn status_in(
        executable: &Path,
        home: &Path,
        config: &Path,
        xdg_config: &Path,
        codex_home: &Path,
    ) -> Result<Vec<HookStatus>, HookError> {
        let executable = executable.to_str().ok_or(HookError::InvalidExecutable)?;
        let pairs = Self::provider_paths(home, config, xdg_config, codex_home);
        pairs
            .into_iter()
            .map(|(provider, path)| {
                let expected = Self::expected_hook(executable, provider)?;
                let state = Self::file_state(&path, &expected);
                Ok(HookStatus::builder()
                    .provider(provider)
                    .path(path)
                    .state(state)
                    .build())
            })
            .collect()
    }

    /// The exact artifact setup would write for `provider` and `executable`:
    /// the canonical command string for command-backed providers, or the full
    /// plugin file for plugin-backed ones. Installed means the provider's
    /// canonical schema slot equals this, so no textual coincidence in
    /// unrelated content can read as healthy.
    ///
    /// # Errors
    /// Returns a [`HookError`] when the command or plugin cannot be built.
    fn expected_hook(executable: &str, provider: AgentTool) -> Result<ExpectedHook, HookError> {
        #[cfg(windows)]
        let command = Self::powershell_hook_command(executable, provider);
        #[cfg(not(windows))]
        let command = Self::posix_hook_command(executable, provider)?;
        Ok(match provider {
            AgentTool::Claude | AgentTool::Codex | AgentTool::Gemini => {
                ExpectedHook::GroupedCommand(command)
            },
            AgentTool::Copilot => ExpectedHook::CopilotCommand(command),
            AgentTool::Kimi => ExpectedHook::KimiCommand(command),
            AgentTool::Amp => ExpectedHook::Plugin(Self::amp_plugin(executable)?),
            AgentTool::Opencode => ExpectedHook::Plugin(Self::opencode_plugin(executable)?),
            // External integrations own their configs; muster installs none.
            AgentTool::Custom => return Err(HookError::UnmanagedProvider(provider)),
        })
    }

    /// Textual state of one integration file, matched against every encoded
    /// form of the executable path.
    fn file_state(path: &Path, expected: &ExpectedHook) -> HookState {
        let Ok(content) = fs::read_to_string(path) else {
            // An unreadable config reads as absent; a later hooks setup surfaces the real error.
            return HookState::Missing;
        };
        let installed = match expected {
            ExpectedHook::GroupedCommand(command) => {
                Self::grouped_json_has_exact(&content, command)
            },
            ExpectedHook::CopilotCommand(command) => Self::copilot_has_exact(&content, command),
            ExpectedHook::KimiCommand(command) => Self::kimi_has_exact(&content, command),
            ExpectedHook::Plugin(plugin) => content.trim_end() == plugin.trim_end(),
        };
        if installed {
            HookState::Installed
        } else if Self::has_stale_marker(&Self::active_content(&content)) {
            // Some muster capture text survives on evaluated lines but does
            // not match what setup writes: another binary, provider, or shape.
            HookState::Stale
        } else {
            HookState::Missing
        }
    }

    /// The lines a provider actually evaluates: comments (TOML/shell `#`,
    /// JS `//`) are dropped; JSON has no comments so it passes through.
    /// Best effort: block comments are not tracked.
    fn active_content(content: &str) -> String {
        content
            .lines()
            .filter(|line| {
                let trimmed = line.trim_start();
                COMMENT_PREFIXES
                    .iter()
                    .all(|prefix| !trimmed.starts_with(prefix))
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// Whether evaluated content still carries a muster capture invocation:
    /// the `hook capture` subcommand pair as commands write it, or the JSON
    /// argument-array pair as plugins write it. A lone unrelated word like a
    /// `capture` permission never counts.
    fn has_stale_marker(active: &str) -> bool {
        STALE_MARKERS.iter().any(|marker| active.contains(marker))
    }

    /// Whether the grouped `SessionStart` schema holds exactly `command`.
    fn grouped_json_has_exact(content: &str, command: &str) -> bool {
        let Ok(root) = serde_json::from_str::<Value>(content) else {
            return false;
        };
        root.get("hooks")
            .and_then(|hooks| hooks.get(SESSION_START_EVENT))
            .and_then(Value::as_array)
            .is_some_and(|entries| {
                entries.iter().any(|entry| {
                    entry
                        .get("hooks")
                        .and_then(Value::as_array)
                        .is_some_and(|members| {
                            members.iter().any(|member| {
                                member.get("command").and_then(Value::as_str) == Some(command)
                            })
                        })
                })
            })
    }

    /// Whether Copilot's `sessionStart` schema holds exactly `command` under
    /// the platform's command key.
    fn copilot_has_exact(content: &str, command: &str) -> bool {
        #[cfg(windows)]
        let command_key = COPILOT_POWERSHELL_KEY;
        #[cfg(not(windows))]
        let command_key = COPILOT_BASH_KEY;
        let Ok(root) = serde_json::from_str::<Value>(content) else {
            return false;
        };
        root.get("hooks")
            .and_then(|hooks| hooks.get(COPILOT_SESSION_START_EVENT))
            .and_then(Value::as_array)
            .is_some_and(|members| {
                members
                    .iter()
                    .any(|member| member.get(command_key).and_then(Value::as_str) == Some(command))
            })
    }

    /// Whether a Kimi `[[hooks]]` table holds exactly `command` with the
    /// session event and matcher setup writes.
    fn kimi_has_exact(content: &str, command: &str) -> bool {
        let Ok(document) = content.parse::<DocumentMut>() else {
            return false;
        };
        let matches_hook = |event: Option<&str>, matcher: Option<&str>, cmd: Option<&str>| {
            event == Some(SESSION_START_EVENT)
                && matcher == Some(KIMI_SESSION_MATCHER)
                && cmd == Some(command)
        };
        let standard = document
            .get("hooks")
            .and_then(Item::as_array_of_tables)
            .is_some_and(|hooks| {
                hooks.iter().any(|hook| {
                    matches_hook(
                        hook.get("event").and_then(Item::as_str),
                        hook.get("matcher").and_then(Item::as_str),
                        hook.get("command").and_then(Item::as_str),
                    )
                })
            });
        // Inline `hooks = [{...}]` arrays are the same hooks spelled the
        // other valid way; verify them identically.
        let inline = document
            .get("hooks")
            .and_then(Item::as_array)
            .is_some_and(|hooks| {
                hooks.iter().any(|hook| {
                    hook.as_inline_table().is_some_and(|table| {
                        matches_hook(
                            table.get("event").and_then(toml_edit::Value::as_str),
                            table.get("matcher").and_then(toml_edit::Value::as_str),
                            table.get("command").and_then(toml_edit::Value::as_str),
                        )
                    })
                })
            });
        standard || inline
    }

    /// Installs every provider integration under explicit testable roots.
    ///
    /// # Errors
    /// Returns a [`HookError`] if any existing config is malformed or a write
    /// cannot complete.
    #[cfg(test)]
    fn setup_in(
        executable: &Path,
        home: &Path,
        config: &Path,
        xdg_config: &Path,
    ) -> Result<Vec<PathBuf>, HookError> {
        Self::setup_in_with_codex(
            executable,
            home,
            config,
            xdg_config,
            &home.join(CODEX_CONFIG_DIR),
        )
    }

    /// Installs integrations with an explicit Codex configuration directory.
    ///
    /// # Errors
    /// Returns a [`HookError`] if any existing config is malformed or a write
    /// cannot complete.
    fn setup_in_with_codex(
        executable: &Path,
        home: &Path,
        config: &Path,
        xdg_config: &Path,
        codex_home: &Path,
    ) -> Result<Vec<PathBuf>, HookError> {
        let executable = executable.to_str().ok_or(HookError::InvalidExecutable)?;
        #[cfg(windows)]
        let kimi_command = Self::powershell_hook_command(executable, AgentTool::Kimi);
        #[cfg(not(windows))]
        let kimi_command = Self::posix_hook_command(executable, AgentTool::Kimi)?;
        #[cfg(windows)]
        let copilot_command = Self::powershell_hook_command(executable, AgentTool::Copilot);
        #[cfg(not(windows))]
        let copilot_command = Self::posix_hook_command(executable, AgentTool::Copilot)?;
        let pairs = Self::provider_paths(home, config, xdg_config, codex_home);
        let paths: Vec<PathBuf> = pairs.iter().map(|(_, path)| path.clone()).collect();
        #[cfg(windows)]
        for (provider, path) in pairs[..3].iter().map(|(p, path)| (*p, path)) {
            let command = Self::powershell_hook_command(executable, provider);
            Self::install_grouped_json(path, provider, &command)?;
        }
        #[cfg(not(windows))]
        for (provider, path) in pairs[..3].iter().map(|(p, path)| (*p, path)) {
            let command = Self::posix_hook_command(executable, provider)?;
            Self::install_grouped_json(path, provider, &command)?;
        }
        Self::install_copilot(&paths[3], &copilot_command)?;
        Self::install_kimi(&paths[4], AgentTool::Kimi, &kimi_command)?;
        Self::write_text(&paths[5], &Self::amp_plugin(executable)?)?;
        Self::write_text(&paths[6], &Self::opencode_plugin(executable)?)?;
        Ok(paths)
    }

    /// Returns the CLI arguments for one provider's lifecycle callback.
    fn capture_arguments(provider: AgentTool) -> [String; 4] {
        [
            HOOK_SUBCOMMAND.to_string(),
            CAPTURE_SUBCOMMAND.to_string(),
            CAPTURE_PROVIDER_ARGUMENT.to_string(),
            provider.protocol_token().to_string(),
        ]
    }

    /// Builds a POSIX shell command for provider hook formats that accept one
    /// command string.
    ///
    /// # Errors
    /// Returns a [`HookError`] if the executable cannot be safely quoted.
    fn posix_hook_command(executable: &str, provider: AgentTool) -> Result<String, HookError> {
        let executable = shlex::try_quote(executable).map_err(|_| HookError::InvalidExecutable)?;
        Ok(format!(
            "{executable} {} {CAPTURE_PROCESS_ID_ARGUMENT} \"$PPID\" {CAPTURE_PARENT_PROCESS_ID_ARGUMENT} \"$(ps -o ppid= -p \"$PPID\" | tr -d '[:space:]')\"",
            Self::capture_arguments(provider).join(" "),
        ))
    }

    /// Builds a PowerShell invocation, including the call operator required for
    /// a quoted executable path.
    #[cfg(any(windows, test))]
    fn powershell_hook_command(executable: &str, provider: AgentTool) -> String {
        let executable = executable.replace('\'', "''");
        format!(
            "$provider = (Get-CimInstance -ClassName Win32_Process -Filter \"ProcessId=$PID\").ParentProcessId; $parent = (Get-CimInstance -ClassName Win32_Process -Filter \"ProcessId=$provider\").ParentProcessId; & '{executable}' {} {CAPTURE_PROCESS_ID_ARGUMENT} $provider {CAPTURE_PARENT_PROCESS_ID_ARGUMENT} $parent",
            Self::capture_arguments(provider).join(" "),
        )
    }

    /// Reconciles Muster's provider-specific entry in a grouped `SessionStart`
    /// hook array, replacing stale executable paths and removing duplicates.
    ///
    /// # Errors
    /// Returns a [`HookError`] for malformed JSON, incompatible shapes, or I/O.
    fn install_grouped_json(
        path: &Path,
        provider: AgentTool,
        command: &str,
    ) -> Result<(), HookError> {
        let mut root = Self::read_json(path)?;
        let object = root
            .as_object_mut()
            .ok_or_else(|| HookError::Schema(path.to_path_buf()))?;
        let hooks = Self::object_entry(object, "hooks", path)?;
        let entries = Self::array_entry(hooks, SESSION_START_EVENT, path)?;
        let mut installed = false;
        let mut changed = false;
        for entry in entries.iter_mut() {
            let hooks = entry
                .as_object_mut()
                .and_then(|entry| entry.get_mut("hooks"))
                .and_then(Value::as_array_mut)
                .ok_or_else(|| HookError::Schema(path.to_path_buf()))?;
            hooks.retain_mut(|hook| {
                let Some(existing) = hook.get("command").and_then(Value::as_str) else {
                    return true;
                };
                if !Self::is_provider_capture_command(existing, provider) {
                    return true;
                }
                if installed {
                    changed = true;
                    return false;
                }
                installed = true;
                if existing != command {
                    if let Some(object) = hook.as_object_mut() {
                        object.insert("command".to_string(), Value::String(command.to_string()));
                    }
                    changed = true;
                }
                true
            });
        }
        let entry_count = entries.len();
        entries.retain(|entry| !Self::is_empty_owned_hook_group(entry));
        changed |= entries.len() != entry_count;
        if !installed {
            entries.push(json!({
                "hooks": [{ "type": "command", "command": command }]
            }));
            changed = true;
        }
        if changed {
            Self::write_json(path, &root)?;
        }
        Ok(())
    }

    /// Whether `command` invokes Muster's capture receiver for `provider`,
    /// regardless of the executable path installed by an earlier version.
    fn is_provider_capture_command(command: &str, provider: AgentTool) -> bool {
        shlex::split(command).is_some_and(|arguments| {
            arguments
                .as_slice()
                .windows(Self::capture_arguments(provider).len())
                .any(|arguments| arguments == Self::capture_arguments(provider))
        })
    }

    /// Whether an entry became an empty Muster-owned group after duplicate
    /// capture commands were removed.
    fn is_empty_owned_hook_group(entry: &Value) -> bool {
        entry.as_object().is_some_and(|entry| {
            entry.len() == 1
                && entry
                    .get("hooks")
                    .and_then(Value::as_array)
                    .is_some_and(Vec::is_empty)
        })
    }

    /// Writes Copilot's dedicated user hook file.
    ///
    /// # Errors
    /// Returns a [`HookError`] if the owned hook file cannot be written.
    fn install_copilot(path: &Path, command: &str) -> Result<(), HookError> {
        #[cfg(windows)]
        let command_key = COPILOT_POWERSHELL_KEY;
        #[cfg(not(windows))]
        let command_key = COPILOT_BASH_KEY;
        let hook = json!({
            "version": 1,
            "hooks": {
                COPILOT_SESSION_START_EVENT: [{
                    "type": "command",
                    command_key: command
                }]
            }
        });
        Self::write_json(path, &hook)
    }

    /// Reconciles Kimi's provider-specific `SessionStart` hook while preserving
    /// unrelated TOML and hook entries.
    ///
    /// # Errors
    /// Returns a [`HookError`] for malformed TOML, incompatible shapes, or I/O.
    fn install_kimi(path: &Path, provider: AgentTool, command: &str) -> Result<(), HookError> {
        let raw = Self::read_text(path)?;
        let mut document = if raw.trim().is_empty() {
            DocumentMut::new()
        } else {
            raw.parse::<DocumentMut>()
                .map_err(|source| HookError::Toml {
                    path: path.to_path_buf(),
                    source,
                })?
        };
        if document.get("hooks").is_none() {
            document["hooks"] = Item::ArrayOfTables(ArrayOfTables::new());
        }
        // An inline `hooks = [{...}]` array is valid, semantically identical
        // TOML; normalize it so both spellings install and verify.
        if let Some(inline) = document["hooks"].as_array().cloned() {
            let mut tables = ArrayOfTables::new();
            for value in inline.iter() {
                let table = value
                    .as_inline_table()
                    .cloned()
                    .map(toml_edit::InlineTable::into_table)
                    .ok_or_else(|| HookError::Schema(path.to_path_buf()))?;
                tables.push(table);
            }
            document["hooks"] = Item::ArrayOfTables(tables);
        }
        let hooks = document["hooks"]
            .as_array_of_tables_mut()
            .ok_or_else(|| HookError::Schema(path.to_path_buf()))?;
        let mut installed = false;
        let mut changed = false;
        let mut duplicates = Vec::new();
        for (index, hook) in hooks.iter_mut().enumerate() {
            let Some(existing) = hook.get("command").and_then(Item::as_str) else {
                continue;
            };
            if hook.get("event").and_then(Item::as_str) != Some(SESSION_START_EVENT)
                || !Self::is_provider_capture_command(existing, provider)
            {
                continue;
            }
            if installed {
                duplicates.push(index);
                continue;
            }
            installed = true;
            if existing != command {
                hook["command"] = toml_edit::value(command);
                changed = true;
            }
            if hook.get("matcher").and_then(Item::as_str) != Some(KIMI_SESSION_MATCHER) {
                hook["matcher"] = toml_edit::value(KIMI_SESSION_MATCHER);
                changed = true;
            }
        }
        for index in duplicates.into_iter().rev() {
            hooks.remove(index);
            changed = true;
        }
        if !installed {
            let mut hook = Table::new();
            hook["event"] = toml_edit::value(SESSION_START_EVENT);
            hook["matcher"] = toml_edit::value(KIMI_SESSION_MATCHER);
            hook["command"] = toml_edit::value(command);
            hooks.push(hook);
            changed = true;
        }
        if changed {
            Self::write_text(path, &document.to_string())?;
        }
        Ok(())
    }

    /// Returns an Amp plugin that reports `event.thread.id` on session start.
    ///
    /// # Errors
    /// Returns a [`HookError`] if the executable cannot be JSON encoded.
    fn amp_plugin(executable: &str) -> Result<String, HookError> {
        let executable = serde_json::to_string(executable).map_err(HookError::PluginEncoding)?;
        let owner =
            serde_json::to_string(MUSTER_AGENT_SESSION_ENV).map_err(HookError::PluginEncoding)?;
        let arguments = serde_json::to_string(&Self::capture_arguments(AgentTool::Amp))
            .map_err(HookError::PluginEncoding)?;
        Ok(format!(
            r#"import {{ spawn }} from "node:child_process"
import type {{ PluginAPI }} from "@ampcode/plugin"

const executable = {executable}
const active = Boolean(process.env[{owner}])

const capture = (sessionId: string) => {{
  if (!active) return
  const child = spawn(executable, [...{arguments}, "{CAPTURE_PROCESS_ID_ARGUMENT}", process.pid.toString(), "{CAPTURE_PARENT_PROCESS_ID_ARGUMENT}", process.ppid.toString()], {{ stdio: ["pipe", "ignore", "ignore"] }})
  child.on("error", () => {{}})
  child.stdin.on("error", () => {{}})
  child.stdin.end(JSON.stringify({{ version: {AGENT_PROTOCOL_VERSION}, event: "session_started", session_id: sessionId }}))
}}

export default function musterSession(amp: PluginAPI) {{
  amp.on("session.start", (event) => capture(event.thread.id))
}}
"#
        ))
    }

    /// Returns an OpenCode plugin that reports IDs from session lifecycle events.
    ///
    /// # Errors
    /// Returns a [`HookError`] if the executable cannot be JSON encoded.
    fn opencode_plugin(executable: &str) -> Result<String, HookError> {
        let executable = serde_json::to_string(executable).map_err(HookError::PluginEncoding)?;
        let owner =
            serde_json::to_string(MUSTER_AGENT_SESSION_ENV).map_err(HookError::PluginEncoding)?;
        let arguments = serde_json::to_string(&Self::capture_arguments(AgentTool::Opencode))
            .map_err(HookError::PluginEncoding)?;
        Ok(format!(
            r#"import {{ spawn }} from "node:child_process"

const executable = {executable}
const active = Boolean(process.env[{owner}])
const sessionParents = new Map()
let activeSessionId
let capturedSessionId
let pendingSessionId
let captureInFlight = false

const flush = () => {{
  if (!active || captureInFlight || !pendingSessionId || pendingSessionId === capturedSessionId) return
  const sessionId = pendingSessionId
  pendingSessionId = undefined
  captureInFlight = true
  const child = spawn(executable, [...{arguments}, "{CAPTURE_PROCESS_ID_ARGUMENT}", process.pid.toString(), "{CAPTURE_PARENT_PROCESS_ID_ARGUMENT}", process.ppid.toString()], {{ stdio: ["pipe", "ignore", "ignore"] }})
  let settled = false
  const complete = (succeeded) => {{
    if (settled) return
    settled = true
    if (succeeded) capturedSessionId = sessionId
    captureInFlight = false
    flush()
  }}
  child.on("error", () => complete(false))
  child.on("exit", (code) => complete(code === 0))
  child.stdin.on("error", () => complete(false))
  child.stdin.end(JSON.stringify({{ version: {AGENT_PROTOCOL_VERSION}, event: "session_started", session_id: sessionId }}))
}}

const capture = (sessionId) => {{
  if (!active || !sessionId || sessionId === capturedSessionId || sessionId === pendingSessionId) return
  pendingSessionId = sessionId
  flush()
}}

export const MusterSession = async ({{ client }}) => {{
  const known = await client.session.list().catch(() => undefined)
  for (const info of known?.data ?? []) sessionParents.set(info.id, info.parentID)

  const select = (sessionId) => {{
    if (!sessionParents.has(sessionId) || sessionParents.get(sessionId)) return
    activeSessionId = sessionId
    capture(sessionId)
  }}

  return {{
    event: async ({{ event }}) => {{
      if (event.type === "session.created" || event.type === "session.updated") {{
        const info = event.properties?.info ?? event.properties?.session ?? event.properties
        const sessionId = info?.id ?? info?.sessionID
        if (sessionId) sessionParents.set(sessionId, info?.parentID)
        if (sessionId === activeSessionId && !info?.parentID) capture(sessionId)
        return
      }}
      if (event.type === "session.deleted") {{
        const info = event.properties?.info ?? event.properties?.session ?? event.properties
        const sessionId = info?.id ?? info?.sessionID
        if (sessionId) sessionParents.delete(sessionId)
        if (sessionId === activeSessionId) activeSessionId = undefined
        return
      }}
      if (event.type === "tui.session.select") select(event.properties?.sessionID)
    }},
    "chat.message": async (input) => select(input.sessionID),
  }}
}}
"#
        ))
    }

    /// Extracts a provider session ID from the canonical protocol or a native
    /// compatibility payload.
    ///
    /// # Errors
    /// Returns a [`HookError`] for unsupported versions or absent identities.
    fn native_id(payload: &Value) -> Result<NativeSessionId, HookError> {
        if let Some(version) = payload.get("version") {
            let version = version
                .as_u64()
                .ok_or(HookError::UnsupportedProtocolVersion(u64::MAX))?;
            if version != u64::from(AGENT_PROTOCOL_VERSION) {
                return Err(HookError::UnsupportedProtocolVersion(version));
            }
            let event = payload
                .get("event")
                .and_then(Value::as_str)
                .ok_or(HookError::MissingProtocolEvent)?;
            if event != PROTOCOL_SESSION_STARTED {
                return Err(HookError::UnsupportedProtocolEvent(event.to_string()));
            }
        }
        let native = payload
            .get("session_id")
            .or_else(|| payload.get("sessionId"))
            .and_then(Value::as_str)
            .ok_or(HookError::MissingSessionId)?;
        NativeSessionId::try_new(native).map_err(|_| HookError::MissingSessionId)
    }

    /// Reads JSON or returns an empty object when the file does not exist.
    ///
    /// # Errors
    /// Returns a [`HookError`] for I/O or parse failures.
    fn read_json(path: &Path) -> Result<Value, HookError> {
        let raw = Self::read_text(path)?;
        if raw.trim().is_empty() {
            return Ok(Value::Object(Map::new()));
        }
        serde_json::from_str(&raw).map_err(|source| HookError::Json {
            path: path.to_path_buf(),
            source,
        })
    }

    /// Reads UTF-8 text or returns empty text when the file is absent.
    ///
    /// # Errors
    /// Returns a [`HookError`] when an existing file cannot be read.
    fn read_text(path: &Path) -> Result<String, HookError> {
        match fs::read_to_string(path) {
            Ok(raw) => Ok(raw),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(String::new()),
            Err(source) => Err(HookError::Read {
                path: path.to_path_buf(),
                source,
            }),
        }
    }

    /// Returns an object field, creating it only when absent.
    ///
    /// # Errors
    /// Returns a [`HookError`] when an existing field is not an object.
    fn object_entry<'a>(
        parent: &'a mut Map<String, Value>,
        key: &str,
        path: &Path,
    ) -> Result<&'a mut Map<String, Value>, HookError> {
        parent
            .entry(key)
            .or_insert_with(|| Value::Object(Map::new()))
            .as_object_mut()
            .ok_or_else(|| HookError::Schema(path.to_path_buf()))
    }

    /// Returns an array field, creating it only when absent.
    ///
    /// # Errors
    /// Returns a [`HookError`] when an existing field is not an array.
    fn array_entry<'a>(
        parent: &'a mut Map<String, Value>,
        key: &str,
        path: &Path,
    ) -> Result<&'a mut Vec<Value>, HookError> {
        parent
            .entry(key)
            .or_insert_with(|| Value::Array(Vec::new()))
            .as_array_mut()
            .ok_or_else(|| HookError::Schema(path.to_path_buf()))
    }

    /// Serializes formatted JSON and writes it atomically.
    ///
    /// # Errors
    /// Returns a [`HookError`] if serialization or writing fails.
    fn write_json(path: &Path, value: &Value) -> Result<(), HookError> {
        let mut raw = serde_json::to_string_pretty(value).map_err(|source| HookError::Json {
            path: path.to_path_buf(),
            source,
        })?;
        raw.push('\n');
        Self::write_text(path, &raw)
    }

    /// Writes an owned integration file atomically while preserving an existing
    /// target's permissions and any symlink used to reach it.
    ///
    /// # Errors
    /// Returns a [`HookError`] if path resolution, writing, or replacement fails.
    fn write_text(path: &Path, raw: &str) -> Result<(), HookError> {
        let destination = Self::write_destination(path)?;
        if let Some(parent) = destination.parent() {
            fs::create_dir_all(parent).map_err(|source| HookError::Write {
                path: parent.to_path_buf(),
                source,
            })?;
        }
        if fs::read_to_string(&destination).is_ok_and(|current| current == raw) {
            return Ok(());
        }
        let permissions = match fs::metadata(&destination) {
            Ok(metadata) => Some(metadata.permissions()),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
            Err(source) => {
                return Err(HookError::Read {
                    path: destination,
                    source,
                });
            },
        };
        let mut file = AtomicWriteFile::open(&destination).map_err(|source| HookError::Write {
            path: destination.clone(),
            source,
        })?;
        file.write_all(raw.as_bytes())
            .map_err(|source| HookError::Write {
                path: destination.clone(),
                source,
            })?;
        if let Some(permissions) = permissions {
            file.set_permissions(permissions)
                .map_err(|source| HookError::Write {
                    path: destination.clone(),
                    source,
                })?;
        }
        file.commit().map_err(|source| HookError::Write {
            path: destination,
            source,
        })
    }

    /// Resolves existing symlinks to their target without requiring the final
    /// target to exist, so atomic replacement leaves every alias intact.
    ///
    /// # Errors
    /// Returns a [`HookError`] when metadata or symlink resolution fails.
    fn write_destination(path: &Path) -> Result<PathBuf, HookError> {
        let mut destination = path.to_path_buf();
        for depth in 0..=MAX_PROVIDER_CONFIG_SYMLINKS {
            match fs::symlink_metadata(&destination) {
                Ok(metadata) if metadata.file_type().is_symlink() => {
                    if depth == MAX_PROVIDER_CONFIG_SYMLINKS {
                        return Err(HookError::SymlinkDepth(destination));
                    }
                    let target = fs::read_link(&destination).map_err(|source| HookError::Read {
                        path: destination.clone(),
                        source,
                    })?;
                    destination = if target.is_absolute() {
                        target
                    } else {
                        match destination.parent() {
                            Some(parent) => parent.join(target),
                            None => target,
                        }
                    };
                },
                Ok(_) => return Ok(destination),
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                    return Ok(destination);
                },
                Err(source) => {
                    return Err(HookError::Read {
                        path: destination,
                        source,
                    });
                },
            }
        }
        Err(HookError::SymlinkDepth(destination))
    }
}

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

    /// Setup is idempotent and preserves unrelated JSON/TOML settings.
    #[test]
    fn setup_preserves_configs_without_duplicating_hooks() {
        let root = std::env::temp_dir().join(format!("muster-hooks-{}", uuid::Uuid::new_v4()));
        let home = root.join("home");
        let config = root.join("config");
        let xdg_config = root.join("xdg");
        let claude = home.join(CLAUDE_SETTINGS);
        let kimi = home.join(KIMI_CONFIG);
        ProviderHooks::write_text(&claude, "{\"theme\":\"dark\"}").unwrap();
        ProviderHooks::write_text(&kimi, "model = \"kimi\"\n").unwrap();

        let paths =
            ProviderHooks::setup_in(Path::new("/opt/muster"), &home, &config, &xdg_config).unwrap();
        ProviderHooks::setup_in(Path::new("/opt/muster"), &home, &config, &xdg_config).unwrap();

        let claude: Value = serde_json::from_str(&fs::read_to_string(claude).unwrap()).unwrap();
        assert_eq!(claude["theme"], "dark");
        assert_eq!(
            claude["hooks"][SESSION_START_EVENT]
                .as_array()
                .unwrap()
                .len(),
            1
        );
        let kimi = fs::read_to_string(kimi).unwrap();
        assert!(kimi.contains("model = \"kimi\""));
        assert_eq!(kimi.matches("event = \"SessionStart\"").count(), 1);
        assert_eq!(paths[6], xdg_config.join(OPENCODE_PLUGIN));
        assert!(paths[6].is_file());
        assert!(!config.join(OPENCODE_PLUGIN).exists());
        fs::remove_dir_all(root).unwrap();
    }

    /// Setup replaces owned grouped and Kimi hooks when the executable moves,
    /// removing duplicate copies without disturbing unrelated commands.
    #[test]
    fn setup_reconciles_outdated_hook_commands() {
        const OLD_EXECUTABLE: &str = "/old/muster";
        const NEW_EXECUTABLE: &str = "/new/muster";
        const UNRELATED_COMMAND: &str = "notify-session";

        let root_path =
            std::env::temp_dir().join(format!("muster-hook-upgrade-{}", uuid::Uuid::new_v4()));
        let home = root_path.join("home");
        let config = root_path.join("config");
        let xdg_config = root_path.join("xdg");
        let claude = home.join(CLAUDE_SETTINGS);
        let kimi = home.join(KIMI_CONFIG);
        let outdated =
            ProviderHooks::posix_hook_command(OLD_EXECUTABLE, AgentTool::Claude).unwrap();
        let current = ProviderHooks::posix_hook_command(NEW_EXECUTABLE, AgentTool::Claude).unwrap();
        let outdated_kimi =
            ProviderHooks::posix_hook_command(OLD_EXECUTABLE, AgentTool::Kimi).unwrap();
        let current_kimi =
            ProviderHooks::posix_hook_command(NEW_EXECUTABLE, AgentTool::Kimi).unwrap();
        ProviderHooks::write_json(
            &claude,
            &json!({
                "hooks": {
                    SESSION_START_EVENT: [
                        {
                            "hooks": [
                                { "type": "command", "command": outdated },
                                { "type": "command", "command": UNRELATED_COMMAND }
                            ]
                        },
                        {
                            "hooks": [
                                { "type": "command", "command": current }
                            ]
                        }
                    ]
                }
            }),
        )
        .unwrap();
        let mut kimi_config = DocumentMut::new();
        kimi_config["hooks"] = Item::ArrayOfTables(ArrayOfTables::new());
        for matcher in ["startup", KIMI_SESSION_MATCHER] {
            let mut hook = Table::new();
            hook["event"] = toml_edit::value(SESSION_START_EVENT);
            hook["matcher"] = toml_edit::value(matcher);
            hook["command"] = toml_edit::value(&outdated_kimi);
            kimi_config["hooks"]
                .as_array_of_tables_mut()
                .unwrap()
                .push(hook);
        }
        ProviderHooks::write_text(&kimi, &kimi_config.to_string()).unwrap();

        ProviderHooks::setup_in(Path::new(NEW_EXECUTABLE), &home, &config, &xdg_config).unwrap();

        let config: Value = serde_json::from_str(&fs::read_to_string(&claude).unwrap()).unwrap();
        let commands = config["hooks"][SESSION_START_EVENT]
            .as_array()
            .unwrap()
            .iter()
            .filter_map(|entry| entry.get("hooks").and_then(Value::as_array))
            .flatten()
            .filter_map(|hook| hook.get("command").and_then(Value::as_str))
            .collect::<Vec<_>>();
        assert_eq!(
            commands
                .iter()
                .filter(|command| **command == current.as_str())
                .count(),
            1
        );
        assert_eq!(
            commands
                .iter()
                .filter(|command| **command == UNRELATED_COMMAND)
                .count(),
            1
        );
        assert!(!commands.contains(&outdated.as_str()));
        let kimi = fs::read_to_string(kimi).unwrap();
        assert!(!kimi.contains(&outdated_kimi));
        assert_eq!(kimi.matches(&current_kimi).count(), 1);
        assert_eq!(kimi.matches(KIMI_SESSION_MATCHER).count(), 1);
        fs::remove_dir_all(root_path).unwrap();
    }

    /// Grouped provider hooks fail closed when an existing group has no hook array.
    #[test]
    fn setup_rejects_a_malformed_nested_hook_group() {
        let root =
            std::env::temp_dir().join(format!("muster-hook-schema-{}", uuid::Uuid::new_v4()));
        let path = root.join(CLAUDE_SETTINGS);
        ProviderHooks::write_json(
            &path,
            &json!({
                "hooks": {
                    SESSION_START_EVENT: [{ "hooks": "not-an-array" }]
                }
            }),
        )
        .unwrap();

        let result = ProviderHooks::install_grouped_json(&path, AgentTool::Claude, "muster hook");

        assert!(matches!(result, Err(HookError::Schema(error_path)) if error_path == path));
        fs::remove_dir_all(root).unwrap();
    }

    /// An explicit Codex home receives its hook rather than the default path.
    #[test]
    fn setup_uses_the_configured_codex_home() {
        let root = std::env::temp_dir().join(format!("muster-codex-home-{}", uuid::Uuid::new_v4()));
        let home = root.join("home");
        let config = root.join("config");
        let xdg_config = root.join("xdg");
        let codex_home = root.join("custom-codex");

        let paths = ProviderHooks::setup_in_with_codex(
            Path::new("/tmp/muster"),
            &home,
            &config,
            &xdg_config,
            &codex_home,
        )
        .unwrap();

        assert_eq!(paths[1], codex_home.join("hooks.json"));
        assert!(paths[1].is_file());
        fs::remove_dir_all(root).unwrap();
    }

    /// Canonical events and native camel-case hook payloads share one decoder.
    #[test]
    fn decodes_protocol_and_compatibility_payloads() {
        let protocol = json!({
            "version": AGENT_PROTOCOL_VERSION,
            "event": "session_started",
            "session_id": "native-one"
        });
        let native = json!({ "sessionId": "native-two" });

        assert_eq!(
            ProviderHooks::native_id(&protocol).unwrap().as_ref(),
            "native-one"
        );
        assert_eq!(
            ProviderHooks::native_id(&native).unwrap().as_ref(),
            "native-two"
        );
    }

    /// Versioned payloads reject unknown event names instead of interpreting
    /// unrelated provider data as a session lifecycle event.
    #[test]
    fn rejects_unknown_versioned_protocol_events() {
        let event = json!({
            "version": AGENT_PROTOCOL_VERSION,
            "event": "session_closed",
            "session_id": "native-one"
        });

        assert!(matches!(
            ProviderHooks::native_id(&event),
            Err(HookError::UnsupportedProtocolEvent(name)) if name == "session_closed"
        ));
    }

    /// Quoted Windows paths use PowerShell's call operator and escape embedded
    /// single quotes.
    #[test]
    fn powershell_commands_invoke_quoted_executables() {
        let command = ProviderHooks::powershell_hook_command(
            r"C:\Program Files\Muster's\muster.exe",
            AgentTool::Copilot,
        );

        assert_eq!(
            command,
            r#"$provider = (Get-CimInstance -ClassName Win32_Process -Filter "ProcessId=$PID").ParentProcessId; $parent = (Get-CimInstance -ClassName Win32_Process -Filter "ProcessId=$provider").ParentProcessId; & 'C:\Program Files\Muster''s\muster.exe' hook capture --provider copilot --process-id $provider --parent-process-id $parent"#
        );
    }

    /// Owned Node integrations absorb asynchronous spawn and pipe errors when
    /// the configured Muster executable is no longer available.
    #[test]
    fn generated_plugins_handle_capture_process_errors() {
        let amp = ProviderHooks::amp_plugin("/missing/muster").unwrap();
        let opencode = ProviderHooks::opencode_plugin("/missing/muster").unwrap();

        assert!(amp.contains("if (!active) return"));
        assert!(opencode.contains("let pendingSessionId"));
        assert!(opencode.contains("let captureInFlight = false"));
        assert!(opencode.contains("const sessionParents = new Map()"));
        assert!(opencode.contains("activeSessionId = sessionId"));
        assert!(opencode.contains("sessionId === activeSessionId && !info?.parentID"));
        assert!(opencode.contains(r#""chat.message": async (input) => select(input.sessionID)"#));
        assert!(opencode.contains("sessionParents.get(sessionId)"));
        assert!(!opencode.contains("capture(info?.id"));
        assert!(opencode.contains("pendingSessionId = sessionId"));
        assert!(opencode.contains(r#"child.on("error", () => complete(false))"#));
        assert!(opencode.contains(r#"child.stdin.on("error", () => complete(false))"#));
        assert!(amp.contains(CAPTURE_PROVIDER_ARGUMENT));
        assert!(amp.contains("amp"));
        assert!(opencode.contains(CAPTURE_PROVIDER_ARGUMENT));
        assert!(opencode.contains(AgentTool::Opencode.protocol_token()));
        for plugin in [&amp, &opencode] {
            assert!(plugin.contains(MUSTER_AGENT_SESSION_ENV));
        }
        assert!(amp.contains(r#"child.on("error", () => {})"#));
        assert!(amp.contains(r#"child.stdin.on("error", () => {})"#));
    }

    /// A path that is a strict prefix of the installed executable must not
    /// match as Installed. Setup with `/opt/muster-old/muster`; checking
    /// `/opt/muster-old/mus` (a prefix) must report every provider Stale,
    /// while the exact installed path reports Installed.
    #[test]
    fn status_does_not_match_path_prefixes() {
        let root = std::env::temp_dir().join(format!("muster-prefix-{}", uuid::Uuid::new_v4()));
        let home = root.join("home");
        let config = root.join("config");
        let xdg = root.join("xdg");
        let codex = home.join(CODEX_CONFIG_DIR);
        let installed_exe = Path::new("/opt/muster-old/muster");
        let prefix_exe = Path::new("/opt/muster-old/mus");

        ProviderHooks::setup_in_with_codex(installed_exe, &home, &config, &xdg, &codex).unwrap();

        // The strict prefix must not read as Installed.
        let prefix_statuses =
            ProviderHooks::status_in(prefix_exe, &home, &config, &xdg, &codex).unwrap();
        for status in &prefix_statuses {
            assert_ne!(
                status.state(),
                HookState::Installed,
                "prefix path matched as Installed for provider {}",
                status.provider()
            );
        }

        // The exact installed path must still report Installed.
        let exact_statuses =
            ProviderHooks::status_in(installed_exe, &home, &config, &xdg, &codex).unwrap();
        for status in &exact_statuses {
            assert_eq!(
                status.state(),
                HookState::Installed,
                "exact path not Installed for provider {}",
                status.provider()
            );
        }

        fs::remove_dir_all(root).unwrap();
    }

    /// Unrelated text containing the word capture is not a muster hook.
    #[test]
    fn status_ignores_unrelated_capture_text() {
        let root = std::env::temp_dir().join(format!("muster-unrel-{}", uuid::Uuid::new_v4()));
        let home = root.join("home");
        fs::create_dir_all(home.join(".claude")).unwrap();
        fs::write(
            home.join(CLAUDE_SETTINGS),
            "{\"permissions\":{\"allow\":[\"Bash(asciinema capture:*)\"]}}",
        )
        .unwrap();

        let statuses = ProviderHooks::status_in(
            Path::new("/opt/muster/muster"),
            &home,
            &root.join("config"),
            &root.join("xdg"),
            &home.join(CODEX_CONFIG_DIR),
        )
        .unwrap();

        let claude_status = statuses
            .iter()
            .find(|status| status.provider() == AgentTool::Claude)
            .expect("claude status present");
        assert_eq!(
            claude_status.state(),
            HookState::Missing,
            "an unrelated capture permission is not a stale muster hook"
        );
        fs::remove_dir_all(root).unwrap();
    }

    /// A Kimi config using the inline hooks spelling installs and verifies.
    #[test]
    fn kimi_inline_hook_arrays_install_and_verify() {
        let root = std::env::temp_dir().join(format!("muster-inline-{}", uuid::Uuid::new_v4()));
        let home = root.join("home");
        let config = root.join("config");
        let xdg = root.join("xdg");
        let codex = home.join(CODEX_CONFIG_DIR);
        fs::create_dir_all(home.join(".kimi-code")).unwrap();
        fs::write(
            home.join(KIMI_CONFIG),
            "hooks = [{ event = \"Other\", command = \"true\" }]\n",
        )
        .unwrap();
        let exe = Path::new("/opt/muster/muster");

        ProviderHooks::setup_in_with_codex(exe, &home, &config, &xdg, &codex).unwrap();
        let statuses = ProviderHooks::status_in(exe, &home, &config, &xdg, &codex).unwrap();

        let kimi_status = statuses
            .iter()
            .find(|status| status.provider() == AgentTool::Kimi)
            .expect("kimi status present");
        assert_eq!(kimi_status.state(), HookState::Installed);
        let rewritten = fs::read_to_string(home.join(KIMI_CONFIG)).unwrap();
        assert!(
            rewritten.contains("event = \"Other\""),
            "the unrelated inline hook survives normalization"
        );
        fs::remove_dir_all(root).unwrap();
    }

    /// A modified plugin file is stale: installed plugins must equal what
    /// setup writes, byte for byte.
    #[test]
    fn status_rejects_a_tampered_plugin() {
        let root = std::env::temp_dir().join(format!("muster-tamper-{}", uuid::Uuid::new_v4()));
        let home = root.join("home");
        let config = root.join("config");
        let xdg = root.join("xdg");
        let codex = home.join(CODEX_CONFIG_DIR);
        fs::create_dir_all(&home).unwrap();
        let exe = Path::new("/opt/muster/muster");
        ProviderHooks::setup_in_with_codex(exe, &home, &config, &xdg, &codex).unwrap();
        let plugin = config.join(AMP_PLUGIN);
        let mut tampered = fs::read_to_string(&plugin).unwrap();
        tampered.push_str("\nconsole.log(\"extra\")\n");
        fs::write(&plugin, tampered).unwrap();

        let statuses = ProviderHooks::status_in(exe, &home, &config, &xdg, &codex).unwrap();

        let amp_status = statuses
            .iter()
            .find(|status| status.provider() == AgentTool::Amp)
            .expect("amp status present");
        assert_eq!(amp_status.state(), HookState::Stale);
        fs::remove_dir_all(root).unwrap();
    }

    /// A provider token that merely begins with the expected value is not a
    /// working callback.
    #[test]
    fn status_rejects_a_provider_token_prefix() {
        let root = std::env::temp_dir().join(format!("muster-tokpre-{}", uuid::Uuid::new_v4()));
        let home = root.join("home");
        let config = root.join("config");
        let xdg = root.join("xdg");
        let codex = home.join(CODEX_CONFIG_DIR);
        fs::create_dir_all(&home).unwrap();
        let exe = Path::new("/opt/muster/muster");
        ProviderHooks::setup_in_with_codex(exe, &home, &config, &xdg, &codex).unwrap();
        // Corrupt Claude's callback into tokens clap would reject; every
        // ordinary token character must fail, not just the dash.
        let claude = home.join(CLAUDE_SETTINGS);
        let installed = fs::read_to_string(&claude).unwrap();
        for suffix in ["-old", ".old", "+x", ":x"] {
            let broken = installed.replace(
                &format!(
                    "{CAPTURE_PROVIDER_ARGUMENT} {}",
                    AgentTool::Claude.protocol_token()
                ),
                &format!(
                    "{CAPTURE_PROVIDER_ARGUMENT} {}{suffix}",
                    AgentTool::Claude.protocol_token()
                ),
            );
            fs::write(&claude, broken).unwrap();
            let statuses = ProviderHooks::status_in(exe, &home, &config, &xdg, &codex).unwrap();
            let claude_status = statuses
                .iter()
                .find(|status| status.provider() == AgentTool::Claude)
                .expect("claude status present");
            assert_eq!(
                claude_status.state(),
                HookState::Stale,
                "'{suffix}' must break the callback"
            );
        }
        fs::write(&claude, installed).unwrap();
        fs::remove_dir_all(root).unwrap();
    }

    /// Suffix matches after valid filename punctuation (colons, spaces) are
    /// rejected: boundaries come from writer delimiters, not path guessing.
    #[test]
    fn status_rejects_suffixes_behind_filename_punctuation() {
        for prefix in ["/prefix:", "/pre fix"] {
            let root = std::env::temp_dir().join(format!("muster-punct-{}", uuid::Uuid::new_v4()));
            let home = root.join("home");
            let config = root.join("config");
            let xdg = root.join("xdg");
            let codex = home.join(CODEX_CONFIG_DIR);
            fs::create_dir_all(&home).unwrap();
            let other = format!("{prefix}/bin/muster");
            ProviderHooks::setup_in_with_codex(Path::new(&other), &home, &config, &xdg, &codex)
                .unwrap();

            let statuses =
                ProviderHooks::status_in(Path::new("/bin/muster"), &home, &config, &xdg, &codex)
                    .unwrap();

            assert!(
                statuses
                    .iter()
                    .all(|status| status.state() == HookState::Stale),
                "a suffix behind '{prefix}' must not read installed"
            );
            fs::remove_dir_all(root).unwrap();
        }
    }

    /// A marker never matches inside a longer path to another binary.
    #[test]
    fn status_rejects_a_path_suffix_of_another_executable() {
        let root = std::env::temp_dir().join(format!("muster-suffix-{}", uuid::Uuid::new_v4()));
        let home = root.join("home");
        let config = root.join("config");
        let xdg = root.join("xdg");
        let codex = home.join(CODEX_CONFIG_DIR);
        fs::create_dir_all(&home).unwrap();
        // Installed for /usr/bin/muster; probed for the suffix /bin/muster.
        let installed = Path::new("/usr/bin/muster");
        ProviderHooks::setup_in_with_codex(installed, &home, &config, &xdg, &codex).unwrap();

        let statuses =
            ProviderHooks::status_in(Path::new("/bin/muster"), &home, &config, &xdg, &codex)
                .unwrap();

        assert!(
            statuses
                .iter()
                .all(|status| status.state() == HookState::Stale),
            "a suffix of another executable's path is stale, not installed"
        );
        let exact = ProviderHooks::status_in(installed, &home, &config, &xdg, &codex).unwrap();
        assert!(
            exact
                .iter()
                .all(|status| status.state() == HookState::Installed),
            "the exact executable still reads installed"
        );
        fs::remove_dir_all(root).unwrap();
    }

    /// A hook invoking the wrong provider callback is not healthy.
    #[test]
    fn status_rejects_a_wrong_provider_callback() {
        let root = std::env::temp_dir().join(format!("muster-wrongp-{}", uuid::Uuid::new_v4()));
        let home = root.join("home");
        let config = root.join("config");
        let xdg = root.join("xdg");
        let codex = home.join(CODEX_CONFIG_DIR);
        fs::create_dir_all(&home).unwrap();
        let exe = Path::new("/opt/muster/muster");
        ProviderHooks::setup_in_with_codex(exe, &home, &config, &xdg, &codex).unwrap();
        // Corrupt Claude's hook to invoke the Gemini callback.
        let claude = home.join(CLAUDE_SETTINGS);
        let wrong = fs::read_to_string(&claude).unwrap().replace(
            AgentTool::Claude.protocol_token(),
            AgentTool::Gemini.protocol_token(),
        );
        fs::write(&claude, wrong).unwrap();

        let statuses = ProviderHooks::status_in(exe, &home, &config, &xdg, &codex).unwrap();

        let claude_status = statuses
            .iter()
            .find(|status| status.provider() == AgentTool::Claude)
            .expect("claude status present");
        assert_eq!(
            claude_status.state(),
            HookState::Stale,
            "a wrong-provider callback needs hooks setup again"
        );
        fs::remove_dir_all(root).unwrap();
    }

    /// A hook the provider never evaluates (commented out) is not installed.
    #[test]
    fn status_ignores_commented_out_hooks() {
        let root = std::env::temp_dir().join(format!("muster-comment-{}", uuid::Uuid::new_v4()));
        let home = root.join("home");
        let config = root.join("config");
        let xdg = root.join("xdg");
        let codex = home.join(CODEX_CONFIG_DIR);
        fs::create_dir_all(&home).unwrap();
        let exe = Path::new("/opt/muster/muster");
        ProviderHooks::setup_in_with_codex(exe, &home, &config, &xdg, &codex).unwrap();
        // Disable the Kimi hook the way a user would: comment every line out.
        let kimi = home.join(KIMI_CONFIG);
        let disabled: String = fs::read_to_string(&kimi)
            .unwrap()
            .lines()
            .map(|line| format!("# {line}\n"))
            .collect();
        fs::write(&kimi, disabled).unwrap();

        let statuses = ProviderHooks::status_in(exe, &home, &config, &xdg, &codex).unwrap();

        let kimi_status = statuses
            .iter()
            .find(|status| status.provider() == AgentTool::Kimi)
            .expect("kimi status present");
        assert_eq!(
            kimi_status.state(),
            HookState::Missing,
            "a fully commented hook is not active"
        );
        fs::remove_dir_all(root).unwrap();
    }

    /// Status distinguishes missing, stale, and installed hook files.
    #[test]
    fn status_reports_missing_stale_and_installed() {
        let root = std::env::temp_dir().join(format!("muster-status-{}", uuid::Uuid::new_v4()));
        let home = root.join("home");
        let config = root.join("config");
        let xdg = root.join("xdg");
        let codex = home.join(CODEX_CONFIG_DIR);
        fs::create_dir_all(&home).unwrap();
        let exe = Path::new("/opt/muster/muster");

        // Nothing installed yet: everything is missing.
        let before = ProviderHooks::status_in(exe, &home, &config, &xdg, &codex).unwrap();
        assert!(
            before
                .iter()
                .all(|status| status.state() == HookState::Missing)
        );

        // Install for this executable: everything is installed.
        ProviderHooks::setup_in_with_codex(exe, &home, &config, &xdg, &codex).unwrap();
        let after = ProviderHooks::status_in(exe, &home, &config, &xdg, &codex).unwrap();
        assert!(
            after
                .iter()
                .all(|status| status.state() == HookState::Installed)
        );

        // A different binary path: the same files are now stale.
        let moved = Path::new("/elsewhere/muster");
        let stale = ProviderHooks::status_in(moved, &home, &config, &xdg, &codex).unwrap();
        assert!(
            stale
                .iter()
                .all(|status| status.state() == HookState::Stale)
        );

        fs::remove_dir_all(root).unwrap();
    }

    /// `status_in` reports Installed for every provider when the executable path
    /// contains characters that JSON-encode differently from their raw form.
    /// A backslash is a valid POSIX path character that JSON encodes as `\\`,
    /// so the Amp and OpenCode plugin files embed the escaped form while
    /// `file_state` would previously search only for the raw path.
    #[test]
    fn status_detects_installed_when_executable_has_special_chars() {
        let root =
            std::env::temp_dir().join(format!("muster-status-encoded-{}", uuid::Uuid::new_v4()));
        let home = root.join("home");
        let config = root.join("config");
        let xdg = root.join("xdg");
        let codex = home.join(CODEX_CONFIG_DIR);
        // Path with a backslash: JSON encodes it as \\, so content.contains(raw)
        // would miss the Amp and OpenCode plugin files.
        let exe_path_str = format!("{}/mu\\ster/muster", root.display());
        let exe_path = Path::new(&exe_path_str);

        ProviderHooks::setup_in_with_codex(exe_path, &home, &config, &xdg, &codex).unwrap();
        let statuses = ProviderHooks::status_in(exe_path, &home, &config, &xdg, &codex).unwrap();

        for status in &statuses {
            assert_eq!(
                status.state(),
                HookState::Installed,
                "{} should be Installed",
                status.provider()
            );
        }
        fs::remove_dir_all(root).unwrap();
    }

    /// Atomic replacement retains restrictive permissions from an existing
    /// provider settings file.
    #[cfg(unix)]
    #[test]
    fn atomic_writes_preserve_existing_permissions() {
        use std::os::unix::fs::PermissionsExt;

        const PRIVATE_MODE: u32 = 0o600;
        const PERMISSION_MASK: u32 = 0o777;
        let root = std::env::temp_dir().join(format!("muster-hook-mode-{}", uuid::Uuid::new_v4()));
        let path = root.join("settings.json");
        ProviderHooks::write_text(&path, "old").unwrap();
        fs::set_permissions(&path, fs::Permissions::from_mode(PRIVATE_MODE)).unwrap();

        ProviderHooks::write_text(&path, "new").unwrap();

        assert_eq!(
            fs::metadata(&path).unwrap().permissions().mode() & PERMISSION_MASK,
            PRIVATE_MODE
        );
        fs::remove_dir_all(root).unwrap();
    }

    /// Rewriting a symlinked provider config updates its target without
    /// replacing the dotfile-managed alias.
    #[cfg(unix)]
    #[test]
    fn atomic_writes_preserve_provider_config_symlinks() {
        use std::os::unix::fs::symlink;

        let root =
            std::env::temp_dir().join(format!("muster-hook-symlink-{}", uuid::Uuid::new_v4()));
        let target = root.join("managed/settings.json");
        let link = root.join("settings.json");
        ProviderHooks::write_text(&target, "old").unwrap();
        symlink(&target, &link).unwrap();

        ProviderHooks::write_text(&link, "new").unwrap();

        assert!(
            fs::symlink_metadata(&link)
                .unwrap()
                .file_type()
                .is_symlink()
        );
        assert_eq!(fs::read_to_string(target).unwrap(), "new");
        fs::remove_dir_all(root).unwrap();
    }

    /// First-time setup follows a relative dangling symlink and creates its
    /// target without replacing the dotfile-managed alias.
    #[cfg(unix)]
    #[test]
    fn atomic_writes_preserve_dangling_provider_config_symlinks() {
        use std::os::unix::fs::symlink;

        const RELATIVE_TARGET: &str = "managed/settings.json";
        let root =
            std::env::temp_dir().join(format!("muster-hook-dangling-{}", uuid::Uuid::new_v4()));
        let target = root.join(RELATIVE_TARGET);
        let link = root.join("settings.json");
        fs::create_dir_all(&root).unwrap();
        symlink(RELATIVE_TARGET, &link).unwrap();

        ProviderHooks::write_text(&link, "new").unwrap();

        assert!(
            fs::symlink_metadata(&link)
                .unwrap()
                .file_type()
                .is_symlink()
        );
        assert_eq!(fs::read_to_string(target).unwrap(), "new");
        fs::remove_dir_all(root).unwrap();
    }
}