ikigai-embedded 0.1.43

In-process transport: composes a kernel directly in the host process.
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
//! Host configuration, read from `$XDG_CONFIG_HOME/ikigai/config.toml` (falling back to
//! `~/.config/ikigai/config.toml`).
//!
//! The one place the daemon and the CLI both read — so they cannot diverge the way a shell
//! env var and a launchd plist just did (the mail `from` that was set for one process and not
//! the other). A minimal `key = "value"` scanner; dotted keys like `mail.from` are ordinary
//! keys to it. It grows a real TOML parser if and when the config outgrows a flat map.
//!
//! Deliberately in the CONFIG dir, NOT `file_root()`: `IKIGAI_FILES` repoints the workspace
//! *data* dir, but a *setting* like the mail sender shouldn't move with it. This is the shared
//! ikigai config home — `grants.json` already lives beside it, and the CLI's own settings
//! (keybindings) read the same `config.toml`.
//!
//! Settings that already had environment variables keep them as an override — the file is the
//! home, the env is an escape hatch for CI and containers. `email_config`
//! reads `mail.from` / `mail.host` / `mail.port` this way.

use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;

/// The config home a `--config-home` FLAG named for this process, if one did. Set once, by the
/// binary, before anything reads the config home; see [`set_config_home`].
static FLAG_HOME: OnceLock<PathBuf> = OnceLock::new();

/// Name this process's config home outright, as the `--config-home` flag does (ledger #919):
/// from here on [`config_home`], [`config_path`] and every file under them resolve inside
/// `dir`, and `XDG_CONFIG_HOME` and `HOME` are not consulted for it. **An explicit flag wins
/// over the environment** — the rule is config home plus flags, so the flag is the channel and
/// the environment the fallback, never the other way round.
///
/// `dir` IS the config home (it holds `config.toml`, `grants.json`, …), not an XDG base with an
/// `ikigai/` beneath it: gonk's `--config-home` means the same. It must be ABSOLUTE — the
/// binary absolutizes what was typed — because a relative config home is one that moves with
/// the working directory, which `config_home` exists to refuse. Setting it twice to the same
/// directory is a no-op; to a different one is refused, since a process has one config home.
///
/// `ikigai_engine::config::set_config_home` is this function's TWIN (the engine reads the same
/// `config.toml` and depends on nothing here); the binary sets both.
pub fn set_config_home(dir: PathBuf) -> Result<(), String> {
    if !dir.is_absolute() {
        return Err(format!(
            "the config home must be an absolute path, and `{}` is not",
            dir.display()
        ));
    }
    match FLAG_HOME.get() {
        Some(prior) if *prior == dir => Ok(()),
        Some(prior) => Err(format!(
            "the config home is already `{}`; a process has one",
            prior.display()
        )),
        None => FLAG_HOME
            .set(dir)
            .map_err(|_| "the config home was set concurrently".into()),
    }
}

/// The config home a `--config-home` flag named, if any — for a caller that must hand a home
/// to a module that would otherwise read the environment itself (the durable store's
/// `store.toml`, browse's `a11y.toml` layers).
pub fn config_home_flag() -> Option<&'static Path> {
    FLAG_HOME.get().map(PathBuf::as_path)
}

/// The ikigai config home: the `--config-home` flag's directory when one was given
/// ([`set_config_home`]), else `$XDG_CONFIG_HOME/ikigai`, or `$HOME/.config/ikigai` when
/// `XDG_CONFIG_HOME` is unset. `None` when none of the three is known.
///
/// THE spelling of the config home — every file the host reads from it resolves through
/// here. It used to be written twice: this module honoured `XDG_CONFIG_HOME` while nine
/// other call sites joined `$HOME/.config/ikigai` directly. The two AGREE in the default
/// case, which is precisely why the divergence survived: it appears only on a machine that
/// sets the variable, and there it split the config home in half — `grants.json`,
/// `clients.json`, `calendar.json`, `llm.json` and the code-signers directory read from
/// `$HOME` while `config.toml` read from `$XDG_CONFIG_HOME`. The QUIC certificate directory
/// managed to disagree with *itself*: `ikigai-cli`'s `quic::dir` resolved it through the
/// XDG-honouring spelling and `peer_cert_dir` through the other, so `holds_cert_for` could
/// report no certificate for a peer whose certificate had just been written.
///
/// `ikigai_engine::config::path` is a deliberate TWIN of this rule, not a third spelling:
/// neither crate depends on the other, so one shared function would have to be pushed down
/// into `ikigai-core`. Keep the two in step.
pub fn config_home() -> Option<PathBuf> {
    if let Some(flag) = config_home_flag() {
        return Some(flag.to_path_buf());
    }
    config_home_from(
        std::env::var_os("XDG_CONFIG_HOME"),
        std::env::var_os("HOME"),
    )
}

/// [`config_home`] with the environment passed in, so the resolution rule is testable
/// without `set_var`: the environment is process-global, and mutating it races the test
/// harness's own threads.
///
/// A set-but-EMPTY `XDG_CONFIG_HOME` counts as unset, per the XDG base directory spec. The
/// old spellings took it literally and resolved a relative `ikigai/…` against the working
/// directory — a config home that moved with `cd`.
fn config_home_from(xdg: Option<OsString>, home: Option<OsString>) -> Option<PathBuf> {
    xdg.filter(|value| !value.is_empty())
        .map(PathBuf::from)
        .or_else(|| home.map(|home| PathBuf::from(home).join(".config")))
        .map(|base| base.join("ikigai"))
}

/// `$XDG_CONFIG_HOME/ikigai/config.toml`, or `~/.config/ikigai/config.toml` when
/// `XDG_CONFIG_HOME` is unset. Independent of `IKIGAI_FILES` (see the module note).
///
/// Falls back to a RELATIVE `./.config/ikigai/config.toml` where [`config_home`] gives up:
/// a process with no `HOME` still reads *a* file. The JSON siblings return `None` instead —
/// each caller keeps the failure semantics it already had, only the directory is unified.
pub fn config_path() -> PathBuf {
    config_home()
        .unwrap_or_else(|| Path::new(".").join(".config").join("ikigai"))
        .join("config.toml")
}

/// The per-peer certificate directory `<config home>/quic-<name>/` (plasma holds
/// `quic-bug`, bug holds `quic-plasma`), or `None` when there is no config home or `name`
/// cannot name one directory. See [`peer_cert_dir_in`].
pub fn peer_cert_dir(name: &str) -> Option<PathBuf> {
    peer_cert_dir_in(&config_home()?, name)
}

/// `<home>/quic-<name>/`, or `None` when `name` is not a single path segment.
///
/// THE spelling of the per-peer directory: the peer listing's "do I hold a pinned
/// certificate?" oracle and the CLI's `peer:<name>` dialer both resolve through here, so
/// they cannot disagree about where a peer's certificate lives.
///
/// ⚠ `name` is usually what the LAN ANNOUNCED over mDNS, and a DNS-SD instance name may
/// carry any byte. Joined raw, `plasma/../quic-plasma` resolved to the real `quic-plasma`
/// directory, so a stranger's announcement was listed as trusted with `ik:pinnedHere true`
/// (ledger #741). A name with a path separator (`/` or `\`), a NUL, or nothing at all
/// names no directory; it is refused here, before any path is built, rather than
/// normalized, because a normalized name would be a DIFFERENT peer's name.
///
/// ```
/// use std::path::{Path, PathBuf};
/// use ikigai_embedded::config::peer_cert_dir_in;
///
/// let home = Path::new("/home/b/.config/ikigai");
/// assert_eq!(peer_cert_dir_in(home, "plasma"), Some(PathBuf::from("/home/b/.config/ikigai/quic-plasma")));
/// assert_eq!(peer_cert_dir_in(home, "plasma/../quic-bug"), None);
/// assert_eq!(peer_cert_dir_in(home, ""), None);
/// ```
pub fn peer_cert_dir_in(home: &Path, name: &str) -> Option<PathBuf> {
    is_single_segment(name).then(|| home.join(format!("quic-{name}")))
}

/// Whether `name` stays ONE directory entry once prefixed with `quic-`. Separators of
/// either platform are refused on every platform: a name that is one segment on macOS
/// and three on Windows is not a name to build a path from. `.` and `..` need no case of
/// their own, because the `quic-` prefix makes them ordinary entries.
fn is_single_segment(name: &str) -> bool {
    !name.is_empty() && !name.contains(['/', '\\', '\0'])
}

/// The value of `key` in the host config, or `None` if the file or the key is absent.
pub fn get(key: &str) -> Option<String> {
    value_for(&std::fs::read_to_string(config_path()).ok()?, key)
}

/// Every value for `key`, in file order — for settings that legitimately repeat.
///
/// A machine's TOPOLOGY is the motivating case: it has as many mounts as it has peers, and
/// they belong in the config home rather than in a launchd plist, so `git pull` cannot
/// overwrite one machine's identity with another's.
pub fn all(key: &str) -> Vec<String> {
    std::fs::read_to_string(config_path())
        .map(|text| values_for(&text, key))
        .unwrap_or_default()
}

/// Every `key = value` line whose key begins with `prefix`, in file order, as
/// `(key, value)` — for a family of settings that is validated as a whole, so a misspelled
/// key is reported rather than silently ignored (the `lisp.*` bounds read it).
pub fn entries_under(prefix: &str) -> Vec<(String, String)> {
    std::fs::read_to_string(config_path())
        .map(|text| entries_under_in(&text, prefix))
        .unwrap_or_default()
}

/// The `(key, value)` lines of `text` whose key begins with `prefix`. See [`value_for`] for
/// the parsing rules.
pub(crate) fn entries_under_in(text: &str, prefix: &str) -> Vec<(String, String)> {
    text.lines()
        .map(str::trim)
        .filter(|line| !line.is_empty() && !line.starts_with('#'))
        .filter_map(|line| line.split_once('='))
        .filter(|(name, _)| name.trim().starts_with(prefix))
        .map(|(name, value)| {
            (
                name.trim().to_string(),
                value.trim().trim_matches(['"', '\'']).trim().to_string(),
            )
        })
        .collect()
}

/// The instance names that SCOPE `key` in the file — the `<instance>` of every
/// `<instance>.<key> = …` line, in file order, deduped.
///
/// Instance-scoped properties (`serve.derive_every`, `serve.browse.root`) attach behavior to a
/// NAMED process instead of to every process reading the shared config. A reader that falls
/// back from `<instance>.<key>` to plain `<key>` needs to know whether ANYONE scopes the key:
/// for a resource only one process may hold (the browse store), a scoped line for instance A
/// plus an unscoped line that instance B still honours re-creates exactly the collision the
/// scoping exists to prevent.
pub fn scoping_instances(key: &str) -> Vec<String> {
    std::fs::read_to_string(config_path())
        .map(|text| scoping_instances_in(&text, key))
        .unwrap_or_default()
}

/// The `<instance>` prefixes of every `<instance>.<key>` line in `text`. See
/// [`scoping_instances`].
fn scoping_instances_in(text: &str, key: &str) -> Vec<String> {
    let suffix = format!(".{key}");
    let mut instances: Vec<String> = Vec::new();
    for line in text.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        if let Some((name, _)) = line.split_once('=') {
            if let Some(instance) = name.trim().strip_suffix(&suffix) {
                if !instance.is_empty() && !instances.iter().any(|i| i == instance) {
                    instances.push(instance.to_string());
                }
            }
        }
    }
    instances
}

/// Every `key = value` line for `key`. See [`value_for`] for the parsing rules.
fn values_for(text: &str, key: &str) -> Vec<String> {
    text.lines()
        .map(str::trim)
        .filter(|line| !line.is_empty() && !line.starts_with('#'))
        .filter_map(|line| line.split_once('='))
        .filter(|(name, _)| name.trim() == key)
        .map(|(_, value)| value.trim().trim_matches(['"', '\'']).trim().to_string())
        .collect()
}

/// The first `key = value` line for `key`, trimmed and unquoted. Blank lines and `#` comments
/// are skipped. Not a full TOML parser — the flat `key = "value"` shape the config uses today.
fn value_for(text: &str, key: &str) -> Option<String> {
    for line in text.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        if let Some((name, value)) = line.split_once('=') {
            if name.trim() == key {
                return Some(value.trim().trim_matches(['"', '\'']).trim().to_string());
            }
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::{
        config_home, config_home_from, config_path, peer_cert_dir_in, scoping_instances_in,
        value_for, values_for,
    };
    use std::ffi::OsString;
    use std::path::{Path, PathBuf};

    /// `XDG_CONFIG_HOME` decides the config home when it is set. The second spelling this
    /// replaced ignored it, and the two agreed everywhere except on the machines that set
    /// it — a divergence the default case cannot show.
    #[test]
    fn xdg_config_home_decides_the_config_home_when_set() {
        assert_eq!(
            config_home_from(Some("/xdg".into()), Some("/home/b".into())),
            Some(PathBuf::from("/xdg/ikigai"))
        );
        // With no HOME to fall back to, XDG alone still resolves.
        assert_eq!(
            config_home_from(Some("/xdg".into()), None),
            Some(PathBuf::from("/xdg/ikigai"))
        );
    }

    /// Unset — and set-but-empty, which the spec says to read as unset — fall back to
    /// `$HOME/.config`. Empty used to resolve a RELATIVE `ikigai/…`, a config home that
    /// moved with the working directory.
    #[test]
    fn an_unset_or_empty_xdg_falls_back_to_home_config() {
        assert_eq!(
            config_home_from(None, Some("/home/b".into())),
            Some(PathBuf::from("/home/b/.config/ikigai"))
        );
        assert_eq!(
            config_home_from(Some(OsString::new()), Some("/home/b".into())),
            Some(PathBuf::from("/home/b/.config/ikigai"))
        );
    }

    /// Neither base directory known: `None`, so each caller applies its OWN fallback
    /// rather than inheriting one it did not choose.
    #[test]
    fn no_base_directory_at_all_is_none() {
        assert_eq!(config_home_from(None, None), None);
        assert_eq!(
            config_path(),
            config_home()
                .unwrap_or_else(|| Path::new(".").join(".config").join("ikigai"))
                .join("config.toml")
        );
    }

    /// The invariant that actually broke: `config.toml`, `grants.json` and `clients.json`
    /// are SIBLINGS in one directory. Whatever the ambient environment resolves to, a
    /// served kernel must not read its grants from one config home and its settings from
    /// another.
    #[test]
    fn the_config_home_files_are_siblings() {
        // An explicit override relocates its file BY DESIGN — the escape hatch for CI and
        // containers is not a divergence.
        if std::env::var_os("IKIGAI_GRANTS").is_some()
            || std::env::var_os("IKIGAI_CLIENTS").is_some()
        {
            return;
        }
        let Some(home) = config_home() else {
            return; // no HOME and no XDG_CONFIG_HOME: nothing to be a sibling of.
        };
        let grants = crate::grants_path();
        let clients = crate::clients::clients_path();
        assert_eq!(config_path().parent(), Some(home.as_path()));
        assert_eq!(
            grants.as_deref().and_then(Path::parent),
            Some(home.as_path())
        );
        assert_eq!(
            clients.as_deref().and_then(Path::parent),
            Some(home.as_path())
        );
    }

    /// `serve.browse.root` scopes `browse.root` to the "serve" instance; the plain key, a
    /// commented line, and an unrelated dotted key must not read as scoping instances.
    #[test]
    fn scoped_spellings_surface_their_instances() {
        let text = "browse.root = \"~/a\"\n\
                    serve.browse.root = \"~/b\"\n\
                    serve.browse.root = \"~/c\"\n\
                    daemon.browse.root = \"~/d\"\n\
                    # repl.browse.root = \"~/e\"\n\
                    mail.from = \"x@y.example\"\n";
        assert_eq!(
            scoping_instances_in(text, "browse.root"),
            vec!["serve".to_string(), "daemon".to_string()]
        );
        assert!(scoping_instances_in(text, "browse.store").is_empty());
    }

    /// A machine has as many mounts as it has peers, so `mount` must be repeatable — the
    /// single-value reader would silently take the first and drop the rest.
    #[test]
    fn repeated_keys_all_come_back_in_order() {
        let text = "# topology\n\
                    mount = \"prefer urn:llm:=peer:plasma\"\n\
                    other = 1\n\
                    mount = \"alias urn:cal:=quic://bug.local:4433\"\n";
        assert_eq!(
            values_for(text, "mount"),
            vec![
                "prefer urn:llm:=peer:plasma".to_string(),
                "alias urn:cal:=quic://bug.local:4433".to_string()
            ]
        );
        assert!(values_for(text, "absent").is_empty());
    }

    #[test]
    fn reads_a_dotted_key_unquoted() {
        let text = "# host config\n\nmail.from = \"brian@bosatsu.net\"\nmail.port = 587\n";
        assert_eq!(
            value_for(text, "mail.from").as_deref(),
            Some("brian@bosatsu.net")
        );
        assert_eq!(value_for(text, "mail.port").as_deref(), Some("587"));
    }

    #[test]
    fn an_absent_or_commented_key_is_none() {
        assert_eq!(value_for("mail.host = localhost", "mail.from"), None);
        // A commented line is not the key.
        assert_eq!(value_for("# mail.from = x@y.example", "mail.from"), None);
    }

    /// The per-peer directory is one entry under the config home, or nothing (ledger #741):
    /// a name that would add segments is refused, never normalized into another peer's.
    #[test]
    fn a_peer_cert_dir_is_one_segment_or_none() {
        let home = Path::new("/c/ikigai");
        assert_eq!(
            peer_cert_dir_in(home, "plasma"),
            Some(PathBuf::from("/c/ikigai/quic-plasma"))
        );
        // Names an announcement may legitimately carry are kept as they are.
        for ok in ["bug-2", "plasma (2)", "..", ".", "plasma.local"] {
            let dir = peer_cert_dir_in(home, ok).unwrap_or_else(|| panic!("{ok:?} is one segment"));
            assert_eq!(
                dir.parent(),
                Some(home),
                "{ok:?} stays directly under the home"
            );
        }
        for bad in ["", "plasma/../quic-bug", "/etc", "a/b", "a\\b", "a\0b"] {
            assert_eq!(
                peer_cert_dir_in(home, bad),
                None,
                "{bad:?} must name no directory"
            );
        }
    }
}