nightporter 0.1.0

Handles your PRs while you're away: an agentic night shift for GitHub and GitLab.
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
//! Config: one global `config.toml` plus optional per-repo override files.
//!
//! Layering is done on raw TOML tables (`[defaults]` ⊕ repo file), then deserialised once into
//! [`RepoSettings`], so every setting is automatically overridable per repo.

use crate::forge::{ForgeKind, RepoId, Trigger};
use crate::paths::{Paths, expand_tilde};
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::time::Duration;

pub const VERSION: u32 = 1;

#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
    #[serde(default = "one")]
    pub version: u32,
    #[serde(default = "default_code_dir")]
    pub code_dir: String,
    #[serde(default = "three")]
    pub scan_depth: usize,
    #[serde(default = "two_min", with = "dur")]
    pub poll_interval: Duration,
    #[serde(default = "ten_min", with = "dur")]
    pub sweep_interval: Duration,
    #[serde(default = "five")]
    pub min_free_gb: u64,
    #[serde(default = "two_usize")]
    pub max_concurrent_jobs: usize,
    #[serde(default = "fifty")]
    pub daily_job_cap: u32,
    #[serde(default = "thirty")]
    pub retention_days: u32,
    #[serde(default = "fourteen")]
    pub worktree_idle_days: u32,
    #[serde(default)]
    pub accounts: Vec<Account>,
    #[serde(default)]
    pub notifications: Notifications,
    #[serde(default)]
    pub marketplaces: Vec<String>,
    /// Where `h` / `nightporter handoff` opens a job: `auto`, `herdr` or `rex`.
    #[serde(default)]
    pub handoff: Handoff,
    /// Raw `[defaults]` table; resolved per repo by [`Config::settings_for`].
    #[serde(default)]
    pub defaults: toml::Table,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Account {
    pub forge: ForgeKind,
    #[serde(default)]
    pub host: Option<String>,
    /// `cli` (gh/glab auth token) or `keyring`.
    #[serde(default)]
    pub token: TokenSource,
}

impl Account {
    pub fn host(&self) -> &str {
        self.host.as_deref().unwrap_or(match self.forge {
            ForgeKind::GitHub => "github.com",
            ForgeKind::GitLab => "gitlab.com",
        })
    }
}

#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum Handoff {
    /// The terminal you're in, else whichever of herdr or Rex is installed.
    #[default]
    Auto,
    Herdr,
    Rex,
}

#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum TokenSource {
    #[default]
    Cli,
    Keyring,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
#[allow(clippy::struct_excessive_bools, reason = "mirrors the [notifications] TOML table")]
pub struct Notifications {
    #[serde(default = "yes")]
    pub needs_approval: bool,
    #[serde(default = "yes")]
    pub failed: bool,
    #[serde(default = "yes")]
    pub done: bool,
    #[serde(default = "yes")]
    pub new_author: bool,
}

impl Default for Notifications {
    fn default() -> Self {
        Self { needs_approval: true, failed: true, done: true, new_author: true }
    }
}

#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(rename_all = "lowercase")]
pub enum Level {
    Observe,
    Suggest,
    Draft,
    Auto,
}

impl Level {
    pub fn as_str(self) -> &'static str {
        match self {
            Level::Observe => "observe",
            Level::Suggest => "suggest",
            Level::Draft => "draft",
            Level::Auto => "auto",
        }
    }
}

#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum AgentKind {
    Claude,
    OpenCode,
}

impl AgentKind {
    pub fn label(self) -> &'static str {
        match self {
            AgentKind::Claude => "Claude Code",
            AgentKind::OpenCode => "OpenCode",
        }
    }
    pub fn bin(self) -> &'static str {
        match self {
            AgentKind::Claude => "claude",
            AgentKind::OpenCode => "opencode",
        }
    }
}

#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum Escalation {
    Deps,
    Size,
}

/// Effective settings for one repo (defaults with the repo file layered on top).
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RepoSettings {
    #[serde(default)]
    pub subscribed: bool,
    #[serde(default = "claude")]
    pub agent: AgentKind,
    /// Extra args for the agent CLI, e.g. `["--model", "opus"]`.
    #[serde(default)]
    pub agent_args: Vec<String>,
    /// Shell commands the agent may run (e.g. `"npm test"`, `"ddev phpunit"`). Prefix match.
    #[serde(default)]
    pub allow_commands: Vec<String>,
    #[serde(default = "draft")]
    pub level: Level,
    #[serde(default = "all_triggers")]
    pub triggers: Vec<Trigger>,
    #[serde(default = "two_min", with = "dur")]
    pub debounce: Duration,
    #[serde(default)]
    pub max_concurrent: Option<usize>,
    #[serde(default = "three_u32")]
    pub max_ci_attempts: u32,
    /// Let CI-failure jobs run at `auto`. CI output is text from builds and tools that may print
    /// anything (including a stranger's test names or logs), so by default those jobs stop at
    /// `draft` and wait for you.
    #[serde(default)]
    pub ci_auto: bool,
    #[serde(default = "thirty_min", with = "dur")]
    pub timeout: Duration,
    #[serde(default)]
    pub max_budget_usd: Option<f64>,
    /// Claude Code's OS sandbox for the agent's shell commands (Seatbelt on macOS, bubblewrap on
    /// Linux). Fails closed: if it can't start, the job fails instead of running unsandboxed.
    /// Turn off for repos whose test commands need Docker/DDEV sockets.
    #[serde(default = "yes")]
    pub sandbox: bool,
    /// Domains sandboxed commands may reach (none by default).
    #[serde(default)]
    pub sandbox_domains: Vec<String>,
    /// Extra paths under your home folder that sandboxed commands may read (on top of the
    /// worktree and common toolchain folders). `["~/"]` lifts the home-folder restriction.
    #[serde(default)]
    pub sandbox_read_allow: Vec<String>,
    /// Extra instructions file (your own, outside the repo).
    #[serde(default)]
    pub prompt: Option<String>,
    #[serde(default)]
    pub packs: Vec<String>,
    #[serde(default)]
    pub trust: Trust,
    #[serde(default)]
    pub schedule: Vec<Window>,
    #[serde(default)]
    pub reply: ReplySettings,
    #[serde(default)]
    pub checks: Checks,
    #[serde(default)]
    pub env: Env,
    #[serde(default)]
    pub maintainer: Maintainer,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Trust {
    #[serde(default = "default_roles")]
    pub roles: Vec<crate::forge::Role>,
    #[serde(default)]
    pub allow_users: Vec<String>,
    #[serde(default)]
    pub deny_users: Vec<String>,
    #[serde(default)]
    pub allow_teams: Vec<String>,
    #[serde(default)]
    pub deny_teams: Vec<String>,
    #[serde(default)]
    pub allow_bots: Vec<String>,
    /// Accept everyone. Capped at `suggest`.
    #[serde(default)]
    pub open: bool,
}

impl Default for Trust {
    fn default() -> Self {
        toml::from_str("").expect("defaults")
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Window {
    /// `mon-fri`, `sat,sun`, `daily`, `tue`.
    pub days: String,
    /// `HH:MM-HH:MM`; may cross midnight (`22:00-06:00`).
    pub windows: Vec<String>,
    /// IANA time zone; defaults to the system zone.
    #[serde(default)]
    pub tz: Option<String>,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ReplySettings {
    /// `concise`, `detailed-tech-lead`, `non-technical`, a pack style, or a path to a `.md` file.
    #[serde(default = "concise")]
    pub style: String,
    #[serde(default = "en")]
    pub language: String,
    #[serde(default = "yes")]
    pub footer: bool,
    #[serde(default)]
    pub resolve_threads: bool,
}

impl Default for ReplySettings {
    fn default() -> Self {
        toml::from_str("").expect("defaults")
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Checks {
    /// Extra protected globs, added to the built-in list (which can't be removed).
    #[serde(default)]
    pub protected: Vec<String>,
    #[serde(default = "default_escalations")]
    pub escalate_on: Vec<Escalation>,
    #[serde(default = "five_hundred")]
    pub max_diff_lines: usize,
}

impl Default for Checks {
    fn default() -> Self {
        toml::from_str("").expect("defaults")
    }
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Env {
    #[serde(default)]
    pub setup: Vec<String>,
    #[serde(default)]
    pub teardown: Vec<String>,
    #[serde(default)]
    pub cleanup: Vec<String>,
    #[serde(default)]
    pub prompt: Option<String>,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Maintainer {
    #[serde(default)]
    pub enabled: bool,
    #[serde(default = "draft")]
    pub level: Level,
    #[serde(default = "np_label")]
    pub label: String,
}

impl Default for Maintainer {
    fn default() -> Self {
        toml::from_str("").expect("defaults")
    }
}

impl Config {
    pub fn load(paths: &Paths) -> Result<Self> {
        let file = paths.config_file();
        let text = match std::fs::read_to_string(&file) {
            Ok(t) => t,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
            Err(e) => return Err(e).with_context(|| format!("read {}", file.display())),
        };
        Self::parse(&text).with_context(|| format!("in {}", file.display()))
    }

    pub fn parse(text: &str) -> Result<Self> {
        let cfg: Config = toml::from_str(text)?;
        if cfg.version > VERSION {
            bail!("config version {} is newer than this nightporter ({VERSION}); upgrade nightporter", cfg.version);
        }
        // Validate defaults eagerly so typos surface at load, not at the first event.
        cfg.resolve(None)?;
        Ok(cfg)
    }

    pub fn code_dir(&self) -> PathBuf {
        expand_tilde(&self.code_dir)
    }

    /// Effective settings for `repo`, reading its override file if present.
    pub fn settings_for(&self, paths: &Paths, repo: &RepoId) -> Result<RepoSettings> {
        let file = paths.repo_file(repo);
        let over = match std::fs::read_to_string(&file) {
            Ok(t) => Some(t.parse::<toml::Table>().with_context(|| format!("in {}", file.display()))?),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
            Err(e) => return Err(e).with_context(|| format!("read {}", file.display())),
        };
        self.resolve(over.as_ref()).with_context(|| format!("settings for {repo}"))
    }

    pub fn resolve(&self, over: Option<&toml::Table>) -> Result<RepoSettings> {
        let mut merged = self.defaults.clone();
        // `subscribed` only makes sense per repo.
        merged.remove("subscribed");
        if let Some(o) = over {
            merge(&mut merged, o);
        }
        let s: RepoSettings = merged.try_into()?;
        crate::schedule::validate(&s.schedule)?;
        Ok(s.clamped())
    }
}

impl RepoSettings {
    /// Apply the safety caps that config can't override.
    fn clamped(mut self) -> Self {
        if self.trust.open {
            self.level = self.level.min(Level::Suggest);
            self.maintainer.level = self.maintainer.level.min(Level::Suggest);
        }
        self.maintainer.level = self.maintainer.level.min(Level::Draft);
        self
    }

    pub fn concurrency(&self) -> usize {
        self.max_concurrent.unwrap_or(usize::MAX).max(1)
    }
}

/// Arrays that combine (global ∪ repo) instead of being replaced: a repo file adding one trusted
/// user must not drop the global lists, and must never be able to drop a global deny.
const UNION: &[&str] =
    &["trust.allow_users", "trust.deny_users", "trust.allow_teams", "trust.deny_teams", "trust.allow_bots", "checks.protected"];

/// Deep-merge `over` into `base`: tables merge, [`UNION`] arrays combine, everything else
/// (including other arrays) replaces.
pub fn merge(base: &mut toml::Table, over: &toml::Table) {
    merge_at(base, over, "");
}

fn merge_at(base: &mut toml::Table, over: &toml::Table, prefix: &str) {
    for (k, v) in over {
        let path = if prefix.is_empty() { k.clone() } else { format!("{prefix}.{k}") };
        match (base.get_mut(k), v) {
            (Some(toml::Value::Table(b)), toml::Value::Table(o)) => merge_at(b, o, &path),
            (Some(toml::Value::Array(b)), toml::Value::Array(o)) if UNION.contains(&path.as_str()) => {
                for x in o {
                    if !b.contains(x) {
                        b.push(x.clone());
                    }
                }
            }
            _ => {
                base.insert(k.clone(), v.clone());
            }
        }
    }
}

/// Edit a TOML file in place, keeping comments and layout. Every edit re-reads the file right
/// before writing, so edits from several TUIs (or an editor) don't overwrite each other.
/// Validates the result and writes atomically.
pub fn edit_file(path: &Path, f: impl FnOnce(&mut toml_edit::DocumentMut)) -> Result<()> {
    let text = match std::fs::read_to_string(path) {
        Ok(t) => t,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(e) => return Err(e.into()),
    };
    let mut doc: toml_edit::DocumentMut = text.parse().with_context(|| format!("parse {}", path.display()))?;
    f(&mut doc);
    let out = doc.to_string();
    // Validate before writing, so a bad edit can't brick the daemon.
    if path.file_name().is_some_and(|n| n == "config.toml") {
        Config::parse(&out)?;
    } else {
        Config::parse("")?.resolve(Some(&out.parse::<toml::Table>()?))?;
    }
    write_atomic(path, out.as_bytes())
}

pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<()> {
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir)?;
    }
    let tmp = path.with_extension(format!("tmp.{}", std::process::id()));
    std::fs::write(&tmp, bytes)?;
    std::fs::rename(&tmp, path)?;
    Ok(())
}

/// Parse `90s`, `2m`, `1h30m`, `1d`.
pub fn parse_duration(s: &str) -> Result<Duration> {
    let s = s.trim();
    let (mut total, mut num) = (0u64, String::new());
    for c in s.chars() {
        if c.is_ascii_digit() {
            num.push(c);
            continue;
        }
        let n: u64 = num.parse().with_context(|| format!("bad duration {s:?}"))?;
        num.clear();
        total += n * match c {
            's' => 1,
            'm' => 60,
            'h' => 3600,
            'd' => 86400,
            _ => bail!("bad duration unit {c:?} in {s:?} (use s, m, h, d)"),
        };
    }
    if !num.is_empty() || s.is_empty() {
        bail!("bad duration {s:?} (e.g. 90s, 2m, 1h30m)");
    }
    Ok(Duration::from_secs(total))
}

pub fn format_duration(d: Duration) -> String {
    let s = d.as_secs();
    match s {
        _ if s.is_multiple_of(3600) && s > 0 => format!("{}h", s / 3600),
        _ if s.is_multiple_of(60) && s > 0 => format!("{}m", s / 60),
        _ => format!("{s}s"),
    }
}

mod dur {
    use serde::{Deserialize, Deserializer, Serializer};
    use std::time::Duration;
    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
        super::parse_duration(&String::deserialize(d)?).map_err(serde::de::Error::custom)
    }
    #[allow(dead_code)]
    pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(&super::format_duration(*v))
    }
}

/// Starter config written by `nightporter setup`.
pub const TEMPLATE: &str = include_str!("../assets/config.example.toml");

fn one() -> u32 {
    1
}
fn three() -> usize {
    3
}
fn three_u32() -> u32 {
    3
}
fn five() -> u64 {
    5
}
fn two_usize() -> usize {
    2
}
fn fifty() -> u32 {
    50
}
fn thirty() -> u32 {
    30
}
fn fourteen() -> u32 {
    14
}
fn five_hundred() -> usize {
    500
}
fn yes() -> bool {
    true
}
fn two_min() -> Duration {
    Duration::from_secs(120)
}
fn ten_min() -> Duration {
    Duration::from_secs(600)
}
fn thirty_min() -> Duration {
    Duration::from_secs(1800)
}
fn default_code_dir() -> String {
    "~/coding".into()
}
fn claude() -> AgentKind {
    AgentKind::Claude
}
fn draft() -> Level {
    Level::Draft
}
fn concise() -> String {
    "concise".into()
}
fn en() -> String {
    "en".into()
}
fn np_label() -> String {
    "nightporter".into()
}
fn all_triggers() -> Vec<Trigger> {
    use Trigger::{CiFailure, Comment, MergeConflict, Review, ReviewComment};
    vec![ReviewComment, Review, Comment, CiFailure, MergeConflict]
}
fn default_roles() -> Vec<crate::forge::Role> {
    use crate::forge::Role::{Collaborator, Maintainer, Member, Owner};
    vec![Owner, Maintainer, Member, Collaborator]
}
fn default_escalations() -> Vec<Escalation> {
    vec![Escalation::Deps, Escalation::Size]
}

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

    #[test]
    fn empty_config_has_sane_defaults() {
        let c = Config::parse("").unwrap();
        let s = c.resolve(None).unwrap();
        assert!(!s.subscribed);
        assert_eq!(s.level, Level::Draft);
        assert_eq!(s.debounce, Duration::from_secs(120));
        assert_eq!(s.trust.roles.len(), 4);
        assert!(s.reply.footer);
        assert!(!s.reply.resolve_threads);
        assert_eq!(c.poll_interval, Duration::from_secs(120));
    }

    #[test]
    fn template_parses() {
        Config::parse(TEMPLATE).unwrap();
    }

    #[test]
    fn repo_overrides_merge_deeply() {
        let c = Config::parse(
            r#"
            [defaults]
            level = "auto"
            [defaults.trust]
            allow_users = ["alice"]
            [defaults.reply]
            style = "detailed-tech-lead"
            "#,
        )
        .unwrap();
        let over: toml::Table = toml::from_str(
            r"
            subscribed = true
            max_ci_attempts = 5
            [reply]
            footer = false
            ",
        )
        .unwrap();
        let s = c.resolve(Some(&over)).unwrap();
        assert!(s.subscribed);
        assert_eq!(s.level, Level::Auto);
        assert_eq!(s.max_ci_attempts, 5);
        assert_eq!(s.reply.style, "detailed-tech-lead");
        assert!(!s.reply.footer);
        assert_eq!(s.trust.allow_users, vec!["alice"]);
    }

    #[test]
    fn trust_lists_combine() {
        let c = Config::parse("[defaults.trust]\nallow_users = [\"alice\"]\ndeny_users = [\"mallory\"]\nroles = [\"owner\"]").unwrap();
        let over: toml::Table = toml::from_str("[trust]\nallow_users = [\"carol\"]\ndeny_users = []\nroles = [\"maintainer\"]").unwrap();
        let s = c.resolve(Some(&over)).unwrap();
        assert_eq!(s.trust.allow_users, vec!["alice", "carol"]);
        assert_eq!(s.trust.deny_users, vec!["mallory"], "a repo can't drop a global deny");
        assert_eq!(s.trust.roles, vec![crate::forge::Role::Maintainer], "other arrays still replace");
    }

    #[test]
    fn subscribed_cannot_be_set_globally() {
        let c = Config::parse("[defaults]\nsubscribed = true").unwrap();
        assert!(!c.resolve(None).unwrap().subscribed);
    }

    #[test]
    fn caps_cannot_be_overridden() {
        let c = Config::parse("[defaults]\nlevel = \"auto\"\n[defaults.maintainer]\nlevel = \"auto\"").unwrap();
        let s = c.resolve(None).unwrap();
        assert_eq!(s.maintainer.level, Level::Draft);
        let open: toml::Table = toml::from_str("[trust]\nopen = true").unwrap();
        let s = c.resolve(Some(&open)).unwrap();
        assert_eq!(s.level, Level::Suggest);
        assert_eq!(s.maintainer.level, Level::Suggest);
    }

    #[test]
    fn typos_are_errors() {
        assert!(Config::parse("[defaults]\nlevle = \"auto\"").is_err());
        assert!(Config::parse("pol_interval = \"2m\"").is_err());
        assert!(Config::parse("version = 99").is_err());
    }

    #[test]
    fn durations() {
        assert_eq!(parse_duration("90s").unwrap(), Duration::from_secs(90));
        assert_eq!(parse_duration("1h30m").unwrap(), Duration::from_secs(5400));
        assert!(parse_duration("5").is_err());
        assert!(parse_duration("5x").is_err());
        assert!(parse_duration("").is_err());
        assert_eq!(format_duration(Duration::from_secs(120)), "2m");
    }

    #[test]
    fn edit_file_preserves_comments_and_validates() {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().join("x.toml");
        std::fs::write(&p, "# keep me\nlevel = \"draft\"\n").unwrap();
        edit_file(&p, |d| d["subscribed"] = toml_edit::value(true)).unwrap();
        let text = std::fs::read_to_string(&p).unwrap();
        assert!(text.contains("# keep me") && text.contains("subscribed = true"));
        // Another writer's change survives the next edit.
        std::fs::write(&p, "level = \"auto\"\n").unwrap();
        edit_file(&p, |d| d["subscribed"] = toml_edit::value(false)).unwrap();
        assert!(std::fs::read_to_string(&p).unwrap().contains("auto"));
        // Invalid edits are rejected before writing.
        assert!(edit_file(&p, |d| d["level"] = toml_edit::value("yolo")).is_err());
        assert!(std::fs::read_to_string(&p).unwrap().contains("auto"));
    }
}