meerkat-core 0.8.4

Core agent logic for Meerkat (no I/O deps)
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
//! The single path authority for durable storage roots.
//!
//! `StorageLayout` is resolved once at bootstrap and carried through
//! composition; no crate resolves ambient roots on its own (the Phase 5
//! anti-ambient-resolution gate enforces this outside bootstrap/layout
//! modules). The layout owns **roots and canonical top-level locators**;
//! feature crates own *relative* file names beneath them (blob directories,
//! per-realm databases, projection files) — centralizing every path literal
//! would create a storage god-module, which is its own fragmentation.
//!
//! Field semantics (see `docs/plans/storage-unification-plan.md`, Phase 2):
//!
//! - [`invocation_context`](StorageLayout::invocation_context): the exact
//!   working directory / `--context-root`. **Never walked up.** MCP config
//!   discovery keys off this (its no-walk-up rule is a security boundary).
//! - [`project_root`](StorageLayout::project_root): discovered by walking up
//!   from the invocation context looking for `.rkat` (may equal the
//!   invocation context; `None` outside any project).
//! - [`user_home_root`](StorageLayout::user_home_root): the home-like root
//!   today's `user_config_root` parameters map onto (`--user-config-root`
//!   override, else the platform home). Helpers append `.rkat` themselves —
//!   this is deliberately NOT `~/.rkat`, or existing call sites would
//!   produce `~/.rkat/.rkat`.
//! - [`user_rkat_root`](StorageLayout::user_rkat_root): the derived
//!   `<user_home_root>/.rkat` (config.toml, mcp.toml, skills, trust).
//! - [`credentials_root`](StorageLayout::credentials_root): populated by the
//!   composing layer from the auth crate's unchanged convention
//!   (`config_dir/meerkat/credentials`); the layout carries it so tooling
//!   has one place to read, it does not re-derive it.
//! - [`comms_identity_root`](StorageLayout::comms_identity_root): populated
//!   by the composing layer from the session-comms convention. Durable key
//!   material — the resolution is preserved exactly by its owner; the slot
//!   exists so the anti-ambient gate neither exempts it forever nor lets a
//!   port silently relocate (and thereby rotate) identity keys.
//! - [`state_root`](StorageLayout::state_root): the realm data root, chosen
//!   by realm-id-first dual-root resolution
//!   ([`RealmConfig::resolve_locator_dual_root`]).
//! - [`cache_root`](StorageLayout::cache_root): root for rebuildable caches
//!   (skill git cache); populated by the composing layer (the realm scope
//!   root in realm-backed surfaces).

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

use crate::runtime_bootstrap::{
    DualRootResolution, RealmConfig, RealmLocator, RealmRootChoice, RealmRootDefault,
    RuntimeBootstrapError, default_state_root,
};

/// Immutable path authority resolved at bootstrap.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StorageLayout {
    invocation_context: PathBuf,
    project_root: Option<PathBuf>,
    user_home_root: Option<PathBuf>,
    user_rkat_root: Option<PathBuf>,
    credentials_root: Option<PathBuf>,
    comms_identity_root: Option<PathBuf>,
    state_root: PathBuf,
    /// Every state-root candidate resolution probed (chosen root included);
    /// first materialization reserves across all of them.
    realm_root_candidates: Vec<PathBuf>,
    cache_root: Option<PathBuf>,
}

/// Bootstrap inputs for [`StorageLayout::resolve`]. Everything ambient a
/// surface consumes is named here; the resolution itself performs no
/// environment reads beyond what these inputs and the realm-root candidates
/// imply.
#[derive(Debug, Clone, Default)]
pub struct StorageLayoutInputs {
    /// The exact context directory (`--context-root`, else the surface's
    /// invocation directory). Never walked up.
    pub invocation_context: PathBuf,
    /// `--state-root` override; wins over probing when present.
    pub explicit_state_root: Option<PathBuf>,
    /// `--user-config-root` override for the home-like root.
    pub user_config_root: Option<PathBuf>,
    /// The surface's documented default root when the realm exists nowhere.
    pub default_root: Option<RealmRootDefault>,
    /// Whether the project-local candidate (`<project-root>/.rkat/realms`,
    /// where the project root is walked up from the invocation context and
    /// falls back to the context itself outside any project) participates
    /// in probing. The CLI always probes it; server surfaces only when
    /// started with an explicit context root, which keeps their no-flags
    /// behavior unchanged.
    pub probe_local_candidate: bool,
}

/// A layout together with the locator its state root was resolved for.
#[derive(Debug, Clone)]
pub struct ResolvedStorage {
    pub layout: StorageLayout,
    pub locator: RealmLocator,
    /// Provenance of the state root (logged by surfaces, reported by doctor).
    pub root_choice: RealmRootChoice,
}

impl StorageLayout {
    /// Resolve the layout and the realm locator in one step (realm identity
    /// first, then the root — see
    /// [`RealmConfig::resolve_locator_dual_root`]).
    ///
    /// `realm.state_root` (the surface flag) participates as the explicit
    /// root; `inputs.explicit_state_root` is merged into it when the realm
    /// config carries none.
    pub fn resolve(
        inputs: StorageLayoutInputs,
        realm: &RealmConfig,
    ) -> Result<ResolvedStorage, RuntimeBootstrapError> {
        Self::resolve_with_global_candidate(inputs, realm, &default_state_root())
    }

    /// [`Self::resolve`] with an injected user-global candidate root
    /// (testability; production uses [`default_state_root`]).
    pub fn resolve_with_global_candidate(
        inputs: StorageLayoutInputs,
        realm: &RealmConfig,
        global_candidate: &Path,
    ) -> Result<ResolvedStorage, RuntimeBootstrapError> {
        // The invocation context is *where the surface was started*, not
        // necessarily the project root: walk up first, so a nested
        // `--context-root` does not pin project persistence to a
        // subdirectory of the project it lives in. Outside any project the
        // context itself is where a fresh `.rkat` would be created.
        let project_root = find_project_root(&inputs.invocation_context);
        let local_candidate = inputs.probe_local_candidate.then(|| {
            local_realms_candidate(
                project_root
                    .as_deref()
                    .unwrap_or(&inputs.invocation_context),
            )
        });
        let mut realm_config = realm.clone();
        if realm_config.state_root.is_none() {
            realm_config.state_root = inputs.explicit_state_root.clone();
        }
        let default_root = inputs.default_root.unwrap_or(RealmRootDefault::UserGlobal);
        let DualRootResolution {
            locator,
            choice,
            candidate_roots,
        } = realm_config.resolve_locator_dual_root_with(
            local_candidate.as_deref(),
            global_candidate,
            default_root,
        )?;

        let user_home_root = inputs.user_config_root.clone().or_else(dirs::home_dir);
        let user_rkat_root = user_home_root.as_ref().map(|home| home.join(".rkat"));

        let layout = StorageLayout {
            invocation_context: inputs.invocation_context,
            project_root,
            user_home_root,
            user_rkat_root,
            credentials_root: None,
            comms_identity_root: None,
            state_root: locator.state_root.clone(),
            realm_root_candidates: candidate_roots,
            cache_root: None,
        };
        Ok(ResolvedStorage {
            layout,
            locator,
            root_choice: choice,
        })
    }

    /// Injected-roots constructor: no ambient reads at all (tests, embedders
    /// that own their environment).
    pub fn with_injected_roots(
        invocation_context: PathBuf,
        project_root: Option<PathBuf>,
        user_home_root: Option<PathBuf>,
        state_root: PathBuf,
    ) -> Self {
        let user_rkat_root = user_home_root.as_ref().map(|home| home.join(".rkat"));
        Self {
            invocation_context,
            project_root,
            user_home_root,
            user_rkat_root,
            credentials_root: None,
            comms_identity_root: None,
            realm_root_candidates: vec![state_root.clone()],
            state_root,
            cache_root: None,
        }
    }

    /// The exact cwd/`--context-root`; never walked up (MCP trust boundary).
    pub fn invocation_context(&self) -> &Path {
        &self.invocation_context
    }

    /// The walked-up project root (`.rkat` discovery), when inside one.
    pub fn project_root(&self) -> Option<&Path> {
        self.project_root.as_deref()
    }

    /// The home-like root existing `user_config_root` parameters map onto.
    pub fn user_home_root(&self) -> Option<&Path> {
        self.user_home_root.as_deref()
    }

    /// `<user_home_root>/.rkat` (config.toml, mcp.toml, skills, trust).
    pub fn user_rkat_root(&self) -> Option<&Path> {
        self.user_rkat_root.as_deref()
    }

    /// Credentials root (unchanged auth convention), when composed.
    pub fn credentials_root(&self) -> Option<&Path> {
        self.credentials_root.as_deref()
    }

    /// Session-comms identity root (durable key material), when composed.
    pub fn comms_identity_root(&self) -> Option<&Path> {
        self.comms_identity_root.as_deref()
    }

    /// The realm data root.
    pub fn state_root(&self) -> &Path {
        &self.state_root
    }

    /// Every state-root candidate resolution probed, the chosen root
    /// included. First materialization of a realm must reserve across all
    /// of them (the store's cross-candidate first-start reservation) so two
    /// surfaces with different default roots cannot each manufacture a
    /// manifest for the same realm.
    pub fn realm_root_candidates(&self) -> &[PathBuf] {
        &self.realm_root_candidates
    }

    /// Root for rebuildable caches, when composed.
    pub fn cache_root(&self) -> Option<&Path> {
        self.cache_root.as_deref()
    }

    /// The user-global config document (`<user_rkat_root>/config.toml`) —
    /// the reserved `global` realm's config doc.
    pub fn global_config_path(&self) -> Option<PathBuf> {
        self.user_rkat_root.as_ref().map(|r| r.join("config.toml"))
    }

    /// Compose the credentials root (owner: the auth crate's convention).
    #[must_use]
    pub fn with_credentials_root(mut self, root: PathBuf) -> Self {
        self.credentials_root = Some(root);
        self
    }

    /// Compose the comms identity root (owner: the session-comms
    /// convention; resolution preserved exactly by its owner).
    #[must_use]
    pub fn with_comms_identity_root(mut self, root: PathBuf) -> Self {
        self.comms_identity_root = Some(root);
        self
    }

    /// Compose the rebuildable-cache root (realm scope root in realm-backed
    /// surfaces).
    #[must_use]
    pub fn with_cache_root(mut self, root: PathBuf) -> Self {
        self.cache_root = Some(root);
        self
    }
}

/// The project-local realms candidate for a project root:
/// `<root>/.rkat/realms`. Callers pass the walked-up project root (see
/// [`find_project_root`]); the invocation context itself only when outside
/// any project.
pub fn local_realms_candidate(context_root: &Path) -> PathBuf {
    context_root.join(".rkat").join("realms")
}

/// Find the project root by walking up from `start_dir` looking for a
/// `.rkat` entry.
///
/// This is the single canonical copy (previously duplicated in
/// `meerkat-core::config` and `meerkat-tools`, with diverging semantics).
/// It adopts the historically *live* semantic — any existing `.rkat` entry
/// counts, matching the `meerkat-tools` copy every production caller used.
pub fn find_project_root(start_dir: &Path) -> Option<PathBuf> {
    let mut current = start_dir.to_path_buf();
    loop {
        if current.join(".rkat").exists() {
            return Some(current);
        }
        if !current.pop() {
            return None;
        }
    }
}

#[cfg(test)]
#[allow(clippy::expect_used, clippy::panic)]
mod tests {
    use super::*;
    use crate::runtime_bootstrap::RealmSelection;

    #[test]
    fn find_project_root_walks_up_and_accepts_any_rkat_entry() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let project = tmp.path().join("proj");
        let nested = project.join("a/b");
        std::fs::create_dir_all(&nested).expect("mkdir");
        assert_eq!(find_project_root(&nested), None);
        std::fs::create_dir_all(project.join(".rkat")).expect("mkdir .rkat");
        assert_eq!(
            find_project_root(&nested).as_deref(),
            Some(project.as_path())
        );
        // A plain file also counts (the live historical semantic).
        let file_project = tmp.path().join("file-proj");
        std::fs::create_dir_all(&file_project).expect("mkdir");
        std::fs::write(file_project.join(".rkat"), b"marker").expect("write");
        assert_eq!(find_project_root(&file_project), Some(file_project));
    }

    #[test]
    fn resolve_derives_user_rkat_root_from_override() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let home = tmp.path().join("home");
        let inputs = StorageLayoutInputs {
            invocation_context: tmp.path().to_path_buf(),
            explicit_state_root: Some(tmp.path().join("state")),
            user_config_root: Some(home.clone()),
            default_root: Some(RealmRootDefault::ProjectLocal),
            probe_local_candidate: true,
        };
        let realm = RealmConfig {
            selection: RealmSelection::Explicit {
                realm_id: "team".into(),
            },
            ..RealmConfig::default()
        };
        let resolved = StorageLayout::resolve_with_global_candidate(
            inputs,
            &realm,
            &tmp.path().join("global"),
        )
        .expect("resolve");
        assert_eq!(resolved.root_choice, RealmRootChoice::Explicit);
        assert_eq!(resolved.layout.user_home_root(), Some(home.as_path()));
        assert_eq!(
            resolved.layout.user_rkat_root(),
            Some(home.join(".rkat").as_path())
        );
        assert_eq!(
            resolved.layout.global_config_path(),
            Some(home.join(".rkat").join("config.toml"))
        );
        // The user_home_root/user_rkat_root split: no `.rkat/.rkat`.
        assert!(
            !resolved
                .layout
                .global_config_path()
                .expect("path")
                .to_string_lossy()
                .contains(".rkat/.rkat")
        );
    }

    #[test]
    fn cli_shaped_resolution_defaults_to_local_candidate() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let context = tmp.path().join("ws");
        std::fs::create_dir_all(&context).expect("mkdir");
        let inputs = StorageLayoutInputs {
            invocation_context: context.clone(),
            explicit_state_root: None,
            user_config_root: None,
            default_root: Some(RealmRootDefault::ProjectLocal),
            probe_local_candidate: true,
        };
        let realm = RealmConfig {
            selection: RealmSelection::WorkspaceDerived {
                root: context.clone(),
            },
            ..RealmConfig::default()
        };
        let resolved = StorageLayout::resolve_with_global_candidate(
            inputs,
            &realm,
            &tmp.path().join("global"),
        )
        .expect("resolve");
        assert_eq!(resolved.root_choice, RealmRootChoice::Default);
        assert_eq!(
            resolved.layout.state_root(),
            local_realms_candidate(&context).as_path()
        );
        assert!(resolved.locator.realm.as_str().starts_with("ws-"));
    }

    #[test]
    fn nested_invocation_context_resolves_project_root_local_candidate() {
        // A nested `--context-root` (or cwd) inside a project must not pin
        // realm storage to the subdirectory: the local candidate hangs off
        // the walked-up project root.
        let tmp = tempfile::tempdir().expect("tempdir");
        let project = tmp.path().join("proj");
        let nested = project.join("a").join("b");
        std::fs::create_dir_all(&nested).expect("mkdir");
        std::fs::create_dir_all(project.join(".rkat")).expect("mkdir .rkat");
        let inputs = StorageLayoutInputs {
            invocation_context: nested.clone(),
            explicit_state_root: None,
            user_config_root: None,
            default_root: Some(RealmRootDefault::ProjectLocal),
            probe_local_candidate: true,
        };
        let realm = RealmConfig {
            selection: RealmSelection::Explicit {
                realm_id: "team".into(),
            },
            ..RealmConfig::default()
        };
        let resolved = StorageLayout::resolve_with_global_candidate(
            inputs,
            &realm,
            &tmp.path().join("global"),
        )
        .expect("resolve");
        assert_eq!(resolved.layout.project_root(), Some(project.as_path()));
        assert_eq!(resolved.layout.invocation_context(), nested.as_path());
        assert_eq!(
            resolved.layout.state_root(),
            local_realms_candidate(&project).as_path()
        );
        // The probed candidates surface for the first-start reservation.
        assert_eq!(
            resolved.layout.realm_root_candidates(),
            &[local_realms_candidate(&project), tmp.path().join("global")]
        );
    }

    #[test]
    fn injected_roots_carry_a_single_candidate() {
        let layout = StorageLayout::with_injected_roots(
            PathBuf::from("/ctx"),
            None,
            None,
            PathBuf::from("/state"),
        );
        assert_eq!(
            layout.realm_root_candidates(),
            &[PathBuf::from("/state")],
            "injected layouts resolve single-root: no cross-candidate probing happened"
        );
    }

    #[test]
    fn server_shaped_resolution_without_context_never_probes_local() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let cwd = tmp.path().join("cwd");
        // A realm materialized under the cwd-local candidate must NOT be
        // picked up by a server that was not given a context root.
        let local = local_realms_candidate(&cwd);
        std::fs::create_dir_all(local.join("team")).expect("mkdir");
        std::fs::write(
            local
                .join("team")
                .join(crate::runtime_bootstrap::REALM_MANIFEST_FILE_NAME),
            b"{}",
        )
        .expect("manifest");
        let inputs = StorageLayoutInputs {
            invocation_context: cwd,
            explicit_state_root: None,
            user_config_root: None,
            default_root: Some(RealmRootDefault::UserGlobal),
            probe_local_candidate: false,
        };
        let realm = RealmConfig {
            selection: RealmSelection::Explicit {
                realm_id: "team".into(),
            },
            ..RealmConfig::default()
        };
        let global = tmp.path().join("global");
        let resolved =
            StorageLayout::resolve_with_global_candidate(inputs, &realm, &global).expect("resolve");
        assert_eq!(resolved.root_choice, RealmRootChoice::Default);
        assert_eq!(resolved.layout.state_root(), global.as_path());
    }
}