ninox-core 0.10.0

Engine core for the Ninox native app: session lifecycle, config, and storage.
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
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, fs, path::PathBuf};

use crate::harness::{HarnessRegistry, HarnessSpec};

// ---------------------------------------------------------------------------
// Theme
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ThemeVariant {
    Light,
    #[default]
    Dark,
    Ninox,
}

// ---------------------------------------------------------------------------
// Agent configuration
// ---------------------------------------------------------------------------

/// Which agent harness and model to use for a session type.
///
/// Example `~/.config/ninox/config.toml`:
/// ```toml
/// [orchestrator]
/// harness = "claude-code"
/// model = "claude-opus-4-5"
///
/// [worker]
/// harness = "codex"
/// model = "gpt-4o"
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentConfig {
    /// Agent harness: `"claude-code"`, `"codex"`, `"aider"`, or `"opencode"`.
    #[serde(default = "default_harness")]
    pub harness: String,
    /// Model identifier passed to the harness CLI.
    /// Omit to use the harness default.
    pub model: Option<String>,
}

fn default_harness() -> String {
    "claude-code".to_string()
}

impl Default for AgentConfig {
    fn default() -> Self {
        Self { harness: default_harness(), model: None }
    }
}

// Launch-command construction lives in `crate::harness` — `AgentConfig` is
// only the per-role/per-spawn pointer (harness name + model) into the
// registry; resolve via `AppConfig::registry().interactive_cmd/worker_cmd`.

// ---------------------------------------------------------------------------
// Brain configuration
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct BrainConfig {
    pub path: Option<PathBuf>,
    /// Additional named knowledge bases selectable when spawning an
    /// orchestrator. The implicit "default" catalogue (this config's
    /// `resolved_brain_path()`) is always offered first by
    /// `AppConfig::catalogue_options()` and is not duplicated even if an
    /// entry here is also named "default".
    #[serde(default)]
    pub catalogues: Vec<CatalogueRef>,
}

/// A named, selectable knowledge-base catalogue.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CatalogueRef {
    pub name: String,
    pub path: PathBuf,
}

// ---------------------------------------------------------------------------
// Brain harvest configuration
// ---------------------------------------------------------------------------

/// Opt-in-by-default background knowledge capture: when a worker session's
/// PR is first detected, a short-lived `claude -p` subprocess reads its diff
/// and writes facts into the brain vault. See `lifecycle::brain_harvest`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BrainHarvestConfig {
    #[serde(default = "default_brain_harvest_enabled")]
    pub enabled: bool,
}

fn default_brain_harvest_enabled() -> bool {
    true
}

impl Default for BrainHarvestConfig {
    fn default() -> Self {
        Self { enabled: true }
    }
}

// ---------------------------------------------------------------------------
// App configuration
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppConfig {
    pub port:      u16,
    pub font_size: f32,
    #[serde(default)]
    pub theme:     ThemeVariant,
    /// Override for the orchestrator root directory.
    /// Defaults to `~/.config/ninox/orchestrator`.
    #[serde(default)]
    pub orchestrator_root: Option<PathBuf>,
    /// Agent harness and model for orchestrator sessions.
    #[serde(default)]
    pub orchestrator: AgentConfig,
    /// Agent harness and model for worker sessions spawned by `ninox spawn`.
    #[serde(default)]
    pub worker: AgentConfig,
    /// GitHub personal access token. If absent, falls back to GITHUB_TOKEN env var.
    /// Requires `repo` scope for private repos, `public_repo` for public.
    #[serde(default)]
    pub github_token: Option<String>,
    /// Knowledge base (brain) configuration.
    #[serde(default)]
    pub brain: BrainConfig,
    /// Background brain-harvest toggle. See `BrainHarvestConfig`.
    #[serde(default)]
    pub brain_harvest: BrainHarvestConfig,
    /// Theme file name (resolves to `~/.config/ninox/themes/<name>.toml`) or
    /// an absolute/`~`-relative path. `None` uses `themes/field-notes.toml`
    /// if present, else the built-in Field Notes palettes.
    #[serde(default)]
    pub theme_file: Option<String>,
    /// Agent-harness registry overrides/extensions (`[harnesses.<name>]`).
    /// Builtin specs for claude-code/codex/opencode/aider/freebuff apply
    /// when a name is absent here. See `crate::harness`. Kept last so TOML
    /// serialization emits this table-of-tables after every scalar field.
    #[serde(default)]
    pub harnesses: BTreeMap<String, HarnessSpec>,
}

impl Default for AppConfig {
    fn default() -> Self {
        Self {
            port:             8080,
            font_size:        13.0,
            theme:            ThemeVariant::Dark,
            orchestrator_root: None,
            orchestrator:     AgentConfig::default(),
            worker:           AgentConfig::default(),
            github_token:     None,
            brain:            BrainConfig::default(),
            brain_harvest:    BrainHarvestConfig::default(),
            theme_file:       None,
            harnesses:        BTreeMap::new(),
        }
    }
}

impl AppConfig {
    /// The effective harness registry: builtin specs overlaid by this
    /// config's `[harnesses.*]` entries.
    pub fn registry(&self) -> HarnessRegistry {
        HarnessRegistry::from_config(&self.harnesses)
    }

    /// Path to the knowledge-base (brain) directory.
    ///
    /// Honors the `NINOX_BRAIN` environment variable as an override: if
    /// set, it is treated as an absolute path to the brain directory and
    /// returned as-is, mirroring how `config_path()` honors `NINOX_CONFIG`.
    /// This lets a selected catalogue (see `catalogue_options()`) be handed
    /// to a spawned orchestrator session via its environment without
    /// mutating `config.toml`, and lets tests redirect brain reads/writes
    /// without touching the real user brain directory.
    ///
    /// Falls back to `self.brain.path` when set, else `<config_dir>/ninox/brain`.
    pub fn resolved_brain_path(&self) -> PathBuf {
        if let Ok(p) = std::env::var("NINOX_BRAIN") {
            if !p.is_empty() {
                return PathBuf::from(p);
            }
        }
        if let Some(ref p) = self.brain.path {
            return p.clone();
        }
        dirs::config_dir()
            .unwrap_or_else(|| PathBuf::from("."))
            .join("ninox")
            .join("brain")
    }

    /// All selectable knowledge-base catalogues: the implicit "default"
    /// (this config's `resolved_brain_path()`) followed by any additional
    /// catalogues configured under `[[brain.catalogues]]` — skipping any
    /// entry literally named "default" to avoid a confusing duplicate.
    pub fn catalogue_options(&self) -> Vec<CatalogueRef> {
        let mut options = vec![CatalogueRef {
            name: "default".to_string(),
            path: self.resolved_brain_path(),
        }];
        options.extend(
            self.brain
                .catalogues
                .iter()
                .filter(|c| c.name != "default")
                .cloned(),
        );
        options
    }

    pub fn resolved_orchestrator_root(&self) -> PathBuf {
        self.orchestrator_root.clone().unwrap_or_else(|| {
            dirs::config_dir()
                .unwrap_or_else(|| PathBuf::from("."))
                .join("ninox")
                .join("orchestrator")
        })
    }

    /// Path to the `config.toml` file.
    ///
    /// Honors the `NINOX_CONFIG` environment variable as an override: if
    /// set, it is treated as an absolute path to the config file itself
    /// (not a directory) and returned as-is. This is the same override
    /// consumed by spawned agent sessions (see the `NINOX_CONFIG` env var
    /// set alongside `NINOX_BIN` when launching orchestrator sessions), and
    /// it also lets tests redirect config reads/writes away from the real
    /// user config file (e.g. `~/Library/Application Support/ninox/config.toml`
    /// on macOS) without mutating developer machine state.
    ///
    /// Falls back to `<config_dir>/ninox/config.toml` when unset.
    pub fn config_path() -> PathBuf {
        if let Ok(p) = std::env::var("NINOX_CONFIG") {
            if !p.is_empty() {
                return PathBuf::from(p);
            }
        }
        dirs::config_dir()
            .unwrap_or_else(|| PathBuf::from("."))
            .join("ninox")
            .join("config.toml")
    }

    /// Directory for Ninox-managed shell wrappers prepended to agent PATH.
    /// Default: `~/.config/ninox/bin/`
    pub fn ninox_bin_dir() -> PathBuf {
        dirs::config_dir()
            .unwrap_or_else(|| PathBuf::from("."))
            .join("ninox")
            .join("bin")
    }

    /// Directory where per-session metadata JSON files are written by wrapper hooks.
    /// Default: `~/.config/ninox/sessions/`
    pub fn sessions_dir() -> PathBuf {
        dirs::config_dir()
            .unwrap_or_else(|| PathBuf::from("."))
            .join("ninox")
            .join("sessions")
    }

    fn path() -> PathBuf { Self::config_path() }

    pub fn load() -> Result<Self> {
        let p = Self::path();
        if !p.exists() { return Ok(Self::default()); }
        Ok(toml::from_str(&fs::read_to_string(p)?)?)
    }

    pub fn save(&self) -> Result<()> {
        let p = Self::path();
        fs::create_dir_all(p.parent().unwrap())?;
        fs::write(p, toml::to_string(self)?)?;
        Ok(())
    }
}

/// Serializes tests that mutate process-global env vars (`NINOX_CONFIG`,
/// `NINOX_BRAIN`) against each other — `cargo test` runs test fns on
/// parallel threads, so without this guard one test's env mutation could
/// leak into another's read. `pub(crate)` and shared with
/// `lifecycle::poller`'s tests, which also mutate `NINOX_CONFIG`.
#[cfg(test)]
pub(crate) static ENV_TEST_GUARD: std::sync::Mutex<()> = std::sync::Mutex::new(());

/// Set `key=value` for the duration of `f`, restoring the prior value (or
/// unsetting it) afterward. Serialized via `ENV_TEST_GUARD` since env vars
/// are process-global state shared across parallel test threads. Mirrors
/// `ninox_app::app::tests::with_env_override`.
#[cfg(test)]
pub(crate) fn with_env_override<T>(
    key: &str,
    value: impl AsRef<std::ffi::OsStr>,
    f: impl FnOnce() -> T,
) -> T {
    let _guard = ENV_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
    let prior = std::env::var(key).ok();
    std::env::set_var(key, value);

    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));

    match prior {
        Some(v) => std::env::set_var(key, v),
        None    => std::env::remove_var(key),
    }
    result.unwrap()
}

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

    #[test]
    fn round_trip() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("config.toml");
        let cfg = AppConfig { port: 9090, font_size: 14.0, theme: ThemeVariant::Light, ..AppConfig::default() };
        fs::write(&path, toml::to_string(&cfg).unwrap()).unwrap();
        let loaded: AppConfig = toml::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
        assert_eq!(loaded.port, 9090);
        assert_eq!(loaded.theme, ThemeVariant::Light);
        assert!(loaded.orchestrator_root.is_none());
    }

    #[test]
    fn default_theme_is_dark() {
        assert_eq!(AppConfig::default().theme, ThemeVariant::Dark);
    }

    #[test]
    fn missing_theme_field_defaults_to_dark() {
        let cfg: AppConfig = toml::from_str("port = 8080\nfont_size = 13.0\n").unwrap();
        assert_eq!(cfg.theme, ThemeVariant::Dark);
    }

    #[test]
    fn agent_config_round_trip() {
        let toml = "port = 8080\nfont_size = 13.0\n\n[orchestrator]\nharness = \"claude-code\"\nmodel = \"claude-opus-4-5\"\n\n[worker]\nharness = \"codex\"\n";
        let cfg: AppConfig = toml::from_str(toml).unwrap();
        assert_eq!(cfg.orchestrator.harness, "claude-code");
        assert_eq!(cfg.orchestrator.model.as_deref(), Some("claude-opus-4-5"));
        assert_eq!(cfg.worker.harness, "codex");
        assert!(cfg.worker.model.is_none());
    }

    // Launch-shape tests for the four known harnesses moved to
    // `crate::harness::tests` with the registry.

    #[test]
    fn resolved_orchestrator_root_default() {
        let cfg = AppConfig::default();
        assert!(cfg.resolved_orchestrator_root().ends_with("ninox/orchestrator"));
    }

    #[test]
    fn config_path_honors_ninox_config_env() {
        let dir = tempdir().unwrap();
        let override_path = dir.path().join("config_path_honors_ninox_config_env.toml");

        with_env_override("NINOX_CONFIG", &override_path, || {
            assert_eq!(AppConfig::config_path(), override_path);
        });
    }

    #[test]
    fn resolved_brain_path_honors_ninox_brain_env() {
        let dir = tempdir().unwrap();
        let override_path = dir.path().join("brain-override");

        with_env_override("NINOX_BRAIN", &override_path, || {
            let cfg = AppConfig::default();
            assert_eq!(cfg.resolved_brain_path(), override_path);
        });
    }

    #[test]
    fn catalogue_options_defaults_to_single_entry() {
        // Serialize against resolved_brain_path_honors_ninox_brain_env: this
        // test reads resolved_brain_path() twice (via catalogue_options and
        // directly) and must not straddle that test's NINOX_BRAIN window.
        let _guard = ENV_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        let cfg = AppConfig::default();
        let options = cfg.catalogue_options();
        assert_eq!(options.len(), 1);
        assert_eq!(options[0].name, "default");
        assert_eq!(options[0].path, cfg.resolved_brain_path());
    }

    #[test]
    fn brain_harvest_defaults_to_enabled() {
        assert!(AppConfig::default().brain_harvest.enabled);
    }

    #[test]
    fn brain_harvest_missing_table_defaults_to_enabled() {
        let cfg: AppConfig = toml::from_str("port = 8080\nfont_size = 13.0\n").unwrap();
        assert!(cfg.brain_harvest.enabled);
    }

    #[test]
    fn brain_harvest_can_be_disabled_via_config() {
        let toml_src = "port = 8080\nfont_size = 13.0\n\n[brain_harvest]\nenabled = false\n";
        let cfg: AppConfig = toml::from_str(toml_src).unwrap();
        assert!(!cfg.brain_harvest.enabled);
    }

    #[test]
    fn catalogue_options_appends_configured_catalogues_and_skips_duplicate_default() {
        let mut cfg = AppConfig::default();
        cfg.brain.catalogues = vec![
            CatalogueRef { name: "docs".to_string(), path: PathBuf::from("/tmp/docs-brain") },
            CatalogueRef { name: "default".to_string(), path: PathBuf::from("/tmp/should-be-skipped") },
        ];
        let options = cfg.catalogue_options();
        assert_eq!(options.len(), 2);
        assert_eq!(options[0].name, "default");
        assert_eq!(options[1].name, "docs");
        assert_eq!(options[1].path, PathBuf::from("/tmp/docs-brain"));
    }
}