mind-cli 0.46.0

A manager for agent tooling (skills, agents, rules, tools) that melds arbitrary git repos and links items into your agent directories.
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
//! User configuration for `mind`, stored at `~/.mind/config.toml`.

use serde::de::{self, Deserializer, MapAccess, Visitor};
use serde::ser::{SerializeStruct, Serializer};
use serde::{Deserialize, Serialize};

use crate::error::{ItemKind, MindError, Result};
use crate::paths::Paths;

/// One agent home ("lobe") in the config, optionally carrying a `kinds` filter
/// (HARN-1). A lobe with no filter (`kinds == None`) admits all linkable kinds,
/// which is the historical behavior; a filtered lobe admits only the listed
/// kinds.
///
/// Serialization is shape-preserving for backward compatibility: a no-`kinds`
/// entry round-trips as a bare string (`"~/.claude"`), exactly as the original
/// `lobes = ["~/.claude"]` config did. A filtered entry serializes as an inline
/// table (`{ path = "~/.gemini", kinds = ["skill", "agent"] }`). On the way in,
/// both a bare string and the table form parse; an unknown table key or an
/// invalid kind string is rejected.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LobeEntry {
    /// The lobe directory. `~` is expanded at resolution time; stored verbatim.
    pub path: String,
    /// The kinds this lobe admits, or `None` for "all linkable kinds".
    pub kinds: Option<Vec<ItemKind>>,
}

impl LobeEntry {
    /// A lobe path with no kinds filter (admits all kinds).
    pub fn bare(path: impl Into<String>) -> Self {
        LobeEntry {
            path: path.into(),
            kinds: None,
        }
    }

    /// The lobe directory path.
    pub fn path(&self) -> &str {
        &self.path
    }

    /// The kinds filter, or `None` for "all linkable kinds".
    pub fn kinds(&self) -> Option<&[ItemKind]> {
        self.kinds.as_deref()
    }
}

impl Serialize for LobeEntry {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match &self.kinds {
            // Backward compat: a no-kinds lobe is a bare string, so an existing
            // `lobes = ["~/.claude"]` config round-trips unchanged.
            None => serializer.serialize_str(&self.path),
            Some(kinds) => {
                let mut st = serializer.serialize_struct("LobeEntry", 2)?;
                st.serialize_field("path", &self.path)?;
                let kind_strs: Vec<&str> = kinds.iter().map(|k| k.as_str()).collect();
                st.serialize_field("kinds", &kind_strs)?;
                st.end()
            }
        }
    }
}

impl<'de> Deserialize<'de> for LobeEntry {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct LobeEntryVisitor;

        impl<'de> Visitor<'de> for LobeEntryVisitor {
            type Value = LobeEntry;

            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                f.write_str("a lobe path string or a { path, kinds } table")
            }

            fn visit_str<E>(self, v: &str) -> std::result::Result<LobeEntry, E>
            where
                E: de::Error,
            {
                Ok(LobeEntry::bare(v.to_string()))
            }

            fn visit_string<E>(self, v: String) -> std::result::Result<LobeEntry, E>
            where
                E: de::Error,
            {
                Ok(LobeEntry::bare(v))
            }

            fn visit_map<A>(self, mut map: A) -> std::result::Result<LobeEntry, A::Error>
            where
                A: MapAccess<'de>,
            {
                let mut path: Option<String> = None;
                let mut kinds: Option<Vec<String>> = None;
                while let Some(key) = map.next_key::<String>()? {
                    match key.as_str() {
                        "path" => {
                            if path.is_some() {
                                return Err(de::Error::duplicate_field("path"));
                            }
                            path = Some(map.next_value()?);
                        }
                        "kinds" => {
                            if kinds.is_some() {
                                return Err(de::Error::duplicate_field("kinds"));
                            }
                            kinds = Some(map.next_value()?);
                        }
                        // deny_unknown_fields semantics on the table variant.
                        other => {
                            return Err(de::Error::unknown_field(other, &["path", "kinds"]));
                        }
                    }
                }
                let path = path.ok_or_else(|| de::Error::missing_field("path"))?;
                let kinds = match kinds {
                    Some(strs) => Some(ItemKind::parse_kinds(&strs).map_err(de::Error::custom)?),
                    None => None,
                };
                Ok(LobeEntry { path, kinds })
            }
        }

        deserializer.deserialize_any(LobeEntryVisitor)
    }
}

/// Persistent settings. Currently just the agent homes ("lobes") to link items
/// into.
#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
    /// Agent homes ("lobes") `mind` links installed items into. Empty means "use
    /// the default" (see [`crate::paths::Paths::agent_homes`]). Each entry is
    /// either a bare path string or a `{ path, kinds }` table (HARN-1). `~` is
    /// expanded at resolution time; entries are stored verbatim.
    #[serde(default)]
    pub lobes: Vec<LobeEntry>,

    /// Prefer SSH for melded remotes. When true, `meld` rewrites an https remote
    /// (e.g. a `owner/repo` shorthand) to its `git@host:owner/repo` SSH form, so
    /// cloning uses the user's SSH key/agent instead of prompting for an https
    /// username/password (CLI-19). Local paths and explicit `git@`/`ssh://` specs
    /// are unaffected. Default false (https).
    #[serde(default)]
    pub ssh: bool,

    /// Default destination source for `absorb` (ABS-2). When set, `absorb` uses
    /// this path as the destination unless `--to` or `MIND_ABSORB_TO` is given.
    /// Saved interactively when the user chooses a destination via the ABS-3 prompt
    /// and confirms saving (ABS-4). `~` is expanded at use.
    ///
    /// The canonical config key is `absorb-to` (kebab-case); `absorb_to` (snake_case)
    /// is accepted as a legacy alias. New writes always emit `absorb-to`.
    // spec: CLI-171
    #[serde(
        rename = "absorb-to",
        alias = "absorb_to",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub absorb_to: Option<String>,

    /// Ceiling for every source-controlled metadata read (DSC-103). Stored as
    /// written (`"32MiB"`, `"16777216"`, `"unlimited"`) and parsed at startup by
    /// [`resolve_metadata_limit_detail`]; absent means the [`METADATA_SIZE_LIMIT`]
    /// default. The lowest-precedence of the three ways to set it: the
    /// `--max-metadata-size` flag and `MIND_MAX_METADATA_SIZE` both outrank it
    /// (DSC-104).
    // spec: DSC-103
    #[serde(
        rename = "max-metadata-size",
        alias = "max_metadata_size",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub max_metadata_size: Option<String>,

    /// How many hook results `~/.mind/hooks/history.jsonl` keeps (HOOK-163);
    /// `0` turns the history off. Absent means
    /// [`crate::hook_log::DEFAULT_HISTORY`].
    // spec: HOOK-164
    #[serde(
        rename = "hook-history",
        alias = "hook_history",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub hook_history: Option<usize>,

    /// Save each hook's output to a log file (HOOK-165): `true` for
    /// `~/.mind/hooks/logs`, a path (relative to `~/.mind`) for a directory of
    /// your own, `false` (or absent) for no logs. The `--hook-log` flag outranks it.
    // spec: HOOK-165
    #[serde(
        rename = "hook-log",
        alias = "hook_log",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub hook_log: Option<HookLogSetting>,

    /// Which hook logs to keep (HOOK-170): `all` (the default) or `failed`.
    /// Applies only when logging is on; the `--hook-log-keep` flag outranks it.
    // spec: HOOK-170
    #[serde(
        rename = "hook-log-keep",
        alias = "hook_log_keep",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub hook_log_keep: Option<crate::hook_log::LogKeep>,
}

/// The `hook-log` config value (HOOK-165): on/off, or a directory.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(untagged)]
pub enum HookLogSetting {
    Enabled(bool),
    Dir(String),
}

// By hand rather than `untagged`, so a wrong type names what the key takes
// instead of serde's "did not match any variant".
impl<'de> Deserialize<'de> for HookLogSetting {
    fn deserialize<D: Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
        struct V;
        impl Visitor<'_> for V {
            type Value = HookLogSetting;
            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                f.write_str("true, false, or a directory path")
            }
            fn visit_bool<E: de::Error>(self, b: bool) -> std::result::Result<Self::Value, E> {
                Ok(HookLogSetting::Enabled(b))
            }
            fn visit_str<E: de::Error>(self, s: &str) -> std::result::Result<Self::Value, E> {
                Ok(HookLogSetting::Dir(s.to_string()))
            }
        }
        d.deserialize_any(V)
    }
}

/// The environment variable that sets the metadata cap (DSC-104), between the
/// `--max-metadata-size` flag and the config key in precedence.
pub const MAX_METADATA_SIZE_ENV: &str = "MIND_MAX_METADATA_SIZE";

/// Resolve the metadata size cap from its three origins, highest precedence
/// first: the `--max-metadata-size` flag, `MIND_MAX_METADATA_SIZE`, then the
/// `max-metadata-size` config key. `None` everywhere yields the
/// [`METADATA_SIZE_LIMIT`] default (DSC-104).
///
/// Pure in its three inputs so the precedence is testable without a process
/// environment shared by every other test in the binary; `main::run` gathers
/// them. A value that is present but unparseable is a hard error naming its
/// origin, never a silent fallback to the next one down: an operator who typed
/// a cap and got the default instead would have no way to tell (DSC-105).
///
/// Startup uses [`resolve_metadata_limit_detail`], which also names the
/// origin; this value-only form remains for the precedence tests.
#[cfg(test)]
pub fn resolve_metadata_limit(
    flag: Option<&str>,
    env: Option<&str>,
    configured: Option<&str>,
) -> Result<u64> {
    resolve_metadata_limit_detail(flag, env, configured).map(|(limit, _)| limit)
}

/// Which of the three origins supplied the metadata cap in force, carrying the
/// raw value as written (DSC-104). `Default` means none of them did.
///
/// Recorded once at startup (`main::run`, beside
/// [`crate::error::set_metadata_size_limit`]) so `config show` can say where
/// its effective value came from without re-reading the environment and
/// guessing (CLI-241).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MetadataLimitOrigin {
    /// This run's `--max-metadata-size`.
    Flag(String),
    /// `MIND_MAX_METADATA_SIZE`.
    Env(String),
    /// The `max-metadata-size` config key.
    Config(String),
    /// Nothing was set: the built-in default.
    Default,
}

impl MetadataLimitOrigin {
    /// The name an operator knows this origin by, for messages.
    pub fn label(&self) -> &'static str {
        match self {
            MetadataLimitOrigin::Flag(_) => "--max-metadata-size",
            MetadataLimitOrigin::Env(_) => MAX_METADATA_SIZE_ENV,
            MetadataLimitOrigin::Config(_) => "the 'max-metadata-size' config key",
            MetadataLimitOrigin::Default => "the built-in default",
        }
    }

    /// The raw value as written, `None` for the default.
    pub fn raw(&self) -> Option<&str> {
        match self {
            MetadataLimitOrigin::Flag(raw)
            | MetadataLimitOrigin::Env(raw)
            | MetadataLimitOrigin::Config(raw) => Some(raw),
            MetadataLimitOrigin::Default => None,
        }
    }
}

/// Resolve the metadata size cap from its three origins (flag, then
/// `MIND_MAX_METADATA_SIZE`, then the config key; the default when none is
/// set, DSC-104) and report which origin supplied it. A present but
/// unparseable value is a hard error naming its origin, never a fallback to
/// the next one down (DSC-105).
pub fn resolve_metadata_limit_detail(
    flag: Option<&str>,
    env: Option<&str>,
    configured: Option<&str>,
) -> Result<(u64, MetadataLimitOrigin)> {
    let origin = match (flag, env, configured) {
        (Some(raw), _, _) => MetadataLimitOrigin::Flag(raw.to_string()),
        (None, Some(raw), _) => MetadataLimitOrigin::Env(raw.to_string()),
        (None, None, Some(raw)) => MetadataLimitOrigin::Config(raw.to_string()),
        (None, None, None) => {
            return Ok((
                crate::error::METADATA_SIZE_LIMIT,
                MetadataLimitOrigin::Default,
            ));
        }
    };
    let raw = origin.raw().unwrap_or_default();
    let limit =
        crate::error::parse_metadata_size(raw).map_err(|msg| MindError::BadMetadataSize {
            origin: origin.label().to_string(),
            msg,
        })?;
    Ok((limit, origin))
}

static METADATA_LIMIT_ORIGIN: std::sync::OnceLock<MetadataLimitOrigin> = std::sync::OnceLock::new();

/// Record where this run's metadata cap came from. First call wins; `main::run`
/// makes the only one.
pub fn set_metadata_limit_origin(origin: MetadataLimitOrigin) {
    let _ = METADATA_LIMIT_ORIGIN.set(origin);
}

/// Where this run's metadata cap came from, or `None` when startup never
/// recorded it (unit tests, and the verbs that skip the cap, DSC-113).
pub fn metadata_limit_origin() -> Option<&'static MetadataLimitOrigin> {
    METADATA_LIMIT_ORIGIN.get()
}

/// Whether `raw` is a zero-valued size (`0`, `0MiB`, ...) that turns the
/// metadata cap off (DSC-110), as opposed to the words `unlimited`/`none`,
/// which say so on purpose. A zero is the likelier typo for "a small cap", so
/// startup warns about it; the words stay silent.
pub fn zero_turns_cap_off(raw: &str) -> bool {
    if crate::error::parse_metadata_size(raw) != Ok(u64::MAX) {
        return false;
    }
    let cleaned: String = raw
        .chars()
        .filter(|c| !c.is_whitespace())
        .collect::<String>()
        .to_ascii_lowercase();
    if matches!(cleaned.as_str(), "unlimited" | "none") {
        return false;
    }
    // Only a zero count reaches u64::MAX through a number: a literal byte count
    // of u64::MAX is a real (if absurd) ceiling, not the zero spelling.
    let digits: &str = cleaned
        .split(|c: char| !c.is_ascii_digit())
        .next()
        .unwrap_or_default();
    !digits.is_empty() && digits.chars().all(|c| c == '0')
}

impl Config {
    /// Load `config.toml` from the mind home, returning defaults if absent.
    pub fn load(paths: &Paths) -> Result<Config> {
        let file = paths.config_file();
        match std::fs::read_to_string(&file) {
            Ok(text) => toml::from_str(&text).map_err(|e| MindError::ConfigToml {
                path: file.clone(),
                msg: e.to_string(),
            }),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Config::default()),
            Err(e) => Err(MindError::io(&file, e)),
        }
    }

    /// Write the config back to `config.toml`, creating the mind home if needed.
    pub fn save(&self, paths: &Paths) -> Result<()> {
        std::fs::create_dir_all(&paths.mind_home)
            .map_err(|e| MindError::io(&paths.mind_home, e))?;
        let file = paths.config_file();
        let text = toml::to_string(self).map_err(|e| MindError::TomlWrite {
            path: file.clone(),
            source: e,
        })?;
        Paths::atomic_write(&file, text.as_bytes())
    }
}

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

    /// A bare-string lobe entry parses to a no-kinds lobe (backward compat for an
    /// existing `lobes = ["~/.claude"]` config).
    // spec: HARN-1
    #[test]
    fn bare_string_lobe_parses_as_all_kinds() {
        let cfg: Config = toml::from_str("lobes = [\"~/.claude\"]\n").unwrap();
        assert_eq!(cfg.lobes.len(), 1);
        assert_eq!(cfg.lobes[0].path(), "~/.claude");
        assert_eq!(cfg.lobes[0].kinds(), None, "bare entry admits all kinds");
    }

    /// The flag beats the environment, which beats the config key, and none of
    /// the three yields the default.
    // spec: DSC-104
    #[test]
    fn metadata_limit_precedence_is_flag_then_env_then_config() {
        let mib = 1024 * 1024;
        assert_eq!(
            resolve_metadata_limit(Some("1MiB"), Some("2MiB"), Some("3MiB")).unwrap(),
            mib
        );
        assert_eq!(
            resolve_metadata_limit(None, Some("2MiB"), Some("3MiB")).unwrap(),
            2 * mib
        );
        assert_eq!(
            resolve_metadata_limit(None, None, Some("3MiB")).unwrap(),
            3 * mib
        );
        assert_eq!(
            resolve_metadata_limit(None, None, None).unwrap(),
            crate::error::METADATA_SIZE_LIMIT
        );
    }

    /// The detail form reports the origin that won, carrying its raw value, so
    /// `config show` can credit it without re-reading the environment.
    // spec: DSC-104 CLI-241
    #[test]
    fn metadata_limit_detail_reports_the_winning_origin() {
        let mib = 1024 * 1024;
        assert_eq!(
            resolve_metadata_limit_detail(Some("1MiB"), Some("2MiB"), Some("3MiB")).unwrap(),
            (mib, MetadataLimitOrigin::Flag("1MiB".into()))
        );
        assert_eq!(
            resolve_metadata_limit_detail(None, Some("2MiB"), Some("3MiB")).unwrap(),
            (2 * mib, MetadataLimitOrigin::Env("2MiB".into()))
        );
        assert_eq!(
            resolve_metadata_limit_detail(None, None, Some("3MiB")).unwrap(),
            (3 * mib, MetadataLimitOrigin::Config("3MiB".into()))
        );
        assert_eq!(
            resolve_metadata_limit_detail(None, None, None).unwrap(),
            (
                crate::error::METADATA_SIZE_LIMIT,
                MetadataLimitOrigin::Default
            )
        );
        let err = resolve_metadata_limit_detail(None, Some("nope"), None).unwrap_err();
        assert!(err.to_string().contains(MAX_METADATA_SIZE_ENV), "{err}");
    }

    /// Every zero-valued spelling is flagged as turning the cap off by
    /// accident; the words that say so on purpose, a real size, and a literal
    /// u64::MAX byte count are not.
    // spec: DSC-110
    #[test]
    fn zero_turns_cap_off_matches_only_zero_spellings() {
        for raw in ["0", "0MiB", " 0 kb ", "000", "0b"] {
            assert!(zero_turns_cap_off(raw), "{raw:?} is a zero spelling");
        }
        for raw in [
            "unlimited",
            "NONE",
            " Unlimited ",
            "8MiB",
            "1",
            "18446744073709551615",
            "junk",
            "",
        ] {
            assert!(!zero_turns_cap_off(raw), "{raw:?} is not a zero spelling");
        }
    }

    /// A bad value fails, naming its own origin, and a valid lower-precedence
    /// value does not rescue it: a typo that silently fell through to the
    /// default would leave the operator no way to see the cap was not applied.
    // spec: DSC-105
    #[test]
    fn a_bad_metadata_limit_fails_naming_where_it_came_from() {
        for (flag, env, cfg, origin) in [
            (
                Some("1.5MiB"),
                Some("2MiB"),
                Some("3MiB"),
                "--max-metadata-size",
            ),
            (None, Some("nope"), Some("3MiB"), MAX_METADATA_SIZE_ENV),
            (None, None, Some("huge"), "max-metadata-size"),
        ] {
            let err = resolve_metadata_limit(flag, env, cfg)
                .expect_err("an unparseable value must be a hard error");
            assert_eq!(err.kind(), "bad-metadata-size");
            let msg = err.to_string();
            assert!(
                msg.contains(origin),
                "message must name the origin '{origin}': {msg}"
            );
            assert!(
                msg.contains("unlimited") && msg.contains("32MiB"),
                "message must show the accepted forms: {msg}"
            );
        }
    }

    /// The config key accepts both its canonical kebab-case spelling and the
    /// snake_case alias, like `absorb-to`.
    // spec: DSC-103
    #[test]
    fn max_metadata_size_parses_under_both_spellings() {
        let kebab: Config = toml::from_str("max-metadata-size = \"32MiB\"\n").unwrap();
        assert_eq!(kebab.max_metadata_size.as_deref(), Some("32MiB"));
        let snake: Config = toml::from_str("max_metadata_size = \"32MiB\"\n").unwrap();
        assert_eq!(snake.max_metadata_size.as_deref(), Some("32MiB"));
        let absent: Config = toml::from_str("ssh = true\n").unwrap();
        assert_eq!(absent.max_metadata_size, None);
    }

    /// A table lobe entry parses its path and `kinds` filter.
    // spec: HARN-1
    #[test]
    fn table_lobe_parses_kinds() {
        let cfg: Config =
            toml::from_str("lobes = [{ path = \"~/.gemini\", kinds = [\"skill\", \"agent\"] }]\n")
                .unwrap();
        assert_eq!(cfg.lobes.len(), 1);
        assert_eq!(cfg.lobes[0].path(), "~/.gemini");
        assert_eq!(
            cfg.lobes[0].kinds(),
            Some([ItemKind::Skill, ItemKind::Agent].as_slice())
        );
    }

    /// A no-kinds lobe round-trips back to a bare string (so an existing config is
    /// rewritten unchanged), while a filtered lobe round-trips to a table.
    // spec: HARN-1
    #[test]
    fn lobe_entries_round_trip_by_shape() {
        let cfg = Config {
            lobes: vec![
                LobeEntry::bare("~/.claude"),
                LobeEntry {
                    path: "~/.gemini".to_string(),
                    kinds: Some(vec![ItemKind::Skill, ItemKind::Agent]),
                },
            ],
            ..Default::default()
        };
        let text = toml::to_string(&cfg).unwrap();
        // The bare entry serializes as a plain string, not a table.
        assert!(
            text.contains("\"~/.claude\""),
            "bare lobe must serialize as a string: {text}"
        );
        assert!(
            text.contains("kinds"),
            "filtered lobe must serialize with its kinds: {text}"
        );

        // And it parses back to the same value.
        let reparsed: Config = toml::from_str(&text).unwrap();
        assert_eq!(reparsed.lobes, cfg.lobes);
        assert_eq!(reparsed.lobes[0].kinds(), None);
        assert_eq!(
            reparsed.lobes[1].kinds(),
            Some([ItemKind::Skill, ItemKind::Agent].as_slice())
        );
    }

    /// An unknown key inside a lobe table is rejected (deny_unknown_fields on the
    /// table variant).
    // spec: HARN-1
    #[test]
    fn table_lobe_rejects_unknown_key() {
        let err = toml::from_str::<Config>(
            "lobes = [{ path = \"~/.gemini\", kinds = [\"skill\"], bogus = true }]\n",
        )
        .unwrap_err();
        assert!(
            err.to_string().contains("bogus") || err.to_string().contains("unknown"),
            "unknown table key must be rejected: {err}"
        );
    }

    /// An invalid kind string in a lobe table is rejected.
    // spec: HARN-1
    #[test]
    fn table_lobe_rejects_invalid_kind() {
        let err = toml::from_str::<Config>("lobes = [{ path = \"~/.x\", kinds = [\"wizard\"] }]\n")
            .unwrap_err();
        assert!(
            err.to_string().contains("wizard") || err.to_string().contains("valid item kind"),
            "invalid kind must be rejected: {err}"
        );
    }

    /// A malformed `config.toml` produces `MindError::ConfigToml`, not
    /// `MindError::Toml`. The display must mention "config" (not "mind.toml")
    /// so the user looks at the right file.
    #[test]
    fn malformed_config_toml_yields_config_toml_variant() {
        use crate::paths::Paths;
        use std::path::PathBuf;

        let tmp = std::env::temp_dir().join(format!("mind-config-test-{}", std::process::id()));
        std::fs::create_dir_all(&tmp).unwrap();
        let config_path = tmp.join("config.toml");
        std::fs::write(&config_path, b"[[[not valid toml").unwrap();

        let paths = Paths {
            mind_home: tmp.clone(),
            claude_home: PathBuf::from("/tmp/claude-unused"),
        };

        let err = Config::load(&paths).unwrap_err();

        // Must be the ConfigToml variant, not Toml.
        assert!(
            matches!(err, MindError::ConfigToml { .. }),
            "expected ConfigToml, got: {err:?}"
        );

        // The display must say "config" and must not say "mind.toml".
        let msg = err.to_string();
        assert!(
            msg.contains("config"),
            "display must mention 'config': {msg}"
        );
        assert!(
            !msg.contains("mind.toml"),
            "display must not name the wrong file 'mind.toml': {msg}"
        );

        std::fs::remove_dir_all(&tmp).ok();
    }

    /// A `config.toml` with an unknown top-level key (rejected by
    /// `deny_unknown_fields`) also produces `MindError::ConfigToml`.
    #[test]
    fn unknown_key_in_config_toml_yields_config_toml_variant() {
        use crate::paths::Paths;
        use std::path::PathBuf;

        let tmp = std::env::temp_dir().join(format!("mind-config-test-uk-{}", std::process::id()));
        std::fs::create_dir_all(&tmp).unwrap();
        let config_path = tmp.join("config.toml");
        std::fs::write(&config_path, b"no_such_field = true\n").unwrap();

        let paths = Paths {
            mind_home: tmp.clone(),
            claude_home: PathBuf::from("/tmp/claude-unused"),
        };

        let err = Config::load(&paths).unwrap_err();

        assert!(
            matches!(err, MindError::ConfigToml { .. }),
            "expected ConfigToml for unknown key, got: {err:?}"
        );

        let msg = err.to_string();
        assert!(
            msg.contains("config"),
            "display must mention 'config': {msg}"
        );
        assert!(
            !msg.contains("mind.toml"),
            "display must not name the wrong file: {msg}"
        );

        std::fs::remove_dir_all(&tmp).ok();
    }

    /// `hook-log` takes a bool or a path; anything else is an error that
    /// names what it takes.
    #[test]
    fn hook_log_takes_a_bool_or_a_path() {
        // spec: HOOK-165
        let cfg: Config = toml::from_str("hook-log = true\n").unwrap();
        assert_eq!(cfg.hook_log, Some(HookLogSetting::Enabled(true)));
        let cfg: Config = toml::from_str("hook-log = \"logs\"\n").unwrap();
        assert_eq!(cfg.hook_log, Some(HookLogSetting::Dir("logs".into())));
        let err = toml::from_str::<Config>("hook-log = 1\n").unwrap_err();
        assert!(
            err.to_string().contains("true, false, or a directory path"),
            "{err}"
        );
    }

    /// The canonical `absorb-to` (kebab-case) key is accepted in config.toml.
    // spec: CLI-171
    #[test]
    fn absorb_to_kebab_key_is_accepted() {
        let cfg: Config = toml::from_str("\"absorb-to\" = \"/some/path\"\n").unwrap();
        assert_eq!(cfg.absorb_to.as_deref(), Some("/some/path"));
    }

    /// The legacy `absorb_to` (snake_case) key is still accepted as an alias.
    // spec: CLI-171
    #[test]
    fn absorb_to_snake_key_is_alias() {
        let cfg: Config = toml::from_str("absorb_to = \"/legacy/path\"\n").unwrap();
        assert_eq!(cfg.absorb_to.as_deref(), Some("/legacy/path"));
    }

    /// Serializing a config with `absorb_to` set emits the kebab-case key.
    // spec: CLI-171
    #[test]
    fn absorb_to_serializes_as_kebab() {
        let cfg = Config {
            absorb_to: Some("/out/path".to_string()),
            ..Config::default()
        };
        let s = toml::to_string(&cfg).unwrap();
        assert!(
            s.contains("absorb-to"),
            "serialized config must use kebab key: {s}"
        );
        assert!(
            !s.contains("absorb_to"),
            "serialized config must not use snake key: {s}"
        );
    }
}