newt-core 0.8.0

Newt-Agent core types, errors, and the NeMoCode-style tier router
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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
//! The `~/.newt/ocap/` durable-policy store (#1131, epic #1126 track O2) — the
//! newt-side store that implements the agent-bridle policy contract (bridle
//! #221 / #220).
//!
//! The accumulation loop's memory: prompt → decision → **stored policy** →
//! fewer prompts. Four per-verdict TOML files under `~/.newt/ocap/` —
//! `approve.toml` / `deny.toml` / `ask.toml` / `passkey.toml` — each a bridle
//! [`PolicyFile`] of per-class entries (exec / fs / net). This module LOADS
//! them into a [`PolicySet`] and answers the one question the permission gate
//! asks: *"is there a durable verdict for this capability + target?"*
//!
//! Three rules from the contract (bridle `policy`), enforced by construction:
//! - **Precedence:** deny > passkey > ask > approve — the most restrictive
//!   durable verdict wins. [`PolicySet::evaluate`] applies it.
//! - **No match ⇒ fall through:** [`evaluate_request`] returns `None`, and the
//!   gate uses its interactive prompt / default-deny floor. Durable policy only
//!   ever *narrows or pre-answers*; it never widens the floor.
//! - **The loosening verdict is signed** (#1207 / bridle #226): every
//!   `approve.toml` entry must carry a valid Ed25519 `sig` by the operator's
//!   root key. [`verify_approves`] drops unsigned/tampered approves LOUDLY at
//!   load — fail-closed to "no durable grant" (the gate prompts). With no root
//!   key available, ALL approves drop. The narrowing verdicts (deny/ask/
//!   passkey) load unsigned: forging them can only narrow, and dropping a deny
//!   over a bad signature would widen — exactly backwards.
//!
//! Split for the mocked-unit tier (no real fs in unit tests): [`build_store`] +
//! [`verify_approves`] are pure (contents + injected verifier); [`load_store`]
//! is the thin fs wrapper.

use std::path::Path;

pub use agent_bridle::policy::{
    ApproveVerifier, CapabilityClass, Ed25519ApproveVerifier, ExecEntry, FsEntry, NetEntry,
    PolicyFile, PolicySet, Verdict,
};

use crate::agentic::DenialKind;

/// Shared recovery nudge for startup grant/protection diagnostics.
pub const REPAIR_HINT: &str = "run `newt doctor` to inspect and repair";

/// The four verdicts in load order — every store read walks exactly these.
pub const VERDICTS: [Verdict; 4] = [
    Verdict::Deny,
    Verdict::Passkey,
    Verdict::Ask,
    Verdict::Approve,
];

/// Map a newt permission axis onto the policy contract's capability class.
/// `None` for axes the durable store does not cover (a remote MCP tool leash is
/// name-based, not a fs/exec/net capability — it is never durably stored here).
pub fn class_for(kind: DenialKind) -> Option<CapabilityClass> {
    match kind {
        DenialKind::Exec => Some(CapabilityClass::Exec),
        DenialKind::FsRead | DenialKind::FsWrite => Some(CapabilityClass::Fs),
        DenialKind::Net => Some(CapabilityClass::Net),
        _ => None,
    }
}

/// Build a [`PolicySet`] from the four verdict files' contents (pure — the
/// unit-testable core). Each entry is `(verdict, Some(toml))` for a present
/// file or `(verdict, None)` for a missing one. A malformed file is SKIPPED
/// (its verdict stays empty) with the error pushed to `warnings` — a bad policy
/// file must never break startup, only lose that file's rules loudly.
pub fn build_store(files: &[(Verdict, Option<String>)]) -> (PolicySet, Vec<String>) {
    let mut set = PolicySet::default();
    let mut warnings = Vec::new();
    for (verdict, contents) in files {
        let Some(text) = contents else { continue };
        match PolicyFile::parse(text) {
            Ok(file) => {
                set.files.insert(*verdict, file);
            }
            Err(e) => warnings.push(format!("{}: {e}", verdict.filename())),
        }
    }
    (set, warnings)
}

/// Sanitize the LOOSENING verdict (pure; #1207): run `approve.toml` through
/// bridle's fail-closed [`PolicyFile::verified_approves`] with the trusted
/// verifier. `None` (no root key this session) drops ALL approve entries with
/// one loud warning — an unverifiable grant is no grant. The narrowing
/// verdicts pass through untouched (see the module docs for why).
pub fn verify_approves(
    mut set: PolicySet,
    verifier: Option<&dyn ApproveVerifier>,
) -> (PolicySet, Vec<String>) {
    let Some(approves) = set.files.remove(&Verdict::Approve) else {
        return (set, Vec::new());
    };
    match verifier {
        Some(v) => {
            let (kept, warnings) = approves.verified_approves(v);
            set.files.insert(Verdict::Approve, kept);
            (set, warnings)
        }
        None => {
            let dropped = approves.exec.len() + approves.fs.len() + approves.net.len();
            let warnings = if dropped == 0 {
                Vec::new()
            } else {
                vec![format!(
                    "approve.toml: no root signing key available — {dropped} \
                     durable grant(s) dropped (fail-closed; the gate will prompt)"
                )]
            };
            (set, warnings)
        }
    }
}

/// Load the store from `<config dir>/ocap/*.toml` (the fs wrapper around
/// [`build_store`] + [`verify_approves`]). `config_path` is the config FILE
/// path (e.g. `~/.newt/config.toml`); the store lives beside it under `ocap/`.
/// A missing file = empty policy of that verdict. `root_verifying_key` is the
/// operator's 32-byte Ed25519 root public key (newt-identity) that approve
/// signatures must verify under; `None` fail-closes every durable grant.
pub fn load_store(
    config_path: &Path,
    root_verifying_key: Option<[u8; 32]>,
) -> (PolicySet, Vec<String>) {
    let dir = config_path.with_file_name("ocap");
    let files: Vec<(Verdict, Option<String>)> = VERDICTS
        .iter()
        .map(|&v| {
            let path = dir.join(v.filename());
            (v, std::fs::read_to_string(&path).ok())
        })
        .collect();
    let (set, mut warnings) = build_store(&files);
    let verifier = root_verifying_key.map(|verifying_key| Ed25519ApproveVerifier { verifying_key });
    let (set, mut sig_warnings) =
        verify_approves(set, verifier.as_ref().map(|v| v as &dyn ApproveVerifier));
    warnings.append(&mut sig_warnings);
    for warning in &mut warnings {
        warning.push_str("; ");
        warning.push_str(REPAIR_HINT);
    }
    (set, warnings)
}

/// The durable verdict for a permission request, if any (the one question the
/// gate asks the store). `None` ⇒ no durable policy ⇒ the gate prompts.
/// Matching is exact on the target string; a gate with richer matching
/// normalizes the target before calling.
pub fn evaluate_request(set: &PolicySet, kind: DenialKind, target: &str) -> Option<Verdict> {
    let mut request_policy = std::borrow::Cow::Borrowed(set);
    if kind == DenialKind::FsWrite {
        // The shared Fs class is mode-blind. Remove only read-only approvals;
        // narrowing verdicts retain their coverage and the shared precedence.
        if let Some(approve) = request_policy.to_mut().files.get_mut(&Verdict::Approve) {
            approve.fs.retain(|entry| entry.write);
        }
    }
    // Only authenticated OS spellings are equivalent. In particular, never
    // resolve a signed pathname against the mutable filesystem at match time.
    #[cfg(target_os = "macos")]
    if matches!(kind, DenialKind::FsRead | DenialKind::FsWrite) {
        let target = crate::fs_aliases::rewrite(target);
        return request_policy
            .files
            .iter()
            .filter(|(_, file)| {
                file.fs
                    .iter()
                    .any(|entry| crate::fs_aliases::rewrite(&entry.path) == target)
            })
            .map(|(verdict, _)| *verdict)
            .min_by_key(|verdict| verdict.precedence());
    }
    request_policy.evaluate(class_for(kind)?, target)
}

/// Fold a VERIFIED store's `approve.toml` entries into `(DenialKind, target)`
/// grants — the shape [`crate::widen_caveats`] / a session's `durable_grants`
/// set already consumes (#2524 item 1). Only the `Approve` verdict grants
/// anything (deny/ask/passkey never widen); callers MUST pass a `set` that has
/// already gone through [`verify_approves`] with a real verifier, so an
/// unsigned or bad-signature entry is never here to begin with — this
/// function does no signature checking itself, it only re-shapes what
/// survived verification.
///
/// A read-only `[[fs]]` entry (`write = false`/absent) yields one `FsRead`
/// grant; `write = true` yields both `FsRead` and `FsWrite` (a write grant
/// implies read, matching [`lock_fs_to_workspace`]'s convention). `exec`/`net`
/// entries map 1:1 onto their axis. This NEVER widens past what the signature
/// covers: it is a pure re-listing of exactly the verified entries, and the
/// caller composes the result with [`crate::widen_caveats`] (which only
/// inserts into an already-`Only` scope — an axis already `All` is untouched,
/// so folding can never turn a fenced axis open).
pub fn approved_grants(set: &PolicySet) -> Vec<(DenialKind, String)> {
    let Some(approve) = set.files.get(&Verdict::Approve) else {
        return Vec::new();
    };
    let mut grants = Vec::new();
    for entry in &approve.exec {
        grants.push((DenialKind::Exec, entry.target.clone()));
    }
    for entry in &approve.fs {
        grants.push((DenialKind::FsRead, entry.path.clone()));
        if entry.write {
            grants.push((DenialKind::FsWrite, entry.path.clone()));
        }
    }
    for entry in &approve.net {
        grants.push((DenialKind::Net, entry.host.clone()));
    }
    grants
}

/// Bless an `approve.toml` (pure; the write half of #1207): re-sign EVERY entry
/// with the operator's root key — the ceremony behind `newt doctor --sign-ocap`,
/// where a present human explicitly vouches for the file as it stands (that
/// presence + explicit command IS the authorization; hand-edited entries become
/// valid grants here and nowhere else).
///
/// The danger invariant binds even here: a high-danger target (per the caller's
/// danger table, passed as a predicate per the bridle contract) is REFUSED a
/// signature and reported — `validate_approve` is the contract's mandatory
/// pre-persist check, and blessing must not launder an interpreter grant into
/// the store. Refused entries keep whatever `sig` they had (an invalid one
/// still drops at load, fail-closed).
///
/// Returns `(signed_count, refused)` — refusal strings are operator-facing.
pub fn sign_approves(
    file: &mut PolicyFile,
    is_high_danger: impl Fn(CapabilityClass, &str) -> bool,
    sign: impl Fn(&[u8]) -> [u8; 64],
) -> (usize, Vec<String>) {
    let mut signed = 0;
    let mut refused = Vec::new();
    let mut bless =
        |class: CapabilityClass, what: &str, payload: Vec<u8>, sig: &mut Option<String>| {
            match PolicySet::validate_approve(class, what, &is_high_danger) {
                Ok(()) => {
                    *sig = Some(sign_entry(&payload, &sign));
                    signed += 1;
                }
                Err(reason) => refused.push(reason),
            }
        };
    for e in &mut file.exec {
        let payload = e.signing_payload();
        let target = e.target.clone();
        bless(CapabilityClass::Exec, &target, payload, &mut e.sig);
    }
    for e in &mut file.fs {
        let payload = e.signing_payload();
        let path = e.path.clone();
        bless(CapabilityClass::Fs, &path, payload, &mut e.sig);
    }
    for e in &mut file.net {
        let payload = e.signing_payload();
        let host = e.host.clone();
        bless(CapabilityClass::Net, &host, payload, &mut e.sig);
    }
    (signed, refused)
}

/// One capability + target the interactive gate's `AllowPermanent` answer
/// wants to persist (#2535/#2524 PR1 — every "permanently allow" kind, not
/// just net).
#[derive(Debug, Clone)]
pub enum ApproveEntry {
    Exec { target: String },
    Fs { path: String, write: bool },
    Net { host: String },
}

impl ApproveEntry {
    pub fn class(&self) -> CapabilityClass {
        match self {
            Self::Exec { .. } => CapabilityClass::Exec,
            Self::Fs { .. } => CapabilityClass::Fs,
            Self::Net { .. } => CapabilityClass::Net,
        }
    }

    /// The target string this entry is keyed on (command, path, or host).
    pub fn target(&self) -> &str {
        match self {
            Self::Exec { target } => target,
            Self::Fs { path, .. } => path,
            Self::Net { host } => host,
        }
    }
}

/// Sign one canonical entry payload — the single seam both [`sign_approves`]
/// (bulk re-bless) and [`persist_approve`] (one freshly-answered grant) route
/// through, so there is exactly one place that turns bytes into a hex `sig`.
pub fn sign_entry(payload: &[u8], sign: &impl Fn(&[u8]) -> [u8; 64]) -> String {
    agent_bridle::policy::hex_encode(&sign(payload))
}

/// Append ONE operator-answered grant to `approve.toml` under the config file
/// lock, signed in-session at the moment of the answer (#2535/#2524 PR1: the
/// writer behind "allow permanently" for every kind, not just net).
///
/// Refuses — no lock taken, no write — a high-danger target per
/// `is_high_danger` (the same [`PolicySet::validate_approve`] invariant
/// `sign_approves`/`newt doctor --sign-ocap` already enforce, now checked
/// BEFORE the entry ever reaches disk rather than after), and an `Fs` target
/// that is not an absolute, `..`-free path (#2524 round 2 item 2: a relative
/// `read_file path="../../"` must never become a durable `/` grant).
///
/// Returns whether the pre-existing on-disk text (read under the lock, before
/// this call's own write) contained a `#` comment — NOT the updated
/// [`PolicyFile`] itself: the caller must NOT fold the file this function
/// just wrote straight into a live [`PolicySet`] (#2524 round 2 item 1,
/// BLOCKER): this function performs no signature verification of whatever
/// ELSE was already on disk, so folding its return value would launder a
/// pre-existing unsigned/tampered entry into live authority the moment any
/// other grant is persisted. The caller must reload through the verifying
/// path ([`load_store`]) instead.
///
/// The `bool` (#2524 follow-up item 3) exists because re-serialising through
/// [`PolicyFile::to_toml`] drops any hand-written TOML comment — `newt doctor
/// --sign-ocap` already says so; the interactive writer did not. A crude
/// `contains('#')` scan (not a TOML-comment parser) is deliberately
/// conservative: a `#` inside a quoted string value is vanishingly rare in
/// this file's shape (bare paths/commands/hosts) and a false positive here
/// only costs one extra notice line, never a wrong grant.
pub fn persist_approve(
    config_path: &Path,
    entry: ApproveEntry,
    is_high_danger: impl Fn(CapabilityClass, &str) -> bool,
    sign: impl Fn(&[u8]) -> [u8; 64],
) -> anyhow::Result<bool> {
    let entry = normalize_fs_target(entry)?;
    PolicySet::validate_approve(entry.class(), entry.target(), &is_high_danger)
        .map_err(anyhow::Error::msg)?;

    let (destination, _lock) = lock_approve_file(config_path)?;
    let text = match std::fs::read_to_string(destination.as_path()) {
        Ok(text) => text,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(e) => return Err(e.into()),
    };
    let had_comments = text.contains('#');
    let mut file = PolicyFile::parse(&text).map_err(|e| anyhow::anyhow!(e))?;

    match entry {
        ApproveEntry::Exec { target } => {
            let e = ExecEntry {
                target,
                ..Default::default()
            };
            let sig = sign_entry(&e.signing_payload(), &sign);
            file.exec.push(ExecEntry {
                sig: Some(sig),
                ..e
            });
        }
        ApproveEntry::Fs { path, write } => {
            let e = FsEntry {
                path,
                write,
                ..Default::default()
            };
            let sig = sign_entry(&e.signing_payload(), &sign);
            file.fs.push(FsEntry {
                sig: Some(sig),
                ..e
            });
        }
        ApproveEntry::Net { host } => {
            let e = NetEntry {
                host,
                ..Default::default()
            };
            let sig = sign_entry(&e.signing_payload(), &sign);
            file.net.push(NetEntry {
                sig: Some(sig),
                ..e
            });
        }
    }

    let toml = file.to_toml().map_err(|e| anyhow::anyhow!(e))?;
    destination.atomic_write(toml.as_bytes())?;
    Ok(had_comments)
}

/// Resolve `approve.toml`'s path beside `config_path` and take its write
/// lock — the ONE lock-acquisition route for every approve.toml writer
/// (#2524 round 2 item 4): [`persist_approve`] (the interactive "allow
/// permanently" writer) and `newt doctor --sign-ocap` (the bulk re-sign
/// ceremony, in `newt-cli`) both go through this instead of each taking its
/// own lock, so the two can never interleave a read-modify-write. Creates the
/// `ocap/` directory if missing. The caller reads/parses `destination`,
/// mutates its own [`PolicyFile`], and writes back with
/// [`crate::atomic_fs::ResolvedPath::atomic_write`] before the returned
/// [`crate::atomic_fs::LockGuard`] drops.
pub fn lock_approve_file(
    config_path: &Path,
) -> anyhow::Result<(crate::atomic_fs::ResolvedPath, crate::atomic_fs::LockGuard)> {
    let dir = config_path.with_file_name("ocap");
    std::fs::create_dir_all(&dir)?;
    let path = dir.join(Verdict::Approve.filename());
    let destination = crate::atomic_fs::ResolvedPath::resolve(&path)?;
    let lock = crate::atomic_fs::acquire_lock(&destination.lock_path())?;
    Ok((destination, lock))
}

/// Normalize an [`ApproveEntry::Fs`] target before it ever reaches
/// `validate_approve` (#2524 round 2 item 2): require an absolute path, run
/// it through the SAME [`crate::caveats::lexically_normalize`] the read/write
/// fences already use (one normalizer, not a second one for the durable
/// store), and refuse any `..` that survives — a relative or climbing target
/// like `../../` must never durably widen to whatever directory happens to
/// contain it. `Exec`/`Net` entries pass through untouched.
fn normalize_fs_target(entry: ApproveEntry) -> anyhow::Result<ApproveEntry> {
    let ApproveEntry::Fs { path, write } = entry else {
        return Ok(entry);
    };
    Ok(ApproveEntry::Fs {
        path: normalize_fs_path(&path)?,
        write,
    })
}

/// The string-level normalization [`normalize_fs_target`] applies to an
/// `[[fs]]` target: require an absolute path, run it through the SAME
/// [`crate::caveats::lexically_normalize`] the read/write fences use, and
/// refuse any `..` that survives. Exposed `pub` (#2524 follow-up item 2) so
/// the gate can classify danger and phrase a refusal against the SAME
/// normalized target the writer would actually persist — never a second
/// copy of this normalizer, and never a danger decision made against a raw
/// `/ws/..` that the writer would have turned into `/`.
pub fn normalize_fs_path(path: &str) -> anyhow::Result<String> {
    if !Path::new(path).is_absolute() {
        anyhow::bail!("permanent allow refused: fs target `{path}` must be an absolute path");
    }
    let normalized = crate::caveats::lexically_normalize(path);
    if normalized
        .components()
        .any(|c| matches!(c, std::path::Component::ParentDir))
    {
        anyhow::bail!("permanent allow refused: fs target `{path}` escapes above its root");
    }
    Ok(normalized.to_string_lossy().into_owned())
}

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

    fn store(approve: &str, deny: &str) -> PolicySet {
        build_store(&[
            (Verdict::Approve, Some(approve.to_string())),
            (Verdict::Deny, Some(deny.to_string())),
        ])
        .0
    }

    #[test]
    fn class_mapping_covers_the_durable_axes() {
        assert_eq!(class_for(DenialKind::Exec), Some(CapabilityClass::Exec));
        assert_eq!(class_for(DenialKind::FsRead), Some(CapabilityClass::Fs));
        assert_eq!(class_for(DenialKind::FsWrite), Some(CapabilityClass::Fs));
        assert_eq!(class_for(DenialKind::Net), Some(CapabilityClass::Net));
    }

    #[test]
    fn evaluate_applies_the_contract_precedence() {
        // A durable approve pre-answers a prompt; a durable deny outranks it
        // (deny > … > approve — bridle's precedence law).
        let s = store(
            "[[exec]]\ntarget = \"cargo\"\n",
            "[[exec]]\ntarget = \"rm\"\n",
        );
        assert_eq!(
            evaluate_request(&s, DenialKind::Exec, "cargo"),
            Some(Verdict::Approve)
        );
        assert_eq!(
            evaluate_request(&s, DenialKind::Exec, "rm"),
            Some(Verdict::Deny)
        );
        // No durable policy → None → the gate prompts.
        assert_eq!(evaluate_request(&s, DenialKind::Exec, "python3"), None);
        // Class-scoped: an exec approve doesn't answer an fs question.
        assert_eq!(evaluate_request(&s, DenialKind::FsWrite, "cargo"), None);
    }

    #[test]
    fn fs_axis_matches_both_read_and_write_against_the_fs_class() {
        let s = build_store(&[(
            Verdict::Approve,
            Some("[[fs]]\npath = \"/ws\"\nwrite = true\n".to_string()),
        )])
        .0;
        assert_eq!(
            evaluate_request(&s, DenialKind::FsRead, "/ws"),
            Some(Verdict::Approve)
        );
        assert_eq!(
            evaluate_request(&s, DenialKind::FsWrite, "/ws"),
            Some(Verdict::Approve)
        );
    }

    /// Exercise the actual entry signatures and verifier without a filesystem
    /// or operator key: every test gets a disposable in-memory root key.
    fn signed_approve_store(approve: &str) -> PolicySet {
        let key = agent_mesh_protocol::UserKey::generate();
        let mut file = PolicyFile::parse(approve).unwrap();
        let (signed, refused) = sign_approves(
            &mut file,
            |_, _| false,
            |payload| key.sign(payload).to_bytes(),
        );
        assert_eq!(signed, file.exec.len() + file.fs.len() + file.net.len());
        assert!(refused.is_empty());
        let (set, warnings) = build_store(&[(Verdict::Approve, Some(file.to_toml().unwrap()))]);
        assert!(warnings.is_empty(), "{warnings:?}");
        let verifier = Ed25519ApproveVerifier {
            verifying_key: key.public().as_bytes(),
        };
        let (set, warnings) = verify_approves(set, Some(&verifier));
        assert!(warnings.is_empty(), "{warnings:?}");
        set
    }

    #[test]
    fn signed_readonly_fs_approval_does_not_cover_a_write_request() {
        for mode in ["", "write = false\n"] {
            let set = signed_approve_store(&format!(
                "[[fs]]\npath = \"/fixture/notes.txt\"\n{mode}\
                 [[fs]]\npath = \"/fixture/writable.txt\"\nwrite = true\n"
            ));
            assert_eq!(
                evaluate_request(&set, DenialKind::FsRead, "/fixture/notes.txt"),
                Some(Verdict::Approve),
                "a verified read grant must remain usable"
            );
            assert_eq!(
                evaluate_request(&set, DenialKind::FsWrite, "/fixture/writable.txt"),
                Some(Verdict::Approve),
                "a different target's write grant remains usable only there"
            );
            assert_eq!(
                evaluate_request(&set, DenialKind::FsWrite, "/fixture/notes.txt"),
                None,
                "a read-only signature must not pre-answer a write request"
            );
        }
    }

    #[test]
    fn signed_fs_write_approval_covers_both_modes_regardless_of_entry_order() {
        for modes in [[false, true], [true, false]] {
            let set = signed_approve_store(&format!(
                "[[fs]]\npath = \"/fixture/notes.txt\"\nwrite = {}\n\
                 [[fs]]\npath = \"/fixture/notes.txt\"\nwrite = {}\n",
                modes[0], modes[1]
            ));
            for kind in [DenialKind::FsRead, DenialKind::FsWrite] {
                assert_eq!(
                    evaluate_request(&set, kind, "/fixture/notes.txt"),
                    Some(Verdict::Approve)
                );
                assert_eq!(evaluate_request(&set, kind, "/fixture/other.txt"), None);
            }
        }
    }

    #[test]
    fn readonly_fs_restrictions_still_outrank_a_signed_write_approval() {
        for verdict in [Verdict::Deny, Verdict::Passkey, Verdict::Ask] {
            let mut set =
                signed_approve_store("[[fs]]\npath = \"/fixture/notes.txt\"\nwrite = true\n");
            set.files.insert(
                verdict,
                PolicyFile::parse("[[fs]]\npath = \"/fixture/notes.txt\"\n").unwrap(),
            );
            for kind in [DenialKind::FsRead, DenialKind::FsWrite] {
                assert_eq!(
                    evaluate_request(&set, kind, "/fixture/notes.txt"),
                    Some(verdict),
                    "filtering read-only approvals must not weaken narrowing verdicts"
                );
            }
        }
    }

    #[test]
    fn a_malformed_file_is_skipped_loudly_not_fatal() {
        let (set, warnings) = build_store(&[
            (
                Verdict::Approve,
                Some("[[exec]]\ntarget = \"cargo\"\n".to_string()),
            ),
            (
                Verdict::Deny,
                Some("[[exec]]\ntarget=\"rm\"\nbad_key=1\n".to_string()),
            ),
        ]);
        // The good file loaded…
        assert_eq!(
            evaluate_request(&set, DenialKind::Exec, "cargo"),
            Some(Verdict::Approve)
        );
        // …the malformed one is absent (not fatal) and reported.
        assert!(
            warnings.iter().any(|w| w.contains("deny.toml")),
            "{warnings:?}"
        );
        assert_eq!(evaluate_request(&set, DenialKind::Exec, "rm"), None);
    }

    #[test]
    fn missing_files_yield_an_empty_store() {
        let (set, warnings) = build_store(&[(Verdict::Approve, None), (Verdict::Deny, None)]);
        assert!(warnings.is_empty());
        assert_eq!(evaluate_request(&set, DenialKind::Exec, "anything"), None);
    }

    /// #2524 item 1: `approved_grants` re-shapes exactly the Approve verdict's
    /// entries, one `FsRead` per `[[fs]]` entry plus a second `FsWrite` only
    /// when `write = true` (a write grant implies read); it never reads
    /// deny/ask/passkey (those never grant anything).
    #[test]
    fn approved_grants_lists_approve_entries_and_never_the_narrowing_verdicts() {
        let (set, warnings) = build_store(&[
            (
                Verdict::Approve,
                Some(
                    "[[exec]]\ntarget = \"cargo\"\n\
                     [[fs]]\npath = \"/ro\"\n\
                     [[fs]]\npath = \"/rw\"\nwrite = true\n\
                     [[net]]\nhost = \"example.test\"\n"
                        .to_string(),
                ),
            ),
            (
                Verdict::Deny,
                Some("[[exec]]\ntarget = \"rm\"\n".to_string()),
            ),
        ]);
        assert!(warnings.is_empty(), "{warnings:?}");
        let mut grants = approved_grants(&set);
        grants.sort();
        let mut expected = vec![
            (DenialKind::Exec, "cargo".to_string()),
            (DenialKind::FsRead, "/ro".to_string()),
            (DenialKind::FsRead, "/rw".to_string()),
            (DenialKind::FsWrite, "/rw".to_string()),
            (DenialKind::Net, "example.test".to_string()),
        ];
        expected.sort();
        assert_eq!(grants, expected, "must never include the denied `rm`");
    }

    #[test]
    fn approved_grants_of_an_empty_or_approve_less_store_is_empty() {
        assert!(approved_grants(&PolicySet::default()).is_empty());
        let (set, warnings) = build_store(&[(
            Verdict::Deny,
            Some("[[exec]]\ntarget = \"rm\"\n".to_string()),
        )]);
        assert!(warnings.is_empty());
        assert!(approved_grants(&set).is_empty());
    }

    /// The pure verifier double: accepts exactly one signature value.
    struct SigEquals(&'static [u8]);
    impl ApproveVerifier for SigEquals {
        fn verify(&self, _payload: &[u8], sig: &[u8]) -> Result<(), String> {
            (sig == self.0).then_some(()).ok_or("bad signature".into())
        }
    }

    /// #1207 asymmetry law: an unsigned approve is DROPPED (fail-closed, loud);
    /// an unsigned deny SURVIVES (narrowing verdicts load unsigned — dropping a
    /// deny over a missing sig would widen).
    #[test]
    fn unsigned_approve_drops_but_unsigned_deny_survives() {
        let (set, _) = build_store(&[
            (
                Verdict::Approve,
                Some("[[exec]]\ntarget = \"git\"\n".to_string()),
            ),
            (
                Verdict::Deny,
                Some("[[exec]]\ntarget = \"rm\"\n".to_string()),
            ),
        ]);
        let (set, warnings) = verify_approves(set, Some(&SigEquals(&[1])));
        // The unsigned approve is gone: no durable grant, the gate prompts.
        assert_eq!(evaluate_request(&set, DenialKind::Exec, "git"), None);
        assert!(
            warnings
                .iter()
                .any(|w| w.contains("git") && w.contains("unsigned")),
            "{warnings:?}"
        );
        // The unsigned deny still binds.
        assert_eq!(
            evaluate_request(&set, DenialKind::Exec, "rm"),
            Some(Verdict::Deny)
        );
    }

    /// #1207: a validly-signed approve survives verification and answers the
    /// gate; a bad signature drops.
    #[test]
    fn signed_approve_survives_and_bad_sig_drops() {
        let (set, _) = build_store(&[(
            Verdict::Approve,
            Some(
                "[[exec]]\ntarget = \"cargo\"\nsig = \"0a\"\n\
                 [[net]]\nhost = \"crates.io\"\nsig = \"ff\"\n"
                    .to_string(),
            ),
        )]);
        let (set, warnings) = verify_approves(set, Some(&SigEquals(&[0x0a])));
        assert_eq!(
            evaluate_request(&set, DenialKind::Exec, "cargo"),
            Some(Verdict::Approve),
            "the validly-signed grant answers the gate"
        );
        assert_eq!(evaluate_request(&set, DenialKind::Net, "crates.io"), None);
        assert_eq!(warnings.len(), 1, "{warnings:?}");
    }

    /// #1207 fail-closed floor: with NO root key, every durable grant drops
    /// (one loud warning) — an unverifiable grant is no grant. An empty
    /// approve file warns nothing.
    #[test]
    fn no_root_key_drops_all_approves_fail_closed() {
        let (set, _) = build_store(&[(
            Verdict::Approve,
            Some("[[exec]]\ntarget = \"cargo\"\nsig = \"0a\"\n".to_string()),
        )]);
        let (set, warnings) = verify_approves(set, None);
        assert_eq!(evaluate_request(&set, DenialKind::Exec, "cargo"), None);
        assert_eq!(warnings.len(), 1);
        assert!(warnings[0].contains("no root signing key"), "{warnings:?}");

        let (empty, warnings) = verify_approves(PolicySet::default(), None);
        assert!(warnings.is_empty(), "nothing to drop, nothing to warn");
        assert_eq!(evaluate_request(&empty, DenialKind::Exec, "cargo"), None);
    }

    /// #1207 write half: blessing signs every non-dangerous entry with the
    /// canonical payload (round-trips through the verify path), REFUSES
    /// high-danger targets (the contract's validate_approve check), and is
    /// idempotent (re-blessing re-signs).
    #[test]
    fn sign_approves_blesses_safe_entries_and_refuses_high_danger() {
        let mut file = PolicyFile::parse(
            "[[exec]]\ntarget = \"cargo\"\n\
             [[exec]]\ntarget = \"bash\"\n\
             [[fs]]\npath = \"/ws\"\nwrite = true\n",
        )
        .unwrap();
        let is_high = |class: CapabilityClass, target: &str| {
            class == CapabilityClass::Exec && target == "bash"
        };
        // A "signature" the double can check: payload length as the first byte.
        let sign = |payload: &[u8]| {
            let mut sig = [0u8; 64];
            sig[0] = payload.len() as u8;
            sig
        };
        let (signed, refused) = sign_approves(&mut file, is_high, sign);
        assert_eq!(signed, 2, "cargo + the fs path");
        assert_eq!(refused.len(), 1);
        assert!(refused[0].contains("bash"), "{refused:?}");
        assert!(file.exec[0].sig.is_some());
        assert!(file.exec[1].sig.is_none(), "the interpreter stays unsigned");
        assert!(file.fs[0].sig.is_some());

        // The blessed file survives the verify path with the matching checker;
        // the refused (unsigned) interpreter entry drops fail-closed.
        struct LenChecker;
        impl ApproveVerifier for LenChecker {
            fn verify(&self, payload: &[u8], sig: &[u8]) -> Result<(), String> {
                (sig.first() == Some(&(payload.len() as u8)))
                    .then_some(())
                    .ok_or("mismatch".into())
            }
        }
        let mut set = PolicySet::default();
        set.files.insert(Verdict::Approve, file);
        let (set, warnings) = verify_approves(set, Some(&LenChecker));
        assert_eq!(
            evaluate_request(&set, DenialKind::Exec, "cargo"),
            Some(Verdict::Approve)
        );
        assert_eq!(
            evaluate_request(&set, DenialKind::FsWrite, "/ws"),
            Some(Verdict::Approve)
        );
        assert_eq!(evaluate_request(&set, DenialKind::Exec, "bash"), None);
        assert_eq!(warnings.len(), 1, "{warnings:?}");
    }

    fn key() -> agent_mesh_protocol::UserKey {
        agent_mesh_protocol::UserKey::generate()
    }

    /// #2524 round 2 item 2, RED FIRST: a relative/climbing `read_file
    /// path="../../"` must never durably widen — `persist_approve` must
    /// refuse it (nothing written) rather than let it become a durable grant
    /// on whatever directory happens to be two levels up from the CWD at
    /// evaluation time.
    #[test]
    fn persist_approve_refuses_a_relative_fs_target_and_writes_nothing() {
        let dir = tempfile::TempDir::new().unwrap();
        let config = dir.path().join("config.toml");
        let k = key();
        let result = persist_approve(
            &config,
            ApproveEntry::Fs {
                path: "../../".to_string(),
                write: false,
            },
            |_, _| false,
            |payload| k.sign(payload).to_bytes(),
        );
        assert!(result.is_err(), "a relative fs target must be refused");
        assert!(
            !dir.path().join("ocap").join("approve.toml").exists(),
            "nothing should be written"
        );
    }

    /// Same regression: an ABSOLUTE path that still climbs above its root
    /// after normalization (`/a/../../b`) must also be refused, not silently
    /// collapsed to `/b` and durably granted.
    #[test]
    fn persist_approve_refuses_an_absolute_path_that_still_climbs_above_its_root() {
        let dir = tempfile::TempDir::new().unwrap();
        let config = dir.path().join("config.toml");
        let k = key();
        let result = persist_approve(
            &config,
            ApproveEntry::Fs {
                path: "/a/../../b".to_string(),
                write: false,
            },
            |_, _| false,
            |payload| k.sign(payload).to_bytes(),
        );
        assert!(
            result.is_err(),
            "a climbing absolute target must be refused"
        );
        assert!(!dir.path().join("ocap").join("approve.toml").exists());
    }

    /// An absolute path with an internal, fully-contained `..` (`/ws/x/../y`)
    /// is legitimate — it normalizes to `/ws/y` and must be signed as that
    /// normalized, unambiguous form, never the raw string.
    #[test]
    fn persist_approve_normalizes_a_contained_relative_segment_before_signing() {
        let dir = tempfile::TempDir::new().unwrap();
        let config = dir.path().join("config.toml");
        let k = key();
        // A platform-absolute path: `/ws` has no drive on Windows. Compare the
        // PARSED entry, since TOML escapes Windows backslashes in the text.
        let ws = dir.path().join("ws");
        let raw = ws.join("x").join("..").join("y");
        persist_approve(
            &config,
            ApproveEntry::Fs {
                path: raw.to_string_lossy().into_owned(),
                write: false,
            },
            |_, _| false,
            |payload| k.sign(payload).to_bytes(),
        )
        .unwrap();
        let text = std::fs::read_to_string(dir.path().join("ocap").join("approve.toml")).unwrap();
        let file = PolicyFile::parse(&text).unwrap();
        assert_eq!(file.fs.len(), 1, "{text}");
        assert_eq!(
            std::path::Path::new(&file.fs[0].path),
            ws.join("y").as_path(),
            "{text}"
        );
    }

    /// #2524 round 2 item 4: `persist_approve` and `newt doctor --sign-ocap`
    /// share ONE lock route (`lock_approve_file`) — a lock already held on
    /// `approve.toml` (simulating a concurrent `--sign-ocap` or another
    /// session's grant) must make `persist_approve` fail cleanly rather than
    /// interleave a read-modify-write with the other holder.
    #[test]
    fn persist_approve_fails_cleanly_when_the_approve_lock_is_already_held() {
        let dir = tempfile::TempDir::new().unwrap();
        let config = dir.path().join("config.toml");
        // Take the SAME lock `persist_approve` would take, via the shared
        // route, before calling it.
        let (_destination, _held) = lock_approve_file(&config).unwrap();
        let k = key();
        let result = persist_approve(
            &config,
            ApproveEntry::Exec {
                target: "cargo".to_string(),
            },
            |_, _| false,
            |payload| k.sign(payload).to_bytes(),
        );
        assert!(
            result.is_err(),
            "a held lock must fail the write cleanly, not interleave"
        );
    }
}