openmoat 0.27.0

Policy checks for AI coding agents: decides allow, defer, review or deny for each tool call the hook of Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot CLI and seven more agents reports, configures Claude Code's, Codex's and Cursor's own OS sandboxes from the same policy, and keeps a local audit log.
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
//! Human approvals that outlive one prompt.
//!
//! Two files under `~/.moat`, both pinned by the policy lock so an agent cannot
//! grant itself anything:
//! - `approvals.json`: session grants, an exact command or exact files for one host
//!   session, valid for [`GRANT_TTL_MS`] after they are written; a command only in
//!   the project it was approved in;
//! - `policy.d/approved.yaml`: standing allow rules appended by `moat allow --always`
//!   and `--site`, and the directories `--dir` allowed (`dirs.rs`), merged into the
//!   user policy at load time so `policy.yaml` is never rewritten; each lasts until
//!   removed, or until the end `--for` gave it (`expiry.rs`).

use std::collections::BTreeMap;
use std::fs;
use std::path::Path;

use anyhow::{Context as _, Result, bail};
use openmoat_core::{Action, Policy, RuleGroup};
use serde::{Deserialize, Serialize};

use crate::home::{Home, write_private};
use crate::time;

mod dirs;
mod expiry;
mod reviewed;
pub use dirs::{DirGrant, Places};
pub use expiry::{State, Window, parse_for, summary as expiry_summary};
pub use reviewed::{approvable, describe, files};

/// Version 2 grants an [`Action`]; version 1 granted only a `command` string.
const GRANTS_VERSION: u32 = 2;
const OVERLAY_VERSION: u32 = 1;
/// The overlay's version while an entry in it ends ([`Overlay::expires`]): a
/// release that does not know the field refuses the file, failing closed,
/// rather than reading every entry as permanent.
const EXPIRING_OVERLAY_VERSION: u32 = 2;
pub const OVERLAY_PREFIX: &str = "approved-";
/// How long a session grant stays valid. Hosts do not tell OpenMoat when a session
/// ends, so a fixed lifetime is what bounds a grant.
pub const GRANT_TTL_MS: i64 = 24 * 60 * 60 * 1000;

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Grant {
    pub host: String,
    pub session_id: String,
    /// What is approved, as [`approvable`] spells it.
    pub action: Action,
    /// Milliseconds since the epoch. A grant written without one reads as 0,
    /// long expired: a grant whose age is unknown must not stay valid forever.
    #[serde(default)]
    pub granted_at_ms: i64,
    /// The id of the newest audit event when the grant was written (0 for an
    /// empty log): it saw every event up to this one. Ids only grow, so this
    /// orders the grant against later calls even if the clock steps back. A
    /// grant written by an older build has none and is ordered by time.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub audit_row: Option<i64>,
    /// Also answers every other session-taint review of this host session that
    /// comes from untrusted content, until the session reads untrusted content
    /// again (`moat allow --last`, answer `s`). Never a secret taint. A build
    /// that does not know the field reads it as a grant for `action` alone.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub covers_taint: bool,
    /// The project the grant was approved in ([`project_of`]): a shell grant,
    /// and one that [`covers_taint`](Self::covers_taint), applies only to calls
    /// in it, since the same command means something else in another
    /// repository. A file grant names absolute paths and needs none. `None` for
    /// a grant an earlier release wrote: such a shell or taint grant applies
    /// nowhere ([`Grant::unbound`]) until a person approves it again.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub project: Option<String>,
    /// Where its files resolved when approved (empty: each was itself); it holds
    /// only while they still do, so a file swapped for a symlink needs review again.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub real: Vec<String>,
}

/// The project a call in `cwd` belongs to, as grants record it: the
/// repository root, else `cwd` itself ([`crate::project::root_of`]), with its
/// symlinks resolved when it exists so either spelling of it is the same
/// project. `home` is the person's home directory.
#[must_use]
pub fn project_of(cwd: &Path, home: &Path) -> String {
    let root = crate::project::root_of(cwd, home).unwrap_or_else(|| cwd.to_path_buf());
    let real = fs::canonicalize(&root).unwrap_or(root);
    crate::context::path_string(&real)
}

/// [`project_of`] the working directory of a call evaluated in `ctx`.
#[must_use]
pub fn project_in(ctx: &openmoat_core::EvalContext) -> String {
    project_of(Path::new(&ctx.cwd), Path::new(&ctx.home))
}

/// A version 1 grant: a shell command.
#[derive(Deserialize)]
struct GrantV1 {
    host: String,
    session_id: String,
    command: String,
    #[serde(default)]
    granted_at_ms: i64,
}

#[derive(Deserialize)]
struct GrantsV1 {
    entries: Vec<GrantV1>,
}

impl Grant {
    /// Valid for [`GRANT_TTL_MS`] from its creation. A creation time in the
    /// future (a clock set back, a hand edit) is not valid either.
    #[must_use]
    pub fn active(&self, now_ms: i64) -> bool {
        (0..GRANT_TTL_MS).contains(&now_ms.saturating_sub(self.granted_at_ms))
    }

    /// Whether it needs a project to apply and names none: written by an
    /// earlier release, so it applies nowhere and must be approved again.
    #[must_use]
    pub fn unbound(&self) -> bool {
        self.needs_project() && self.project.is_none()
    }

    fn needs_project(&self) -> bool {
        self.covers_taint || matches!(self.action, Action::Shell { .. })
    }

    /// Whether it applies to a call in `project` ([`project_of`]).
    fn applies_in(&self, project: &str) -> bool {
        !self.needs_project() || self.project.as_deref() == Some(project)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Grants {
    pub version: u32,
    pub entries: Vec<Grant>,
}

impl Default for Grants {
    fn default() -> Self {
        Self {
            version: GRANTS_VERSION,
            entries: Vec::new(),
        }
    }
}

impl Grants {
    /// Missing file means no grants; a malformed or newer file is an error.
    pub fn load(path: &Path) -> Result<Self> {
        if !path.exists() {
            return Ok(Self::default());
        }
        let text =
            fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
        Self::parse(&text, path)
    }

    /// [`Grants::load`] of `home`'s grants, from the bytes the lock check
    /// kept when it kept them ([`Home::load_state`]).
    pub fn load_in(home: &Home) -> Result<Self> {
        home.load_state(&home.grants_path(), Self::parse, Self::load)
    }

    /// The grants in `text`, read from `path` (named in errors).
    pub fn parse(text: &str, path: &Path) -> Result<Self> {
        let parse = || format!("parsing {}", path.display());
        let value: serde_json::Value = serde_json::from_str(text).with_context(parse)?;
        match value.get("version").and_then(serde_json::Value::as_u64) {
            Some(1) => {
                let old: GrantsV1 = serde_json::from_value(value).with_context(parse)?;
                let entries = old.entries.into_iter().map(|g| Grant {
                    host: g.host,
                    session_id: g.session_id,
                    action: Action::Shell {
                        command: g.command.trim().to_owned(),
                    },
                    granted_at_ms: g.granted_at_ms,
                    audit_row: None,
                    covers_taint: false,
                    project: None,
                    real: Vec::new(),
                });
                Ok(Self {
                    version: GRANTS_VERSION,
                    entries: entries.collect(),
                })
            }
            Some(2) => serde_json::from_value(value).with_context(parse),
            version => bail!(
                "{} has version {}; this build supports {GRANTS_VERSION}",
                path.display(),
                version.map_or_else(|| "none".to_owned(), |v| v.to_string())
            ),
        }
    }

    /// Write the file, dropping grants that expired by `now_ms` so it does not
    /// grow without bound.
    pub fn save(&mut self, path: &Path, now_ms: i64) -> Result<()> {
        self.entries.retain(|g| g.active(now_ms));
        write_private(
            path,
            (serde_json::to_string_pretty(self)? + "\n").as_bytes(),
        )
    }

    /// Grant `action` (spelled by [`approvable`]) to the host session in
    /// `project` ([`project_of`]) as of `now_ms`, having seen the audit log up
    /// to `audit_row`; granting it again restarts its lifetime and moves it to
    /// `project`.
    pub fn grant(
        &mut self,
        scope: Scope<'_>,
        action: &Action,
        now_ms: i64,
        audit_row: Option<i64>,
    ) {
        // The same grant made earlier in this project, or by an earlier
        // release in none, is replaced; one in another project stays.
        self.entries.retain(|g| {
            !(scope.owns(g)
                && g.action == *action
                && g.project.as_deref().is_none_or(|p| p == scope.project))
        });
        self.entries.push(Grant {
            host: scope.host.to_owned(),
            session_id: scope.session_id.to_owned(),
            action: action.clone(),
            granted_at_ms: now_ms,
            audit_row,
            covers_taint: false,
            project: Some(scope.project.to_owned()),
            // Unresolvable now: recorded as itself, but no lookup matches
            // while it stays unresolvable ([`Grants::newest`]).
            real: reviewed::real_files(action).unwrap_or_default(),
        });
    }

    /// Exact match of `action` (spelled by [`approvable`]) for this host session
    /// among grants still valid at `now_ms` that apply in the scope's project;
    /// no prefix or glob semantics. A call without a session id never
    /// matches: every such call shares the placeholder id, so a grant for it
    /// would hold in every session.
    #[must_use]
    pub fn matches(&self, scope: Scope<'_>, action: &Action, now_ms: i64) -> bool {
        self.granted_at(scope, action, now_ms).is_some()
    }

    /// When the grant [`Grants::matches`] finds was made, if there is one.
    #[must_use]
    pub fn granted_at(&self, scope: Scope<'_>, action: &Action, now_ms: i64) -> Option<i64> {
        self.newest(scope, action, now_ms).map(|g| g.granted_at_ms)
    }

    /// The newest grant [`Grants::matches`] finds whose files resolve as approved.
    #[must_use]
    pub fn newest(&self, scope: Scope<'_>, action: &Action, now_ms: i64) -> Option<&Grant> {
        if openmoat_hosts::is_unknown_session(scope.session_id) {
            return None;
        }
        let real = reviewed::real_files(action)?;
        self.active(now_ms)
            .filter(|g| scope.owns(g) && g.action == *action && g.applies_in(scope.project))
            .filter(|g| g.real == real)
            .max_by_key(|g| g.granted_at_ms)
    }

    /// Make the grant for `action` in this host session also answer the
    /// session's other taint reviews from untrusted content ([`Grant::covers_taint`]).
    pub fn cover_taint(&mut self, scope: Scope<'_>, action: &Action) {
        for g in &mut self.entries {
            if scope.owns(g) && g.action == *action && g.project.as_deref() == Some(scope.project) {
                g.covers_taint = true;
            }
        }
    }

    /// The newest grant of this host session that answers its taint reviews from
    /// untrusted content in the scope's project, if one is still valid at `now_ms`.
    #[must_use]
    pub fn covering_taint(&self, scope: Scope<'_>, now_ms: i64) -> Option<&Grant> {
        if openmoat_hosts::is_unknown_session(scope.session_id) {
            return None;
        }
        self.active(now_ms)
            .filter(|g| g.covers_taint && scope.owns(g) && g.applies_in(scope.project))
            .max_by_key(|g| g.granted_at_ms)
    }

    /// Grants still valid at `now_ms`.
    pub fn active(&self, now_ms: i64) -> impl Iterator<Item = &Grant> {
        self.entries.iter().filter(move |g| g.active(now_ms))
    }
}

/// Where a grant is made or looked up: a host session, and the project of the
/// call ([`project_of`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Scope<'a> {
    pub host: &'a str,
    pub session_id: &'a str,
    pub project: &'a str,
}

impl Scope<'_> {
    /// Whether `grant` belongs to this host session (in any project).
    fn owns(&self, grant: &Grant) -> bool {
        grant.host == self.host && grant.session_id == self.session_id
    }
}

/// Allow rules appended by `moat allow --always` and `--site`, and the
/// directories `--dir` allowed.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Overlay {
    pub version: u32,
    #[serde(default)]
    pub allow: Vec<RuleGroup>,
    /// Directories allowed with `--dir`, as chosen; the rule each is comes from
    /// the policy it is merged into ([`DirGrant::rule`]). A release that does not
    /// know the field reads the file without them, allowing less.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub dirs: Vec<DirGrant>,
    /// When the entry with each id holds, for those `--for` gave an end; an
    /// entry without one lasts until removed. Outside its window an entry is
    /// left out of the policy ([`Overlay::in_force`]).
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub expires: BTreeMap<String, Window>,
}

impl Default for Overlay {
    fn default() -> Self {
        Self {
            version: OVERLAY_VERSION,
            allow: Vec::new(),
            dirs: Vec::new(),
            expires: BTreeMap::new(),
        }
    }
}

/// One entry of the overlay, as `openmoat allow` shows what it added or removed.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(untagged)]
pub enum Entry {
    /// Boxed: a rule group is several times the size of a directory grant.
    Rule(Box<RuleGroup>),
    Dir(DirGrant),
}

impl Entry {
    /// `approved-<n>`, as decisions and `openmoat allow --remove` name it.
    pub fn id(&self) -> &str {
        match self {
            Self::Rule(rule) => &rule.id,
            Self::Dir(grant) => &grant.id,
        }
    }
}

impl Overlay {
    pub fn load(path: &Path) -> Result<Self> {
        if !path.exists() {
            return Ok(Self::default());
        }
        let text =
            fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
        Self::parse(&text, path)
    }

    /// [`Overlay::load`] of `home`'s overlay, from the bytes the lock check
    /// kept when it kept them ([`Home::load_state`]).
    pub fn load_in(home: &Home) -> Result<Self> {
        home.load_state(&home.overlay_path(), Self::parse, Self::load)
    }

    /// The overlay in `text`, read from `path` (named in errors).
    pub fn parse(text: &str, path: &Path) -> Result<Self> {
        let overlay: Self = openmoat_core::yaml::from_str(text)
            .with_context(|| format!("parsing {}", path.display()))?;
        if ![OVERLAY_VERSION, EXPIRING_OVERLAY_VERSION].contains(&overlay.version) {
            bail!(
                "{} has version {}; this build supports {OVERLAY_VERSION} and \
                 {EXPIRING_OVERLAY_VERSION}",
                path.display(),
                overlay.version
            );
        }
        if let Some(bad) = overlay.ids().find(|id| !id.starts_with(OVERLAY_PREFIX)) {
            bail!(
                "{}: rule `{bad}` must have an id starting with `{OVERLAY_PREFIX}`",
                path.display()
            );
        }
        if let Some(bad) = overlay
            .dirs
            .iter()
            .find(|g| g.dir.is_empty() || !g.dir.iter().all(|d| dirs::plain_dir(d)))
        {
            bail!(
                "{}: `{}` must name a directory, without glob characters",
                path.display(),
                bad.id
            );
        }
        Ok(overlay)
    }

    pub fn save(&self, path: &Path) -> Result<()> {
        write_private(path, self.text()?.as_bytes())
    }

    /// The file as [`Overlay::save`] writes it: at [`EXPIRING_OVERLAY_VERSION`]
    /// while an entry ends, else at [`OVERLAY_VERSION`], which every release reads.
    pub fn text(&self) -> Result<String> {
        let version = if self.expires.is_empty() {
            OVERLAY_VERSION
        } else {
            EXPIRING_OVERLAY_VERSION
        };
        Ok(format!(
            "# Allow rules added with `openmoat allow`. Remove one with\n\
             # `openmoat allow --remove <id>`, or edit freely, then run `openmoat doctor --accept`.\n{}",
            openmoat_core::yaml::to_string(&Self {
                version,
                ..self.clone()
            })?
        ))
    }

    /// The id of every rule and directory grant.
    pub fn ids(&self) -> impl Iterator<Item = &str> {
        let rules = self.allow.iter().map(|g| g.id.as_str());
        rules.chain(self.dirs.iter().map(|g| g.id.as_str()))
    }

    /// Whether the entry `id` is in force at `now_ms`: it has no end, or
    /// `now_ms` is inside its window ([`Window::holds`]).
    #[must_use]
    pub fn holds(&self, id: &str, now_ms: i64) -> bool {
        self.expires.get(id).is_none_or(|w| w.holds(now_ms))
    }

    /// Only the entries in force at `now_ms` ([`Overlay::holds`]): what the
    /// policy merges. The windows are kept.
    #[must_use]
    pub fn in_force(mut self, now_ms: i64) -> Self {
        let expires = &self.expires;
        let holds = |id: &str| expires.get(id).is_none_or(|w| w.holds(now_ms));
        self.allow.retain(|g| holds(&g.id));
        self.dirs.retain(|g| holds(&g.id));
        self
    }

    /// Give the entry `id` the window `window`, or with `None` no end: a grant
    /// made again gets the end it is made with, never the longer of the two.
    pub fn set_window(&mut self, id: &str, window: Option<Window>) {
        match window {
            Some(window) => self.expires.insert(id.to_owned(), window),
            None => self.expires.remove(id),
        };
    }

    /// Remove every entry not in force at `now_ms` ([`Overlay::holds`]), and
    /// any window naming no entry; the entries removed.
    pub fn prune(&mut self, now_ms: i64) -> Vec<Entry> {
        let ended: Vec<String> = self
            .ids()
            .filter(|id| !self.holds(id, now_ms))
            .map(str::to_owned)
            .collect();
        let removed = ended.iter().filter_map(|id| self.remove(id)).collect();
        let ids: Vec<String> = self.ids().map(str::to_owned).collect();
        self.expires.retain(|id, _| ids.contains(id));
        removed
    }

    /// The allow rule each directory grant is under `policy` ([`DirGrant::rule`]),
    /// with `home`'s places; none without grants, and then nothing is looked up.
    pub fn dir_rules(&self, policy: &Policy, home: &Home) -> Result<Vec<RuleGroup>> {
        if self.dirs.is_empty() {
            return Ok(Vec::new());
        }
        let places = Places::here(home)?;
        Ok(self.dirs.iter().map(|g| g.rule(policy, &places)).collect())
    }

    /// The rules an earlier release's `--dir` wrote ([`dirs::is_old_rule`]),
    /// which leave out only the protections of their day.
    pub fn old_dir_rules(&self) -> impl Iterator<Item = &RuleGroup> {
        self.allow.iter().filter(|g| dirs::is_old_rule(g))
    }

    /// Turn each of [`Overlay::old_dir_rules`] into the directory grant it stands
    /// for under `policy` ([`DirGrant::from_rule`]), keeping its id; the grants
    /// made, in order. Never allows more: what such a rule left out that
    /// `policy` no longer names stays left out ([`DirGrant::except`]).
    pub fn migrate_dirs(&mut self, policy: &Policy, places: &Places) -> Vec<DirGrant> {
        let mut made = Vec::new();
        self.allow
            .retain(|rule| match DirGrant::from_rule(rule, policy, places) {
                Some(grant) => {
                    made.push(grant);
                    false
                }
                None => true,
            });
        self.dirs.extend(made.iter().cloned());
        made
    }

    /// Append an allow rule for one shell command, matched literally: glob
    /// characters in the command are not wildcards in the rule. Shell rules are
    /// prefixes, so extra arguments after the approved command are accepted.
    /// An install of a name close to a popular package, or a run of a
    /// package that is not on the popular list (`npx x`), also gets its
    /// `@package-near-miss` or `@package-run-unknown` atom, which a rule holds
    /// for review on its own: approving the command answers that review too.
    pub fn allow_command(&mut self, command: &str) -> Result<&RuleGroup> {
        let mut patterns = Vec::new();
        for line in std::iter::once(command.to_owned()).chain(openmoat_core::package_atoms(command))
        {
            let pattern = openmoat_core::literal_shell_pattern(&line)
                .with_context(|| format!("cannot approve `{line}`"))?;
            patterns.push(pattern);
        }
        Ok(self.push("openmoat allow --always", |g| g.shell = patterns))
    }

    /// Append an `fs.read` and `fs.write` allow for exactly these paths. A path
    /// holding glob characters is refused: the rule would read them as wildcards.
    pub fn allow_files(&mut self, reads: &[String], writes: &[String]) -> Result<&RuleGroup> {
        if let Some(bad) = reads
            .iter()
            .chain(writes)
            .find(|p| p.contains(['*', '?', '[', ']', '{', '}', '\\']))
        {
            bail!(
                "{bad} contains glob characters; write it in the policy with `openmoat edit` instead"
            );
        }
        Ok(self.push("openmoat allow --always", |g| {
            g.fs_read = reads.to_vec();
            g.fs_write = writes.to_vec();
        }))
    }

    /// Whether a rule here already allows `action` (spelled by [`approvable`]).
    #[must_use]
    pub fn covers(&self, action: &Action) -> bool {
        if let Action::Shell { command } = action {
            let pattern = openmoat_core::literal_shell_pattern(command).ok();
            return self
                .allow
                .iter()
                .any(|g| pattern.as_ref().is_some_and(|p| g.shell.contains(p)));
        }
        let (reads, writes) = files(action);
        !(reads.is_empty() && writes.is_empty())
            && self.allow.iter().any(|g| {
                reads.iter().all(|p| g.fs_read.contains(p))
                    && writes.iter().all(|p| g.fs_write.contains(p))
            })
    }

    /// Append a `net` allow for one host name, which also covers web fetches.
    /// Only a plain name or address is accepted: a wildcard, scheme or port would
    /// widen the rule beyond what the person typed.
    pub fn allow_site(&mut self, host: &str) -> Result<&RuleGroup> {
        let host = host.trim().trim_end_matches('.').to_ascii_lowercase();
        let plain = host.split('.').all(|label| {
            !label.is_empty() && label.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
        });
        if !plain {
            bail!(
                "`{host}` is not a host name such as docs.rs; wildcards, URLs and ports \
                 are not accepted here (write those in the policy with `openmoat edit`)"
            );
        }
        Ok(self.push("openmoat allow --site", |g| g.net = vec![host]))
    }

    /// Append a grant to read and write each spelling of a directory and
    /// everything below it ([`DirGrant`]). It stores the directory only: what
    /// the policy holds for review there (a `.git`, the files CI, a commit hook
    /// or the editor runs later) stays held, by the policy of the day it is
    /// loaded with, not the policy of the day it was made.
    ///
    /// The same directory allowed again is the same grant, with a new reason:
    /// its id, and what it already left out, stay.
    pub fn allow_dir(&mut self, spellings: &[String]) -> &DirGrant {
        let reason = Some(approved_with("openmoat allow --dir"));
        let index = if let Some(index) = self.dirs.iter().position(|g| g.dir == spellings) {
            index
        } else {
            let grant = DirGrant {
                id: self.next_id(),
                reason: None,
                dir: spellings.to_vec(),
                except: Vec::new(),
            };
            self.dirs.push(grant);
            self.dirs.len() - 1
        };
        self.dirs[index].reason = reason;
        &self.dirs[index]
    }

    /// Remove the rule or directory grant with this id, and its window,
    /// returning it.
    pub fn remove(&mut self, id: &str) -> Option<Entry> {
        let entry = if let Some(index) = self.allow.iter().position(|g| g.id == id) {
            Entry::Rule(Box::new(self.allow.remove(index)))
        } else {
            let index = self.dirs.iter().position(|g| g.id == id)?;
            Entry::Dir(self.dirs.remove(index))
        };
        self.expires.remove(id);
        Some(entry)
    }

    /// Append the rule `fill` makes; one that only differs from it in id and
    /// reason is the same grant made again, and gets the new reason instead.
    fn push(&mut self, how: &str, fill: impl FnOnce(&mut RuleGroup)) -> &RuleGroup {
        let mut rule = RuleGroup {
            reason: Some(approved_with(how)),
            ..RuleGroup::default()
        };
        fill(&mut rule);
        let same = |g: &RuleGroup| {
            *g == RuleGroup {
                id: g.id.clone(),
                reason: g.reason.clone(),
                ..rule.clone()
            }
        };
        let index = if let Some(index) = self.allow.iter().position(same) {
            self.allow[index].reason = rule.reason;
            index
        } else {
            rule.id = self.next_id();
            self.allow.push(rule);
            self.allow.len() - 1
        };
        &self.allow[index]
    }

    /// One past the highest number of any id, a window's included: ids stay
    /// unique after a person deletes an earlier entry, a duplicate id would
    /// fail the policy lint, and a window left behind never applies to a new
    /// entry.
    fn next_id(&self) -> String {
        let n = self
            .ids()
            .chain(self.expires.keys().map(String::as_str))
            .filter_map(|id| id.strip_prefix(OVERLAY_PREFIX)?.parse::<u64>().ok())
            .max()
            .unwrap_or(0)
            + 1;
        format!("{OVERLAY_PREFIX}{n}")
    }
}

/// The reason an entry is written with: ``approved with `openmoat allow --dir` on 2026-11-07 10:00``.
fn approved_with(how: &str) -> String {
    format!(
        "approved with `{how}` on {}",
        time::timestamp(time::now_ms())
    )
}

#[cfg(test)]
mod tests;