lorum 0.1.3-alpha.1

Unified MCP configuration manager for AI coding tools
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
//! Kimi adapter for reading/writing MCP and hooks configuration.
//!
//! Configuration file: `~/.kimi/config.toml` (global)
//!
//! MCP format (TOML):
//! ```toml
//! [mcp.client.server-name]
//! command = "npx"
//! args = ["-y", "some-pkg"]
//!
//! [mcp.client.server-name.env]
//! KEY = "value"
//! ```
//!
//! Hooks format (TOML):
//! ```toml
//! [[hooks]]
//! event = "PreToolUse"
//! matcher = "Shell"
//! command = ".kimi/hooks/safety-check.sh"
//! timeout = 10
//! ```

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

use crate::adapters::{
    ConfigValidator, HooksAdapter, RulesAdapter, Severity, SkillsAdapter, ToolAdapter,
    ValidationIssue, kebab_to_pascal, pascal_to_kebab, read_rules_file, toml_utils,
    validate_all_syntax, write_rules_file,
};
use crate::config::{HookHandler, HooksConfig, McpConfig};
use crate::error::LorumError;
use crate::skills::{SkillEntry, copy_dir_recursive, scan_skills_dir};

/// Adapter for Kimi rules.
///
/// Reads and writes rules content from Kimi's `AGENTS.md`
/// file located at the project root.
pub struct KimiRulesAdapter;

impl RulesAdapter for KimiRulesAdapter {
    fn name(&self) -> &str {
        "kimi"
    }

    fn rules_path(&self, project_root: &Path) -> PathBuf {
        project_root.join("AGENTS.md")
    }

    fn read_rules(&self, project_root: &Path) -> Result<Option<String>, LorumError> {
        read_rules_file(&self.rules_path(project_root))
    }

    fn write_rules(&self, project_root: &Path, content: &str) -> Result<(), LorumError> {
        write_rules_file(&self.rules_path(project_root), content)
    }
}

/// Adapter for Kimi skills.
///
/// Reads and writes skills from Kimi's `~/.kimi/skills/` directory.
pub struct KimiSkillsAdapter;

impl SkillsAdapter for KimiSkillsAdapter {
    /// Returns the adapter name `"kimi"`.
    fn name(&self) -> &str {
        "kimi"
    }

    /// Returns `~/.kimi/skills/` if the home directory can be determined.
    fn skills_base_dir(&self) -> Option<PathBuf> {
        dirs::home_dir().map(|h| h.join(".kimi").join("skills"))
    }

    /// Scans `~/.kimi/skills/` and returns all discovered skills.
    ///
    /// Returns an empty list when the directory does not exist.
    fn read_skills(&self) -> Result<Vec<SkillEntry>, LorumError> {
        let Some(dir) = self.skills_base_dir() else {
            return Ok(Vec::new());
        };
        scan_skills_dir(&dir)
    }

    /// Copies a skill directory into `~/.kimi/skills/<name>`.
    ///
    /// If a skill with the same name already exists it is renamed to
    /// `.old-<name>` before the new content is copied.
    fn write_skill(&self, name: &str, source_dir: &Path) -> Result<(), LorumError> {
        let dir = self.skills_base_dir().ok_or_else(|| LorumError::Other {
            message: "cannot determine home directory".into(),
        })?;
        let target = dir.join(name);
        if target.exists() {
            let old = dir.join(format!(".old-{name}"));
            if old.exists() {
                std::fs::remove_dir_all(&old)?;
            }
            std::fs::rename(&target, &old)?;
        }
        copy_dir_recursive(source_dir, &target)
    }

    /// Removes a skill directory from `~/.kimi/skills/`.
    ///
    /// Does nothing if the skill does not exist.
    fn remove_skill(&self, name: &str) -> Result<(), LorumError> {
        let dir = self.skills_base_dir().ok_or_else(|| LorumError::Other {
            message: "cannot determine home directory".into(),
        })?;
        let target = dir.join(name);
        if target.exists() {
            std::fs::remove_dir_all(target)?;
        }
        Ok(())
    }
}

/// Adapter for Kimi.
///
/// Reads and writes MCP server configurations from Kimi's
/// `~/.kimi/config.toml` file under the `[mcp.client]` section,
/// preserving any non-MCP fields.
pub struct KimiAdapter;

/// Top-level TOML key for the mcp section.
const MCP_TOP: &str = "mcp";
/// Nested key under `mcp` for client (server definitions).
const MCP_CLIENT: &str = "client";

/// Returns the global Kimi config path: `~/.kimi/config.toml`.
fn global_config_path() -> Option<PathBuf> {
    dirs::home_dir().map(|h| h.join(".kimi").join("config.toml"))
}

impl HooksAdapter for KimiAdapter {
    fn name(&self) -> &str {
        "kimi"
    }

    fn config_paths(&self) -> Vec<PathBuf> {
        global_config_path().into_iter().collect()
    }

    fn read_hooks(&self) -> Result<HooksConfig, LorumError> {
        let path = match global_config_path() {
            Some(p) => p,
            None => return Ok(HooksConfig::default()),
        };
        if !path.exists() {
            return Ok(HooksConfig::default());
        }
        let root = toml_utils::read_existing_toml(&path)?;
        Ok(parse_hooks_from_toml(&root))
    }

    fn write_hooks(&self, config: &HooksConfig) -> Result<(), LorumError> {
        let path = match global_config_path() {
            Some(p) => p,
            None => {
                return Err(LorumError::Other {
                    message: "cannot determine home directory".into(),
                });
            }
        };
        let mut root = toml_utils::read_existing_toml(&path)?;
        let hooks_array = hooks_config_to_toml_array(config);

        let root_table = root.as_table_mut().ok_or_else(|| LorumError::Other {
            message: format!("expected table at root of {}", path.display()),
        })?;
        root_table.insert("hooks".into(), toml::Value::Array(hooks_array));

        toml_utils::write_toml(&path, &root)
    }

    fn lorum_to_tool_event(&self, lorum_event: &str) -> Option<String> {
        Some(kebab_to_pascal(lorum_event))
    }

    fn tool_to_lorum_event(&self, tool_event: &str) -> Option<String> {
        Some(pascal_to_kebab(tool_event))
    }
}

impl ConfigValidator for KimiAdapter {
    fn name(&self) -> &str {
        "kimi"
    }

    fn validate_config(&self) -> Result<Vec<ValidationIssue>, LorumError> {
        // 1. Run default syntax validation (TOML)
        let mut issues = validate_all_syntax(&<Self as ToolAdapter>::config_paths(self));

        // 2. Extra check: validate [mcp.client] field structure
        if let Some(ref path) = global_config_path() {
            if path.exists() {
                let content = match std::fs::read_to_string(path) {
                    Ok(c) => c,
                    Err(e) => {
                        issues.push(ValidationIssue {
                            severity: Severity::Error,
                            message: format!("failed to read file: {e}"),
                            path: Some(path.clone()),
                            line: None,
                        });
                        return Ok(issues);
                    }
                };

                let root: toml::Value = match toml::from_str(&content) {
                    Ok(v) => v,
                    Err(_) => {
                        // Syntax errors already reported by validate_all_syntax
                        return Ok(issues);
                    }
                };

                if let Some(client) = root
                    .get(MCP_TOP)
                    .and_then(|v| v.get(MCP_CLIENT))
                    .and_then(|v| v.as_table())
                {
                    for (server_name, server_value) in client {
                        if let Some(server_table) = server_value.as_table() {
                            // Check for required `command` field
                            if !server_table.contains_key("command") {
                                issues.push(ValidationIssue {
                                    severity: Severity::Warning,
                                    message: format!(
                                        "MCP server '{}' is missing required 'command' field",
                                        server_name
                                    ),
                                    path: Some(path.clone()),
                                    line: None,
                                });
                            }

                            // Check `args` is an array if present
                            if let Some(args) = server_table.get("args") {
                                if !args.is_array() {
                                    issues.push(ValidationIssue {
                                        severity: Severity::Warning,
                                        message: format!(
                                            "MCP server '{}' has 'args' that is not an array",
                                            server_name
                                        ),
                                        path: Some(path.clone()),
                                        line: None,
                                    });
                                }
                            }
                        }
                    }
                }
            }
        }

        Ok(issues)
    }
}

impl ToolAdapter for KimiAdapter {
    fn name(&self) -> &str {
        "kimi"
    }

    fn config_paths(&self) -> Vec<PathBuf> {
        global_config_path().into_iter().collect()
    }

    fn read_mcp(&self) -> Result<McpConfig, LorumError> {
        let path = match global_config_path() {
            Some(p) => p,
            None => return Ok(McpConfig::default()),
        };
        if !path.exists() {
            return Ok(McpConfig::default());
        }
        let root = toml_utils::read_existing_toml(&path)?;
        Ok(parse_mcp_client(&root))
    }

    fn write_mcp(&self, config: &McpConfig) -> Result<(), LorumError> {
        let path = match global_config_path() {
            Some(p) => p,
            None => {
                return Err(LorumError::Other {
                    message: "cannot determine home directory".into(),
                });
            }
        };
        let mut root = toml_utils::read_existing_toml(&path)?;
        let client_table = toml_utils::mcp_config_to_toml_value(config);

        let root_table = root.as_table_mut().ok_or_else(|| LorumError::Other {
            message: format!("expected table at root of {}", path.display()),
        })?;
        let mcp_entry = root_table
            .entry(MCP_TOP)
            .or_insert_with(|| toml::Value::Table(toml::map::Map::new()));
        mcp_entry
            .as_table_mut()
            .ok_or_else(|| LorumError::Other {
                message: format!("expected table for '{}' at {}", MCP_TOP, path.display()),
            })?
            .insert(MCP_CLIENT.into(), client_table);

        toml_utils::write_toml(&path, &root)
    }
}

/// Parse the `mcp.client` section from a TOML value into `McpConfig`.
fn parse_mcp_client(root: &toml::Value) -> McpConfig {
    let Some(servers) = root
        .get(MCP_TOP)
        .and_then(|v| v.get(MCP_CLIENT))
        .and_then(|v| v.as_table())
    else {
        return McpConfig::default();
    };

    let mut map = std::collections::BTreeMap::new();
    for (name, value) in servers {
        if let Some(server) = toml_utils::parse_mcp_server_toml(value.as_table()) {
            map.insert(name.clone(), server);
        }
    }
    McpConfig { servers: map }
}

/// Parse hooks from a TOML value.
fn parse_hooks_from_toml(root: &toml::Value) -> HooksConfig {
    let Some(hooks_array) = root.get("hooks").and_then(|v| v.as_array()) else {
        return HooksConfig::default();
    };
    let mut events: BTreeMap<String, Vec<HookHandler>> = BTreeMap::new();
    for entry in hooks_array {
        let Some(table) = entry.as_table() else {
            continue;
        };
        let Some(pascal_event) = table
            .get("event")
            .and_then(|v| v.as_str())
            .filter(|s| !s.is_empty())
        else {
            continue;
        };
        let kebab_event = pascal_to_kebab(pascal_event);
        let Some(matcher) = table
            .get("matcher")
            .and_then(|v| v.as_str())
            .filter(|s| !s.is_empty())
        else {
            continue;
        };
        let Some(command) = table
            .get("command")
            .and_then(|v| v.as_str())
            .filter(|s| !s.is_empty())
        else {
            continue;
        };
        let timeout = table
            .get("timeout")
            .and_then(|v| v.as_integer())
            .and_then(|v| u64::try_from(v).ok());
        let handler_type = table.get("type").and_then(|v| v.as_str()).map(String::from);
        events.entry(kebab_event).or_default().push(HookHandler {
            matcher: matcher.to_string(),
            command: command.to_string(),
            timeout,
            handler_type,
        });
    }
    HooksConfig { events }
}

/// Convert a HooksConfig to a TOML array of hook tables.
fn hooks_config_to_toml_array(config: &HooksConfig) -> Vec<toml::Value> {
    let mut array = Vec::new();
    for (event_name, handlers) in &config.events {
        let pascal_event = kebab_to_pascal(event_name);
        for h in handlers {
            let mut table = toml::map::Map::new();
            table.insert("event".into(), toml::Value::String(pascal_event.clone()));
            table.insert("matcher".into(), toml::Value::String(h.matcher.clone()));
            table.insert("command".into(), toml::Value::String(h.command.clone()));
            if let Some(t) = h.timeout {
                table.insert("timeout".into(), toml::Value::Integer(t as i64));
            }
            if let Some(ref ty) = h.handler_type {
                table.insert("type".into(), toml::Value::String(ty.clone()));
            }
            array.push(toml::Value::Table(table));
        }
    }
    array
}

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

    #[test]
    fn rules_path_returns_agents_md() {
        let adapter = KimiRulesAdapter;
        let path = adapter.rules_path(Path::new("/tmp/myproject"));
        assert_eq!(path, PathBuf::from("/tmp/myproject/AGENTS.md"));
    }

    #[test]
    fn read_rules_returns_none_when_file_missing() {
        let dir = tempfile::tempdir().unwrap();
        let adapter = KimiRulesAdapter;
        let result = adapter.read_rules(dir.path()).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn write_rules_creates_file() {
        let dir = tempfile::tempdir().unwrap();
        let adapter = KimiRulesAdapter;
        let path = adapter.rules_path(dir.path());
        assert!(!path.exists());

        adapter
            .write_rules(dir.path(), "Use 4-space indentation.")
            .unwrap();
        assert!(path.exists());
    }

    #[test]
    fn write_then_read_roundtrip() {
        let dir = tempfile::tempdir().unwrap();
        let adapter = KimiRulesAdapter;
        let content = "## Style\nUse 4-space indentation.\n";

        adapter.write_rules(dir.path(), content).unwrap();
        let read = adapter.read_rules(dir.path()).unwrap();
        assert_eq!(read, Some(content.to_owned()));
    }

    #[test]
    fn rules_adapter_name() {
        let adapter = KimiRulesAdapter;
        assert_eq!(adapter.name(), "kimi");
    }
}

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

    #[test]
    #[serial_test::serial]
    fn skills_adapter_name() {
        let adapter = KimiSkillsAdapter;
        assert_eq!(adapter.name(), "kimi");
    }

    #[test]
    #[serial_test::serial]
    fn read_skills_empty_when_no_dir() {
        let home = tempfile::tempdir().unwrap();
        unsafe { std::env::set_var("HOME", home.path()) };
        let adapter = KimiSkillsAdapter;
        let skills = adapter.read_skills().unwrap();
        assert!(skills.is_empty());
        unsafe { std::env::remove_var("HOME") };
    }

    #[test]
    #[serial_test::serial]
    fn write_skill_copies_directory_contents() {
        let home = tempfile::tempdir().unwrap();
        unsafe { std::env::set_var("HOME", home.path()) };
        let src = tempfile::tempdir().unwrap();
        std::fs::write(
            src.path().join("SKILL.md"),
            "---\nname: test-skill\ndescription: \"Test\"\n---\n",
        )
        .unwrap();

        let adapter = KimiSkillsAdapter;
        adapter.write_skill("test-skill", src.path()).unwrap();
        let skills = adapter.read_skills().unwrap();
        assert!(skills.iter().any(|s| s.manifest.name == "test-skill"));
        adapter.remove_skill("test-skill").unwrap();
        unsafe { std::env::remove_var("HOME") };
    }

    #[test]
    #[serial_test::serial]
    fn write_skill_backs_up_existing() {
        let home = tempfile::tempdir().unwrap();
        unsafe { std::env::set_var("HOME", home.path()) };
        let src1 = tempfile::tempdir().unwrap();
        std::fs::write(
            src1.path().join("SKILL.md"),
            "---\nname: my-skill\ndescription: \"v1\"\n---\n",
        )
        .unwrap();

        let adapter = KimiSkillsAdapter;
        adapter.write_skill("my-skill", src1.path()).unwrap();

        // Write a second version -- should back up the first.
        let src2 = tempfile::tempdir().unwrap();
        std::fs::write(
            src2.path().join("SKILL.md"),
            "---\nname: my-skill\ndescription: \"v2\"\n---\n",
        )
        .unwrap();
        adapter.write_skill("my-skill", src2.path()).unwrap();

        let skills = adapter.read_skills().unwrap();
        skills
            .iter()
            .find(|s| s.manifest.name == "my-skill" && s.manifest.description == "v2")
            .expect("should find skill with description v2");

        // Backup should exist.
        let base = adapter.skills_base_dir().unwrap();
        assert!(base.join(".old-my-skill").exists());

        adapter.remove_skill("my-skill").unwrap();
        unsafe { std::env::remove_var("HOME") };
    }

    #[test]
    #[serial_test::serial]
    fn remove_skill_deletes_directory() {
        let home = tempfile::tempdir().unwrap();
        unsafe { std::env::set_var("HOME", home.path()) };
        let adapter = KimiSkillsAdapter;
        adapter
            .write_skill("test-skill", tempfile::tempdir().unwrap().path())
            .unwrap();
        adapter.remove_skill("test-skill").unwrap();
        let skills = adapter.read_skills().unwrap();
        assert!(!skills.iter().any(|s| s.manifest.name == "test-skill"));
        unsafe { std::env::remove_var("HOME") };
    }

    #[test]
    #[serial_test::serial]
    fn remove_skill_is_ok_when_missing() {
        let home = tempfile::tempdir().unwrap();
        unsafe { std::env::set_var("HOME", home.path()) };
        let adapter = KimiSkillsAdapter;
        // Removing a non-existent skill should not error.
        adapter.remove_skill("no-such-skill").unwrap();
        unsafe { std::env::remove_var("HOME") };
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::adapters::test_utils::make_server;
    use std::collections::BTreeMap;
    use std::fs;

    #[test]
    fn read_mcp_from_valid_toml() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        let toml_str = r#"
other_field = true

[mcp.client.test-server]
command = "npx"
args = ["-y", "some-pkg"]

[mcp.client.test-server.env]
KEY = "value"
"#;
        fs::write(&path, toml_str).unwrap();

        let root: toml::Value = toml::from_str(toml_str).unwrap();
        let config = parse_mcp_client(&root);

        assert_eq!(config.servers.len(), 1);
        let server = &config.servers["test-server"];
        assert_eq!(server.command, "npx");
        assert_eq!(server.args, vec!["-y", "some-pkg"]);
        assert_eq!(server.env.get("KEY").unwrap(), "value");
    }

    #[test]
    fn read_mcp_empty_when_no_field() {
        let root: toml::Value = toml::from_str("other = true").unwrap();
        let config = parse_mcp_client(&root);
        assert!(config.servers.is_empty());
    }

    #[test]
    fn write_mcp_preserves_other_fields() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");

        let original = r#"other_field = true
[mcp]
"#;
        fs::write(&path, original).unwrap();

        let mut root = toml_utils::read_existing_toml(&path).unwrap();
        let config = McpConfig {
            servers: {
                let mut m = BTreeMap::new();
                m.insert("svr".into(), make_server("cmd", &["a"], &[("K", "V")]));
                m
            },
        };

        let client_table = toml_utils::mcp_config_to_toml_value(&config);
        let root_table = root.as_table_mut().unwrap();
        let mcp_entry = root_table
            .entry(MCP_TOP)
            .or_insert_with(|| toml::Value::Table(toml::map::Map::new()));
        mcp_entry
            .as_table_mut()
            .unwrap()
            .insert(MCP_CLIENT.into(), client_table);
        toml_utils::write_toml(&path, &root).unwrap();

        let result: toml::Value = toml::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
        assert_eq!(result["other_field"].as_bool(), Some(true));
        assert_eq!(
            result["mcp"]["client"]["svr"]["command"].as_str(),
            Some("cmd")
        );
    }

    #[test]
    fn write_mcp_creates_file_when_missing() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("subdir").join("config.toml");
        assert!(!path.exists());

        let config = McpConfig {
            servers: {
                let mut m = BTreeMap::new();
                m.insert("s".into(), make_server("c", &[], &[]));
                m
            },
        };
        let mut root = toml::Value::Table(toml::map::Map::new());
        let client_table = toml_utils::mcp_config_to_toml_value(&config);
        root.as_table_mut()
            .unwrap()
            .entry(MCP_TOP)
            .or_insert_with(|| toml::Value::Table(toml::map::Map::new()))
            .as_table_mut()
            .unwrap()
            .insert(MCP_CLIENT.into(), client_table);
        toml_utils::write_toml(&path, &root).unwrap();

        assert!(path.exists());
        let result: toml::Value = toml::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
        assert_eq!(result["mcp"]["client"]["s"]["command"].as_str(), Some("c"));
    }

    #[test]
    fn roundtrip_toml() {
        let config = McpConfig {
            servers: {
                let mut m = BTreeMap::new();
                m.insert(
                    "a".into(),
                    make_server("node", &["index.js"], &[("PORT", "3000")]),
                );
                m.insert("b".into(), make_server("python", &["main.py"], &[]));
                m
            },
        };
        let toml_val = toml_utils::mcp_config_to_toml_value(&config);
        let mut outer = toml::map::Map::new();
        let mut mcp_table = toml::map::Map::new();
        mcp_table.insert(MCP_CLIENT.into(), toml_val);
        outer.insert(MCP_TOP.into(), toml::Value::Table(mcp_table));
        let parsed = parse_mcp_client(&toml::Value::Table(outer));
        assert_eq!(config, parsed);
    }

    #[test]
    fn adapter_name() {
        let adapter = KimiAdapter;
        assert_eq!(ToolAdapter::name(&adapter), "kimi");
    }

    // --- hooks -------------------------------------------------------------

    #[test]
    fn parse_hooks_from_valid_toml() {
        let toml_str = r#"
[[hooks]]
event = "PreToolUse"
matcher = "Bash"
command = "scripts/check.sh"
timeout = 60

[[hooks]]
event = "PreToolUse"
matcher = "Write"
command = "scripts/write-check.sh"

[[hooks]]
event = "PostToolUse"
matcher = "Edit"
command = "cargo fmt"
"#;
        let root: toml::Value = toml::from_str(toml_str).unwrap();
        let config = parse_hooks_from_toml(&root);
        assert_eq!(config.events.len(), 2);
        let pre = &config.events["pre-tool-use"];
        assert_eq!(pre.len(), 2);
        assert_eq!(pre[0].matcher, "Bash");
        assert_eq!(pre[0].timeout, Some(60));
        assert_eq!(pre[1].matcher, "Write");
        assert_eq!(pre[1].timeout, None);
        let post = &config.events["post-tool-use"];
        assert_eq!(post.len(), 1);
        assert_eq!(post[0].matcher, "Edit");
    }

    #[test]
    fn parse_hooks_empty_when_no_field() {
        let root: toml::Value = toml::from_str("other = true").unwrap();
        let config = parse_hooks_from_toml(&root);
        assert!(config.events.is_empty());
    }

    #[test]
    fn write_hooks_preserves_other_fields() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        fs::write(&path, "other_field = true\n").unwrap();

        let mut config = HooksConfig::default();
        config.events.insert(
            "pre-tool-use".into(),
            vec![HookHandler {
                matcher: "Shell".into(),
                command: "check.sh".into(),
                timeout: Some(10),
                handler_type: None,
            }],
        );

        // Test via helper functions (adapter uses global path).
        let mut root = toml_utils::read_existing_toml(&path).unwrap();
        let hooks_array = hooks_config_to_toml_array(&config);
        root.as_table_mut()
            .unwrap()
            .insert("hooks".into(), toml::Value::Array(hooks_array));
        toml_utils::write_toml(&path, &root).unwrap();

        let result: toml::Value = toml::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
        assert_eq!(result["other_field"].as_bool(), Some(true));
        let hooks = result["hooks"].as_array().unwrap();
        assert_eq!(hooks.len(), 1);
        assert_eq!(hooks[0]["event"].as_str(), Some("PreToolUse"));
        assert_eq!(hooks[0]["matcher"].as_str(), Some("Shell"));
        assert_eq!(hooks[0]["timeout"].as_integer(), Some(10));
    }

    #[test]
    fn hooks_roundtrip_toml() {
        let mut config = HooksConfig::default();
        config.events.insert(
            "pre-tool-use".into(),
            vec![HookHandler {
                matcher: "Bash".into(),
                command: "check.sh".into(),
                timeout: Some(60),
                handler_type: Some("command".into()),
            }],
        );
        let array = hooks_config_to_toml_array(&config);
        let mut root = toml::map::Map::new();
        root.insert("hooks".into(), toml::Value::Array(array));
        let parsed = parse_hooks_from_toml(&toml::Value::Table(root));
        assert_eq!(config, parsed);
    }
}