Skip to main content

kanade_shared/
config.rs

1use std::path::{Path, PathBuf};
2
3use anyhow::{Context, Result};
4use serde::Deserialize;
5
6// ─── Agent config ────────────────────────────────────────────────────
7
8#[derive(Deserialize, Debug, Clone)]
9pub struct AgentConfig {
10    pub agent: AgentSection,
11    pub log: LogSection,
12}
13
14#[derive(Deserialize, Debug, Clone)]
15pub struct AgentSection {
16    pub id: String,
17    pub nats_url: String,
18    /// DEPRECATED in Sprint 5: group membership is now server-managed
19    /// via the `agent_groups` KV bucket. Use
20    /// `kanade agent groups set <pc_id> <group> [<group> ...]` to
21    /// declare membership. Still parsed for back-compat; the value
22    /// is logged-and-ignored at startup. Field removal is scheduled
23    /// for v0.4.0.
24    #[serde(default)]
25    pub groups: Vec<String>,
26}
27
28#[derive(Deserialize, Debug, Clone)]
29pub struct LogSection {
30    pub path: String,
31    pub level: String,
32    /// Number of rotated daily files (incl. today's) to retain.
33    /// Defaults to 14 — covers two weeks of incidents without
34    /// blowing up disk. Set to 0 to disable on-disk logging
35    /// (stdout only).
36    #[serde(default = "default_keep_days")]
37    pub keep_days: usize,
38}
39
40fn default_keep_days() -> usize {
41    14
42}
43
44// ─── Backend config ──────────────────────────────────────────────────
45
46#[derive(Deserialize, Debug, Clone)]
47pub struct BackendConfig {
48    pub server: ServerSection,
49    pub nats: NatsSection,
50    pub db: DbSection,
51    pub log: LogSection,
52}
53
54#[derive(Deserialize, Debug, Clone)]
55pub struct ServerSection {
56    pub bind: String,
57}
58
59#[derive(Deserialize, Debug, Clone)]
60pub struct NatsSection {
61    pub url: String,
62}
63
64#[derive(Deserialize, Debug, Clone)]
65pub struct DbSection {
66    pub sqlite_path: String,
67}
68
69// ─── Loader ──────────────────────────────────────────────────────────
70
71fn load_typed<T: serde::de::DeserializeOwned>(path: &Path) -> Result<T> {
72    let mut engine = teravars::Engine::new();
73    let ctx = teravars::system_context();
74    let paths: Vec<PathBuf> = vec![path.to_path_buf()];
75    let merged = teravars::load_merged(&paths, &mut engine, &ctx)
76        .with_context(|| format!("teravars load_merged: {path:?}"))?;
77    let cfg: T = toml::Value::Table(merged.config)
78        .try_into()
79        .with_context(|| format!("decode config from {path:?}"))?;
80    Ok(cfg)
81}
82
83pub fn load_agent_config(path: &Path) -> Result<AgentConfig> {
84    load_typed(path)
85}
86
87pub fn load_backend_config(path: &Path) -> Result<BackendConfig> {
88    load_typed(path)
89}
90
91#[cfg(test)]
92mod tests {
93    use super::*;
94
95    /// Smoke test the dev-fleet flow against `agent.dev.toml`:
96    ///   1. When `KANADE_DEV_AGENT_ID` is set, the teravars template
97    ///      resolves `vars.pc_id` to that value and propagates it
98    ///      into `agent.id` + `log.path`. Also exercises a `[vars]`
99    ///      self-reference (`pc_id` falls back to `vars.hostname`),
100    ///      which `load_merged` resolves via its internal
101    ///      fixed-point pass.
102    ///   2. Without the env, the template falls back to `system.host`
103    ///      so vanilla `cargo make agent-dev` still works.
104    ///
105    /// Both halves live in a single `#[test]` so they execute
106    /// sequentially within the cargo test runtime — splitting them
107    /// across two tests races on `KANADE_DEV_AGENT_ID` (macOS CI
108    /// turned the race up enough to fail consistently).
109    #[test]
110    fn agent_dev_toml_renders_pc_id_from_env_or_system_host() {
111        // The dev config lives at the workspace root; CARGO_MANIFEST_DIR
112        // resolves to crates/kanade-shared/, so hop up two.
113        let cfg_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
114            .join("..")
115            .join("..")
116            .join("configs")
117            .join("agent.dev.toml");
118
119        // (1) env set → pc_id == env value
120        // SAFETY: env mutation is process-global; this single test
121        // body owns set + remove so no sibling test can race us.
122        unsafe {
123            std::env::set_var("KANADE_DEV_AGENT_ID", "dev-pc-render-test");
124        }
125        let cfg = load_agent_config(&cfg_path).expect("load agent.dev.toml (env set)");
126        assert_eq!(cfg.agent.id, "dev-pc-render-test");
127        assert!(
128            cfg.log.path.contains("dev-pc-render-test"),
129            "log path should embed pc_id, got {}",
130            cfg.log.path,
131        );
132
133        // (2) env removed → pc_id falls back to vars.hostname
134        // = system.host. The host string varies by box; just assert
135        // it's non-empty and not the literal template that would mean
136        // teravars failed to render.
137        unsafe {
138            std::env::remove_var("KANADE_DEV_AGENT_ID");
139        }
140        let cfg = load_agent_config(&cfg_path).expect("load agent.dev.toml (env unset)");
141        assert!(
142            !cfg.agent.id.is_empty(),
143            "pc_id should fall back to system.host"
144        );
145        assert_ne!(
146            cfg.agent.id, "{{ system.host }}",
147            "template should render, not leak"
148        );
149    }
150}