openmoat 0.29.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
//! What `openmoat policy upgrade` changes, grouped for a person instead of the
//! raw diff: rules that protect more, changes that interrupt less, the
//! `ask` → `review` rename, the count of comment and wording updates and of
//! narrow patterns folded into broader ones, and the directory grants brought
//! up to date (`grants.rs`). Worked out from the policy before and after the
//! merge, read as policies, so a line moved or reworded is never shown as a new
//! rule, nor a pattern its rule still covers as a removal. A change it cannot
//! name is counted under "Other changes", for `d` to show.

use std::collections::BTreeMap;

use openmoat_core::{Kind, Policy, RuleGroup};
use serde_json::Value;

use crate::upgrade::Change;

mod superset;

/// At most this many patterns are named in a line; more are counted.
const NAMED_PATTERNS: usize = 3;
/// A pattern longer than this is counted, not named.
const NAMED_PATTERN_CHARS: usize = 40;

/// The changes, grouped.
#[derive(Debug, Default, PartialEq, Eq)]
pub(super) struct Summary {
    /// What is denied or held for review that was not.
    pub protections: Vec<String>,
    /// What is allowed or left to the agent that was not.
    pub fewer: Vec<String>,
    /// The rename of `ask` to `review` (ADR-053).
    pub renamed: bool,
    /// Changes of comments, blank lines and rule reasons only.
    pub wording: usize,
    /// Patterns taken out of a group that a broader pattern of the same group
    /// still matches as a whole, so nothing is decided differently.
    pub folded: usize,
    /// Directory grants `openmoat policy upgrade` brings up to date
    /// ([`crate::approvals::DirGrant`]), one line each.
    pub dir_grants: Vec<String>,
    /// Other changes, named: a section of the policy that changed.
    pub other: Vec<String>,
    /// Changes of the text that none of the above explains.
    pub unexplained: usize,
}

/// The list a rule group is in, and how its matches are decided.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum List {
    Deny,
    Review,
    Allow,
    Defer,
}

impl List {
    /// Whether a match in this list lets the call through without the person.
    fn lets_through(self) -> bool {
        matches!(self, Self::Allow | Self::Defer)
    }

    fn name(self) -> &'static str {
        match self {
            Self::Deny => "deny",
            Self::Review => "review",
            Self::Allow => "allow",
            Self::Defer => "defer",
        }
    }
}

/// The grouped summary of going from `current` to `merged` with `changes`
/// (the merge's applied stretches) and, when `renamed`, the rename.
pub(super) fn summarise(
    current: &str,
    merged: &str,
    changes: &[&Change],
    renamed: bool,
) -> Summary {
    let mut summary = Summary {
        renamed,
        ..Summary::default()
    };
    let wording_only = changes
        .iter()
        .filter(|c| without_comments(&c.yours) == without_comments(&c.default))
        .count();
    let code = changes.len() - wording_only;
    summary.wording = wording_only;
    match (Policy::parse(current), Policy::parse(merged)) {
        (Ok(before), Ok(after)) => {
            summary.wording += rules(&before, &after, &mut summary);
            sections(&before, &after, &mut summary);
            let named = summary.protections.len()
                + summary.fewer.len()
                + summary.other.len()
                + summary.folded;
            if named == 0 && summary.wording == wording_only {
                summary.unexplained = code;
            }
        }
        // Not read as policies: nothing is named that cannot be shown to be so.
        _ => summary.unexplained = code,
    }
    summary
}

impl Summary {
    /// The groups, each line under its heading, two spaces in.
    pub fn write(&self, out: &mut impl std::io::Write) -> std::io::Result<()> {
        let groups = [
            ("New protections", "+", &self.protections),
            ("Fewer interruptions", "−", &self.fewer),
            ("Other changes", "·", &self.other),
            ("Directory grants", "+", &self.dir_grants),
        ];
        for (heading, mark, lines) in groups {
            if lines.is_empty() {
                continue;
            }
            writeln!(out, "  {heading}")?;
            for line in lines {
                writeln!(out, "    {mark} {}", crate::render::clean(line))?;
            }
        }
        if self.renamed {
            writeln!(out, "  Renamed")?;
            writeln!(out, "    ~ `ask` is now `review` (same behaviour)")?;
        }
        if self.wording > 0 {
            let updates = crate::report::count(self.wording, "comment and wording update");
            writeln!(out, "  + {updates}")?;
        }
        if self.folded > 0 {
            let narrow = crate::report::count(self.folded, "narrow pattern");
            writeln!(out, "  + {narrow} now matched by a broader one")?;
        }
        if self.unexplained > 0 {
            writeln!(out, "  Other changes: {} (d to see)", self.unexplained)?;
        }
        Ok(())
    }
}

/// Every rule group by id, with its list.
fn groups(policy: &Policy) -> BTreeMap<&str, (List, &RuleGroup)> {
    let lists = [
        (List::Deny, &policy.deny),
        (List::Review, &policy.review),
        (List::Allow, &policy.allow),
        (List::Defer, &policy.defer),
    ];
    lists
        .into_iter()
        .flat_map(|(list, groups)| groups.iter().map(move |g| (g.id.as_str(), (list, g))))
        .collect()
}

/// The rule changes, each in its group; returns how many changed their
/// reason only.
fn rules(before: &Policy, after: &Policy, summary: &mut Summary) -> usize {
    let (old, new) = (groups(before), groups(after));
    let mut reworded = 0;
    for (id, (list, group)) in &new {
        match old.get(id) {
            None => added_group(*list, group, summary),
            Some((was, _)) if was != list => summary.other.push(format!(
                "`{id}` moved from `{}:` to `{}:`",
                was.name(),
                list.name()
            )),
            Some((_, was)) => {
                let patterns = pattern_changes(*list, id, was, group, summary);
                // A reason, title or why (ADR-059) changes the words shown, not what is decided.
                let rest_same = RuleGroup {
                    reason: group.reason.clone(),
                    title: group.title.clone(),
                    why: group.why.clone(),
                    ..(*was).clone()
                } == **group;
                let words = (&was.reason, &was.title, &was.why)
                    != (&group.reason, &group.title, &group.why);
                if !patterns && words && rest_same {
                    reworded += 1;
                } else if was.hook_only != group.hook_only {
                    summary.other.push(format!("`{id}`: `hook_only` changed"));
                }
            }
        }
    }
    for (id, (list, _)) in old.iter().filter(|(id, _)| !new.contains_key(*id)) {
        let line = format!("`{id}` removed (it was a `{}:` rule)", list.name());
        if list.lets_through() {
            summary.protections.push(line);
        } else {
            summary.fewer.push(line);
        }
    }
    reworded
}

/// A rule group the policy did not have.
fn added_group(list: List, group: &RuleGroup, summary: &mut Summary) {
    let what = group
        .title
        .clone()
        .or_else(|| group.reason.clone())
        .unwrap_or_else(|| patterns_phrase(&all_patterns(group)));
    let id = &group.id;
    match list {
        List::Deny => summary.protections.push(format!("Denied: {what} (`{id}`)")),
        List::Review => summary
            .protections
            .push(format!("Needs your review: {what} (`{id}`)")),
        List::Allow => summary.fewer.push(format!("Allowed: {what} (`{id}`)")),
        List::Defer => summary
            .fewer
            .push(format!("Left to the agent: {what} (`{id}`)")),
    }
}

/// The patterns `group` gained and lost, one line per direction; whether
/// there were any. A pattern starting with `!` is an exception to the group,
/// so adding one does the opposite of adding a plain pattern. A pattern lost
/// for one the group gains that is the same but for longer `{…}` lists was
/// broadened: the two are shown once, as that, never as a removal. One lost
/// that a pattern the group keeps still matches is counted in
/// [`Summary::folded`], not named: the group decides it as before.
fn pattern_changes(
    list: List,
    id: &str,
    was: &RuleGroup,
    now: &RuleGroup,
    summary: &mut Summary,
) -> bool {
    let folded_before = summary.folded;
    let (mut tighter, mut wider) = (Vec::new(), Vec::new());
    let mut broadened = Vec::new();
    for kind in Kind::ALL {
        let (old, new) = (was.patterns(kind), now.patterns(kind));
        let added: Vec<&String> = new.iter().filter(|p| !old.contains(p)).collect();
        let removed = old.iter().filter(|p| !new.contains(p));
        let mut pairs: Vec<Broadened> = Vec::new();
        let mut taken_out = Vec::new();
        for pattern in removed {
            let pair = added
                .iter()
                .filter(|by| !pairs.iter().any(|pair| pair.new == by.as_str()))
                .find_map(|by| Broadened::of(kind, pattern, by));
            if let Some(pair) = pair {
                pairs.push(pair);
            } else if still_covered(kind, pattern, new) {
                summary.folded += 1;
            } else {
                taken_out.push(pattern);
            }
        }
        let put_in = added
            .into_iter()
            .filter(|p| !pairs.iter().any(|pair| pair.new == p.as_str()));
        for (pattern, added) in put_in
            .map(|p| (p, true))
            .chain(taken_out.into_iter().map(|p| (p, false)))
        {
            let shown = pattern.strip_prefix('!');
            let side = if tightens(added, shown.is_some(), list) {
                &mut tighter
            } else {
                &mut wider
            };
            side.push(shown.unwrap_or(pattern.as_str()));
        }
        broadened.extend(pairs);
    }
    broadened_lines(list, id, &broadened, summary);
    let (now_covers, no_longer) = match list {
        List::Deny => ("now also denies", "no longer denies"),
        List::Review => ("now also holds for review", "no longer holds for review"),
        List::Allow => ("no longer allows", "now also allows"),
        List::Defer => (
            "no longer leaves to the agent",
            "now also leaves to the agent",
        ),
    };
    if !tighter.is_empty() {
        let line = format!("`{id}` {now_covers} {}", patterns_phrase(&tighter));
        summary.protections.push(line);
    }
    if !wider.is_empty() {
        let line = format!("`{id}` {no_longer} {}", patterns_phrase(&wider));
        summary.fewer.push(line);
    }
    !(tighter.is_empty() && wider.is_empty() && broadened.is_empty())
        || summary.folded > folded_before
}

/// Whether a pattern taken in (`added`) or out of a group of `list` makes it
/// decide more calls the strict way. A plain pattern added to a deny or review
/// group protects more; an exception, a removal or an allow group each turn
/// that round.
fn tightens(added: bool, exception: bool, list: List) -> bool {
    added ^ exception ^ list.lets_through()
}

/// A pattern replaced by the same pattern with longer `{…}` lists: everything
/// the old matched, the new still matches, and more.
struct Broadened<'a> {
    new: &'a str,
    /// The alternatives the new pattern's lists gained: `team`.
    gained: Vec<String>,
}

impl<'a> Broadened<'a> {
    /// `removed` replaced by `by`, when `by` is `removed` with longer lists
    /// and matches everything it did: a plain pattern by a plain one, an
    /// exception by an exception.
    fn of(kind: Kind, removed: &str, by: &'a str) -> Option<Self> {
        let ((by_negated, body_by), (negated, body)) =
            (split_exclusion(by), split_exclusion(removed));
        let broader = by_negated == negated && superset::covers(kind, body_by, body);
        broader
            .then(|| superset::gained(body, body_by))
            .flatten()
            .map(|gained| Self { new: by, gained })
    }
}

/// One line per set of alternatives gained, on the side it moves the group
/// to: a pattern of a deny group that now matches more protects more.
/// `kernel-self`: 15 patterns now also cover `team`.
fn broadened_lines(list: List, id: &str, broadened: &[Broadened], summary: &mut Summary) {
    let mut by_gain: BTreeMap<(bool, &[String]), usize> = BTreeMap::new();
    for pair in broadened {
        let exception = pair.new.starts_with('!');
        *by_gain
            .entry((exception, pair.gained.as_slice()))
            .or_default() += 1;
    }
    for ((exception, gained), n) in by_gain {
        let noun = if exception { "exception" } else { "pattern" };
        let what = crate::report::count(n, noun);
        let verb = if n == 1 { "covers" } else { "cover" };
        let names: Vec<String> = gained.iter().map(|g| format!("`{g}`")).collect();
        let line = format!("`{id}`: {what} now also {verb} {}", names.join(", "));
        if tightens(true, exception, list) {
            summary.protections.push(line);
        } else {
            summary.fewer.push(line);
        }
    }
}

/// Whether `removed`, a pattern a group of `kind` no longer lists, is still
/// matched as a whole by one of the group's `patterns`: a plain pattern by a
/// plain one, an exclusion by an exclusion (`**/.vscode/**` for
/// `**/.vscode/tasks.json`). Then taking it out decides nothing differently.
/// Conservative: when the core cannot show it ([`openmoat_core::lint::covers`]),
/// the removal is reported as one.
fn still_covered(kind: Kind, removed: &str, patterns: &[String]) -> bool {
    let (negated, body) = split_exclusion(removed);
    patterns.iter().any(|p| {
        let (by_negated, by) = split_exclusion(p);
        by_negated == negated && superset::covers(kind, by, body)
    })
}

/// `!pattern` → `(true, "pattern")`.
fn split_exclusion(pattern: &str) -> (bool, &str) {
    pattern
        .strip_prefix('!')
        .map_or((false, pattern), |body| (true, body))
}

fn all_patterns(group: &RuleGroup) -> Vec<&str> {
    Kind::ALL
        .iter()
        .flat_map(|k| group.patterns(*k))
        .map(String::as_str)
        .collect()
}

/// A few short patterns by name, else how many: `` `git config user.name` ``,
/// `5 patterns`.
fn patterns_phrase(patterns: &[&str]) -> String {
    let short = patterns.len() <= NAMED_PATTERNS
        && patterns
            .iter()
            .all(|p| p.chars().count() <= NAMED_PATTERN_CHARS);
    if short && !patterns.is_empty() {
        let named: Vec<String> = patterns.iter().map(|p| format!("`{p}`")).collect();
        named.join(", ")
    } else {
        crate::report::count(patterns.len(), "pattern")
    }
}

/// Every top-level section besides the rule lists that differs: `defaults`,
/// `sandbox`, `executables`, …
fn sections(before: &Policy, after: &Policy, summary: &mut Summary) {
    let rest = |policy: &Policy| -> Option<serde_json::Map<String, Value>> {
        let Value::Object(mut map) = serde_json::to_value(policy).ok()? else {
            return None;
        };
        for list in ["deny", "review", "allow", "defer"] {
            map.remove(list);
        }
        Some(map)
    };
    let (Some(old), Some(new)) = (rest(before), rest(after)) else {
        return;
    };
    let keys: std::collections::BTreeSet<&String> = old.keys().chain(new.keys()).collect();
    for key in keys {
        if old.get(key) != new.get(key) {
            summary.other.push(format!("`{key}:` changed"));
        }
    }
}

/// `text` without comment lines, blank lines, trailing comments and trailing
/// spaces: what YAML reads of it.
fn without_comments(text: &str) -> Vec<String> {
    text.lines()
        .map(|line| strip_comment(line).trim_end().to_owned())
        .filter(|line| !line.trim().is_empty())
        .collect()
}

/// `line` up to a `#` that starts a comment: at the start, or after a space
/// outside quotes.
fn strip_comment(line: &str) -> &str {
    let (mut single, mut double) = (false, false);
    let mut previous = ' ';
    for (at, c) in line.char_indices() {
        match c {
            '\'' if !double => single = !single,
            '"' if !single => double = !double,
            '#' if !single && !double && previous.is_whitespace() => return &line[..at],
            _ => {}
        }
        previous = c;
    }
    line
}

#[cfg(test)]
mod tests;