netsky-core 0.1.5

netsky core: agent model, prompt loader, spawner, config
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
490
//! Per-machine `netsky.toml` loader.
//!
//! Reads `netsky.toml` under the resolved netsky root if present;
//! absent file = `None`, every caller falls back to env vars +
//! `consts.rs` defaults (today's behavior on every machine). Schema
//! lives in `netsky.toml.example` at the repo root and
//! `briefs/netsky-config-design.md` (agent6).
//!
//! This is item 2 of the `netsky.toml` roadmap: parse + struct +
//! `Config::load()`. Wiring into specific callsites (`prompt.rs`
//! `read_cwd_addendum`, `consts.rs` owner lookups, the `[tuning]`
//! macro) lands in follow-up commits so each callsite gets its own
//! deliberate-break test.
//!
//! Precedence reminder (cited from `briefs/netsky-config-design.md`
//! section 4): explicit CLI flag > env var > netsky.toml > consts.rs
//! default. Env-var wins so one-off overrides do not require editing
//! the config file. Matches docker / git / cargo conventions.

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

use serde::Deserialize;

use crate::paths::resolve_netsky_dir;

/// The full per-machine config. Every field is optional; a netsky.toml
/// that omits a section means "use my prior layer's value" (env or
/// compile-time default).
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
pub struct Config {
    pub schema_version: Option<u32>,
    pub netsky: Option<NetskySection>,
    pub owner: Option<OwnerSection>,
    pub addendum: Option<AddendumSection>,
    pub clones: Option<ClonesSection>,
    pub channels: Option<ChannelsSection>,
    pub orgs: Option<OrgsSection>,
    pub tuning: Option<TuningSection>,
    pub peers: Option<PeersSection>,
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
pub struct NetskySection {
    pub dir: Option<String>,
    pub machine_id: Option<String>,
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
pub struct OwnerSection {
    pub name: Option<String>,
    pub imessage: Option<String>,
    pub display_email: Option<String>,
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
pub struct AddendumSection {
    pub agent0: Option<String>,
    pub agentinfinity: Option<String>,
    pub clone_default: Option<String>,
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
pub struct ClonesSection {
    pub default_count: Option<u32>,
    pub default_model: Option<String>,
    pub default_effort: Option<String>,
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
pub struct ChannelsSection {
    pub enabled: Option<Vec<String>>,
    pub imessage: Option<ImessageChannel>,
    pub email: Option<EmailChannel>,
    pub calendar: Option<CalendarChannel>,
    pub tasks: Option<TasksChannel>,
    pub drive: Option<DriveChannel>,
    pub slack: Option<SlackChannel>,
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
pub struct ImessageChannel {
    pub owner_handle: Option<String>,
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
pub struct EmailChannel {
    pub allowed: Option<Vec<String>>,
    pub accounts: Option<Vec<EmailAccount>>,
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
pub struct EmailAccount {
    pub primary: Option<String>,
    pub send_as: Option<Vec<String>>,
}

/// Calendar source allowlist. Currently the calendar source defers to the
/// email allowlist (a primary calendar id IS the owning user's email),
/// so this section is forward-compat scaffolding — populating it does
/// not yet override the email-derived list.
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
pub struct CalendarChannel {
    pub allowed: Option<Vec<String>>,
}

/// Tasks source allowlist. Forward-compat scaffolding; the tasks source
/// currently defers to the email allowlist for `account` arg validation.
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
pub struct TasksChannel {
    pub allowed: Option<Vec<String>>,
}

/// Drive source allowlist. Forward-compat scaffolding; the drive source
/// currently defers to the email allowlist for `account` arg validation
/// AND for `share_file` recipient gating.
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
pub struct DriveChannel {
    pub allowed: Option<Vec<String>>,
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
pub struct SlackChannel {
    pub workspace_id: Option<String>,
    pub bot_token_env: Option<String>,
    pub allowed_channels: Option<Vec<String>>,
    pub allowed_dm_users: Option<Vec<String>>,
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
pub struct OrgsSection {
    pub allowed: Option<Vec<String>>,
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
pub struct TuningSection {
    pub ticker_interval_s: Option<u64>,
    pub agent0_hang_s: Option<u64>,
    pub agent0_hang_repage_s: Option<u64>,
    pub agentinit_window_s: Option<u64>,
    pub agentinit_threshold: Option<u64>,
    pub disk_min_mb: Option<u64>,
    pub email_auto_send: Option<bool>,
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
pub struct PeersSection {
    pub iroh: Option<IrohPeers>,
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
pub struct IrohPeers {
    pub default_label: Option<String>,
    /// Per-peer entries: `[peers.iroh.<label>]` -> IrohPeer. Keys are
    /// arbitrary labels chosen by the owner. v0 ships env-var pairing
    /// (NETSKY_IROH_PEER_<LABEL>_NODEID); the toml-persisted form lands
    /// when the CLI pair-show / pair-add flow ships.
    #[serde(flatten)]
    pub by_label: std::collections::BTreeMap<String, IrohPeer>,
}

#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
pub struct IrohPeer {
    pub node_id: Option<String>,
    pub created: Option<String>,
    pub notes: Option<String>,
}

/// Schema versions this loader knows how to parse. Older versions get
/// an explicit error; the alternative is silent misparse on schema
/// drift.
const SUPPORTED_SCHEMA_VERSIONS: &[u32] = &[1];

impl Config {
    /// Load from the resolved netsky root's `netsky.toml`. Returns:
    ///
    /// - `Ok(None)` if the file is absent. This is the steady state on
    ///   every Cody-machine until the owner copies `netsky.toml.example`
    ///   and edits.
    /// - `Ok(Some(cfg))` on a successful parse.
    /// - `Err(...)` on a present-but-invalid file. Callers MUST surface
    ///   the error rather than silently fall back: a malformed config
    ///   is a config bug, not a missing-file case.
    pub fn load() -> crate::Result<Option<Self>> {
        let dir = resolve_netsky_dir();
        Self::load_from(&dir.join("netsky.toml"))
    }

    /// Load from an explicit path. Used by tests and any caller that
    /// needs to pin a non-default location.
    pub fn load_from(path: &Path) -> crate::Result<Option<Self>> {
        let raw = match std::fs::read_to_string(path) {
            Ok(s) => s,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(e) => {
                return Err(crate::anyhow!("read {}: {e}", path.display()));
            }
        };
        let cfg: Config =
            toml::from_str(&raw).map_err(|e| crate::anyhow!("parse {}: {e}", path.display()))?;
        if let Some(v) = cfg.schema_version
            && !SUPPORTED_SCHEMA_VERSIONS.contains(&v)
        {
            return Err(crate::anyhow!(
                "unsupported schema_version {v} in {} (this binary supports {:?}; \
                 either upgrade netsky or pin schema_version to a supported value)",
                path.display(),
                SUPPORTED_SCHEMA_VERSIONS
            ));
        }
        Ok(Some(cfg))
    }
}

/// Resolve the path netsky.toml WOULD live at, even if the file is
/// missing. Useful for status output and the future `netsky init`
/// scaffolder.
pub fn netsky_toml_path() -> PathBuf {
    resolve_netsky_dir().join("netsky.toml")
}

// ---- value-resolution helpers (env > toml > default) ----------------------
//
// These wrap the precedence chain agent6's brief pinned in section 4
// (env > netsky.toml > consts.rs default). Each helper takes an env
// var name + a config-section-extracter + a compile-time default and
// returns the first non-empty value. Callers call the helper instead of
// reading env directly, so adding netsky.toml support to a new tunable
// is a one-line edit at the callsite.

/// Read `env_var`; if unset or empty, consult the `extract` closure on
/// a freshly-loaded `Config`; if still unset, return `default`.
///
/// Errors loading the TOML are silently swallowed (treated as "no toml
/// value available"). Callers that need to surface a malformed config
/// should call [`Config::load`] directly and handle the error.
pub fn resolve<F>(env_var: &str, extract: F, default: &str) -> String
where
    F: FnOnce(&Config) -> Option<String>,
{
    if let Ok(v) = std::env::var(env_var)
        && !v.is_empty()
    {
        return v;
    }
    if let Some(cfg) = Config::load().ok().flatten()
        && let Some(v) = extract(&cfg)
        && !v.is_empty()
    {
        return v;
    }
    default.to_string()
}

/// Email source allowlist (`[channels.email] allowed = [...]`). Returns
/// an empty vec when no netsky.toml is present or the section is unset.
/// Empty list = source is inert (every recipient rejected): the safe
/// default for a fresh clone with no per-machine config.
pub fn email_allowed() -> Vec<String> {
    Config::load()
        .ok()
        .flatten()
        .and_then(|c| c.channels)
        .and_then(|ch| ch.email)
        .and_then(|e| e.allowed)
        .unwrap_or_default()
}

/// Email source primary accounts (`[[channels.email.accounts]]`). Returns
/// an empty vec when unset. Each `EmailAccount` carries a `primary`
/// address and an optional list of `send_as` aliases.
pub fn email_accounts() -> Vec<EmailAccount> {
    Config::load()
        .ok()
        .flatten()
        .and_then(|c| c.channels)
        .and_then(|ch| ch.email)
        .and_then(|e| e.accounts)
        .unwrap_or_default()
}

/// Resolved owner display name. Substituted into prompt templates that
/// address the owner by name (e.g. `prompts/tick-request.md`).
pub fn owner_name() -> String {
    resolve(
        crate::consts::ENV_OWNER_NAME,
        |cfg| cfg.owner.as_ref().and_then(|o| o.name.clone()),
        crate::consts::OWNER_NAME_DEFAULT,
    )
}

/// Resolved owner iMessage handle. Used by `netsky escalate` to text
/// the owner from the watchdog floor without involving any MCP.
pub fn owner_imessage() -> String {
    resolve(
        crate::consts::ENV_OWNER_IMESSAGE,
        |cfg| cfg.owner.as_ref().and_then(|o| o.imessage.clone()),
        crate::consts::OWNER_IMESSAGE_DEFAULT,
    )
}

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

    fn write(path: &Path, body: &str) {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).unwrap();
        }
        fs::write(path, body).unwrap();
    }

    #[test]
    fn missing_file_returns_ok_none() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("netsky.toml");
        let cfg = Config::load_from(&path).unwrap();
        assert!(cfg.is_none(), "missing file should return Ok(None)");
    }

    #[test]
    fn empty_toml_returns_default_config() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("netsky.toml");
        write(&path, "");
        let cfg = Config::load_from(&path).unwrap().expect("Some");
        assert_eq!(cfg, Config::default());
    }

    #[test]
    fn full_schema_round_trips_via_example() {
        // The repo-root netsky.toml.example IS the schema documentation;
        // make sure it parses cleanly so it stays trustworthy. This
        // also catches future schema additions where someone forgets
        // to add a struct field.
        let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        let repo_root = manifest
            .ancestors()
            .nth(3)
            .expect("repo root sits 3 levels above netsky-core's manifest");
        let example = repo_root.join("netsky.toml.example");
        let cfg = Config::load_from(&example)
            .unwrap()
            .expect("netsky.toml.example must exist + parse");
        // Pin a few fields to catch regression if the example drifts.
        assert_eq!(cfg.schema_version, Some(1), "example: schema_version=1");
        let owner = cfg.owner.as_ref().expect("owner section present");
        assert_eq!(owner.name.as_deref(), Some("Cody"));
        let addendum = cfg.addendum.as_ref().expect("addendum section present");
        assert_eq!(
            addendum.agent0.as_deref(),
            Some("addenda/0-personal.md"),
            "addendum.agent0 pinned to addenda/0-personal.md"
        );
        let tuning = cfg.tuning.as_ref().expect("tuning section present");
        assert_eq!(tuning.ticker_interval_s, Some(60));
    }

    #[test]
    fn unsupported_schema_version_errors_loudly() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("netsky.toml");
        write(&path, "schema_version = 99\n");
        let err = Config::load_from(&path).expect_err("schema_version=99 should error");
        let msg = err.to_string();
        assert!(
            msg.contains("schema_version 99"),
            "error should name the bad version: {msg}"
        );
        assert!(
            msg.contains("supports"),
            "error should list supported versions: {msg}"
        );
    }

    #[test]
    fn malformed_toml_returns_err() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("netsky.toml");
        write(&path, "this = is not [valid toml\n");
        let err = Config::load_from(&path).expect_err("malformed should err");
        assert!(
            err.to_string().contains("parse"),
            "error should mention parse failure: {err}"
        );
    }

    #[test]
    fn partial_toml_leaves_unset_sections_none() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("netsky.toml");
        write(
            &path,
            r#"
schema_version = 1
[owner]
name = "Alice"
imessage = "+15551234567"
"#,
        );
        let cfg = Config::load_from(&path).unwrap().expect("Some");
        assert_eq!(cfg.owner.as_ref().unwrap().name.as_deref(), Some("Alice"));
        assert!(cfg.tuning.is_none(), "[tuning] absent => None");
        assert!(cfg.addendum.is_none(), "[addendum] absent => None");
        assert!(cfg.peers.is_none(), "[peers] absent => None");
    }

    #[test]
    fn resolve_prefers_env_over_default() {
        let prior = std::env::var("NETSKY_TEST_RESOLVE").ok();
        unsafe {
            std::env::set_var("NETSKY_TEST_RESOLVE", "from-env");
        }
        let got = resolve("NETSKY_TEST_RESOLVE", |_| None, "from-default");
        assert_eq!(got, "from-env");
        unsafe {
            match prior {
                Some(v) => std::env::set_var("NETSKY_TEST_RESOLVE", v),
                None => std::env::remove_var("NETSKY_TEST_RESOLVE"),
            }
        }
    }

    #[test]
    fn resolve_falls_through_to_default_when_env_and_toml_unset() {
        let prior = std::env::var("NETSKY_TEST_RESOLVE_FT").ok();
        unsafe {
            std::env::remove_var("NETSKY_TEST_RESOLVE_FT");
        }
        let got = resolve("NETSKY_TEST_RESOLVE_FT", |_| None, "from-default");
        assert_eq!(got, "from-default");
        unsafe {
            if let Some(v) = prior {
                std::env::set_var("NETSKY_TEST_RESOLVE_FT", v);
            }
        }
    }

    #[test]
    fn resolve_treats_empty_env_as_unset() {
        let prior = std::env::var("NETSKY_TEST_RESOLVE_EMPTY").ok();
        unsafe {
            std::env::set_var("NETSKY_TEST_RESOLVE_EMPTY", "");
        }
        let got = resolve("NETSKY_TEST_RESOLVE_EMPTY", |_| None, "from-default");
        assert_eq!(
            got, "from-default",
            "empty env should fall through to default, not return empty"
        );
        unsafe {
            match prior {
                Some(v) => std::env::set_var("NETSKY_TEST_RESOLVE_EMPTY", v),
                None => std::env::remove_var("NETSKY_TEST_RESOLVE_EMPTY"),
            }
        }
    }

    #[test]
    fn iroh_peers_keyed_by_label_via_serde_flatten() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("netsky.toml");
        write(
            &path,
            r#"
[peers.iroh]
default_label = "personal"

[peers.iroh.work]
node_id = "abc123"
created = "2026-04-15T04:30:00Z"
notes = "work laptop"

[peers.iroh.server]
node_id = "def456"
"#,
        );
        let cfg = Config::load_from(&path).unwrap().expect("Some");
        let iroh = cfg.peers.as_ref().unwrap().iroh.as_ref().unwrap();
        assert_eq!(iroh.default_label.as_deref(), Some("personal"));
        assert_eq!(iroh.by_label.len(), 2);
        assert_eq!(
            iroh.by_label.get("work").unwrap().node_id.as_deref(),
            Some("abc123")
        );
        assert_eq!(
            iroh.by_label.get("server").unwrap().node_id.as_deref(),
            Some("def456")
        );
    }
}