openmoat 0.24.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
//! `moat policy upgrade`: add what this release's default changed to the
//! person's policy and bring an earlier release's directory grants up to date
//! (`grants.rs`), show what changes (grouped, `summary.rs`; the full diff on
//! `d` or `--diff`) and ask; once applied, sync the agents' sandboxes as `openmoat
//! sandbox sync` does. `--undo` puts the previous policy back.

use std::fs;
use std::io::{ErrorKind, Write as _};
use std::path::{Path, PathBuf};

use anyhow::{Context as _, Result, bail};
use similar::{Algorithm, udiff::unified_diff};

use crate::VERSION;
use crate::cli::UpgradeArgs;
use crate::context::read_policy;
use crate::exit::Code;
use crate::home::{Home, write_private};
use crate::integrity::{self, HookPins};
use crate::render::{DIFF_CONTEXT_LINES, Deferred};
use crate::upgrade::{Base, Plan};
use grants::Migration;

mod grants;
mod summary;

pub fn run(args: &UpgradeArgs) -> Result<Code> {
    let home = Home::locate()?;
    if !home.policy_path().is_file() {
        bail!(
            "no policy at {}; run `openmoat init`",
            home.policy_path().display()
        );
    }
    if args.undo {
        return undo(&home, args.yes);
    }
    let plan = Plan::for_home(&home)?;
    let grants = Migration::for_home(&home, &plan.merge.text)?;
    let mut out = Deferred::default();
    describe(&plan, grants.as_ref(), args, &mut out)?;
    let binary = crate::install::hook_binary()?;
    let hook_upgrade = crate::install::migrate_hooks::needed(&home, &binary)?;
    if hook_upgrade {
        writeln!(
            out,
            "OpenMoat's hooks change too; an agent that keeps its own record of trusted hooks \
             asks you to trust the changed one"
        )?;
    }
    if (plan.applicable() == 0 && grants.is_none()) || args.dry_run {
        if hook_upgrade && !args.dry_run {
            person("openmoat policy upgrade")?;
            integrity::refuse_drift(&home, "upgrade existing hooks")?;
            crate::install::migrate_hooks::update(&home, &binary)?;
            integrity::repin(&home, &binary, HookPins::Keep)?;
            writeln!(out, "✔ OpenMoat's hooks updated")?;
            trust_steps(&home, &binary, &mut out)?;
        }
        if !args.dry_run && up_to_date_without_record(&plan) && crate::terminal::person() {
            // Recorded now so a later default is compared with this one, not 0.3.0.
            write_private(&home.policy_base_path(), plan.merge.base.as_bytes())?;
        }
        out.finish()?;
        return Ok(Code::Ok);
    }
    person("openmoat policy upgrade")?;
    // Applying re-pins every pinned file, so upgrading over drift would accept it unseen.
    integrity::refuse_drift(&home, "upgrade the policy")?;
    let checkpoint = integrity::Checkpoint::take(&home)?;
    lint(&home, &plan.merge.text)?;
    if !args.yes && !confirm(&plan, grants.as_ref(), &mut out)? {
        writeln!(out, "the policy was not changed")?;
        out.finish()?;
        return Ok(Code::Ok);
    }
    // The re-pin after the writes covers every pinned file: one changed while
    // the question waited would be accepted unseen.
    checkpoint.verify(&home, &[])?;
    apply(&home, &plan, grants.as_ref(), &mut out)?;
    if hook_upgrade {
        trust_steps(&home, &binary, &mut out)?;
    }
    sync(&home, &mut out)?;
    out.finish()?;
    Ok(Code::Ok)
}

/// `Apply these changes? [y/N/d]`, where `d` shows the full diff and asks
/// again; anything but yes, end of input included, is no.
fn confirm(plan: &Plan, grants: Option<&Migration>, out: &mut Deferred) -> Result<bool> {
    loop {
        let question = "\nApply these changes? [y/N/d]   (d = show the full diff) ";
        match crate::commands::edit::answer(out, question)?.as_str() {
            "y" | "yes" => return Ok(true),
            "d" | "diff" => full_diff(plan, grants, out)?,
            _ => return Ok(false),
        }
    }
}

/// The policy as it is against the policy upgraded, as `diff -u` shows it,
/// then `approved.yaml` against it with the directory grants brought up to date.
fn full_diff(plan: &Plan, grants: Option<&Migration>, out: &mut Deferred) -> Result<()> {
    let policy = (&plan.current, &plan.merge.text, "policy.yaml");
    let overlay = grants.map(|g| (&g.before, &g.after, "approved.yaml"));
    for (before, after, name) in std::iter::once(policy).chain(overlay) {
        if before == after {
            continue;
        }
        let diff = unified_diff(
            Algorithm::Myers,
            before,
            after,
            DIFF_CONTEXT_LINES,
            Some((
                &format!("{name} (installed)"),
                &format!("{name} (upgraded)"),
            )),
        );
        write!(out, "{diff}")?;
    }
    Ok(())
}

/// The step each set-up agent with its own record of trusted hooks needs
/// after its hook changed (Codex's `/hooks`).
fn trust_steps(home: &Home, binary: &Path, out: &mut Deferred) -> Result<()> {
    for host in openmoat_hosts::Host::ALL {
        if let Some(step) = crate::install::trust_note::step(host)
            && crate::install::HostConfig::for_host(home, host)?.set_up(binary)
        {
            writeln!(out, "! {}: {step}", host.display_name())?;
        }
    }
    Ok(())
}

/// The agents' sandboxes from the upgraded policy, as `openmoat sandbox sync`
/// writes them, after the same checks; when they cannot be written, the
/// command to run.
fn sync(home: &Home, out: &mut Deferred) -> Result<()> {
    let mut lines = Vec::new();
    match crate::commands::sandbox::sync_checked(home, "openmoat policy upgrade", &mut lines) {
        Ok(synced) if synced.updated == 0 => {
            writeln!(out, "✔ Agents' sandboxes already follow the policy")?;
        }
        Ok(_) => writeln!(out, "✔ Agents' sandboxes updated")?,
        Err(e) => writeln!(
            out,
            "! Agents' sandboxes not updated: {e:#}\n  run `openmoat sandbox sync` so the agents' \
             sandboxes follow the upgraded policy"
        )?,
    }
    Ok(())
}

/// What the default adds and the directory grants it brings up to date,
/// grouped (`summary.rs`) or, with `--diff`, also as a diff, and what it cannot add.
fn describe(
    plan: &Plan,
    grants: Option<&Migration>,
    args: &UpgradeArgs,
    out: &mut Deferred,
) -> Result<()> {
    describe_policy(plan, grants, args, out)?;
    if plan.applicable() == 0
        && let Some(grants) = grants
    {
        writeln!(
            out,
            "\nDirectory grants from an earlier OpenMoat leave out only the protections of \
             their day\n"
        )?;
        let summary = summary::Summary {
            dir_grants: grants.lines(),
            ..summary::Summary::default()
        };
        summary.write(out)?;
        if args.diff {
            writeln!(out)?;
            full_diff(plan, Some(grants), out)?;
        }
        if args.dry_run {
            writeln!(
                out,
                "\nNothing was changed: `openmoat policy upgrade` brings them up to date after \
                 asking (`--diff` shows the full diff)."
            )?;
        }
    }
    Ok(())
}

/// What the default adds, grouped, with the directory grants under their own
/// heading, and what it cannot add.
fn describe_policy(
    plan: &Plan,
    grants: Option<&Migration>,
    args: &UpgradeArgs,
    out: &mut Deferred,
) -> Result<()> {
    match plan.base {
        Base::Recorded => {}
        Base::Assumed => writeln!(
            out,
            "No record of the default this policy started from; comparing with the \
             OpenMoat 0.3.0 default (the policy predates OpenMoat recording it)."
        )?,
        Base::Unrelated => {
            writeln!(
                out,
                "This policy was not made from OpenMoat's default, so no change of the default \
                 is offered; compare it with `openmoat policy lint` and the default in docs/POLICY.md."
            )?;
            if !plan.renamed {
                return Ok(());
            }
        }
    }
    let count = plan.applicable();
    if count > 0 {
        let from_default = count - usize::from(plan.renamed);
        let title = if from_default > 0 {
            format!("OpenMoat {VERSION} has new default rules for your policy")
        } else {
            format!("OpenMoat {VERSION} renames a word in your policy")
        };
        writeln!(out, "{title}\n")?;
        let applied: Vec<_> = plan.merge.applied().collect();
        let mut summary =
            summary::summarise(&plan.current, &plan.merge.text, &applied, plan.renamed);
        summary.dir_grants = grants.map(Migration::lines).unwrap_or_default();
        summary.write(out)?;
        if args.diff {
            writeln!(out)?;
            full_diff(plan, grants, out)?;
        }
        if args.dry_run {
            writeln!(
                out,
                "\nNothing was changed: `openmoat policy upgrade` applies them after asking \
                 (`--diff` shows the full diff); `--undo` takes them back."
            )?;
        }
    }
    for change in plan.merge.conflicts() {
        writeln!(
            out,
            "Not applied: you changed the policy at line {}; the default now has:",
            change.line
        )?;
        for line in change.default.lines() {
            writeln!(out, "  {line}")?;
        }
    }
    if plan.merge.conflicts().next().is_some() {
        writeln!(
            out,
            "Make those by hand with `openmoat edit` if you want them."
        )?;
    } else if count == 0 {
        writeln!(
            out,
            "The policy has every change of the OpenMoat {VERSION} default."
        )?;
    }
    Ok(())
}

/// A policy from before `policy.base.yaml` that already has every change.
fn up_to_date_without_record(plan: &Plan) -> bool {
    plan.base == Base::Assumed && plan.merge.changes.is_empty()
}

/// Refuse unless a person is at a terminal: writing the policy re-pins the lock.
fn person(command: &str) -> Result<()> {
    crate::terminal::refuse_agent(command)?;
    if !crate::terminal::interactive() {
        bail!(
            "`{command}` must be run by a person in a terminal, not from a hook or script; \
             `openmoat policy upgrade --dry-run` shows the changes anywhere"
        );
    }
    Ok(())
}

/// Check the upgraded policy, with `moat allow` rules merged, the way `moat
/// edit` checks its draft: from a file in the state directory agents cannot write.
fn lint(home: &Home, text: &str) -> Result<()> {
    let draft = home.root().join("policy.upgrade.yaml");
    write_private(&draft, text.as_bytes())?;
    let checked = home.load_policy_at(&draft);
    let _ = fs::remove_file(&draft);
    checked
        .map(drop)
        .context("the upgraded policy does not lint; the policy was not changed")
}

/// The policy and base each upgrade replaced, kept for `--undo`.
fn backups(home: &Home) -> (PathBuf, PathBuf) {
    let root = home.root();
    (
        root.join("policy.yaml.before-upgrade"),
        root.join("policy.base.yaml.before-upgrade"),
    )
}

/// Write the upgraded policy (keeping the one it replaces for `--undo`) and the
/// directory grants, then re-pin.
fn apply(home: &Home, plan: &Plan, grants: Option<&Migration>, out: &mut Deferred) -> Result<()> {
    let (policy_backup, base_backup) = backups(home);
    let upgrades = plan.applicable() > 0;
    if upgrades {
        write_private(&policy_backup, plan.current.as_bytes())?;
        copy_or_remove(&home.policy_base_path(), &base_backup)?;
        write_private(&home.policy_path(), plan.merge.text.as_bytes())?;
        // A policy not made from the default takes only the rename (ADR-053); recording
        // the assumed 0.3.0 default as its base would make the next upgrade merge the
        // default into it as if the person had edited every line.
        if plan.base != Base::Unrelated {
            write_private(&home.policy_base_path(), plan.merge.base.as_bytes())?;
        }
    }
    if let Some(grants) = grants {
        grants.save(home)?;
    }
    let binary = crate::install::hook_binary()?;
    crate::install::migrate_hooks::update(home, &binary)?;
    integrity::repin(home, &binary, HookPins::Keep)?;
    writeln!(out)?;
    if upgrades {
        let paths = crate::report::Paths::detect();
        writeln!(
            out,
            "✔ Policy upgraded            undo: openmoat policy upgrade --undo"
        )?;
        writeln!(
            out,
            "  the previous policy is in {}",
            paths.path(&policy_backup)
        )?;
    }
    if let Some(grants) = grants {
        // Not undone with the policy: the grants only keep out more.
        let made = crate::report::count(grants.lines().len(), "directory grant");
        writeln!(
            out,
            "✔ {made} brought up to date: what the policy holds for review stays held in them"
        )?;
    }
    Ok(())
}

fn undo(home: &Home, yes: bool) -> Result<Code> {
    let (policy_backup, base_backup) = backups(home);
    if !policy_backup.is_file() {
        bail!(
            "no upgrade to undo: {} does not exist",
            policy_backup.display()
        );
    }
    person("openmoat policy upgrade --undo")?;
    integrity::refuse_drift(home, "undo the policy upgrade")?;
    let checkpoint = integrity::Checkpoint::take(home)?;
    let current = read_policy(&home.policy_path())?;
    let previous = read_policy(&policy_backup)?;
    let mut out = Deferred::default();
    let diff = unified_diff(
        Algorithm::Myers,
        &current,
        &previous,
        DIFF_CONTEXT_LINES,
        Some((
            "policy.yaml (installed)",
            "policy.yaml (before the upgrade)",
        )),
    );
    write!(out, "{diff}")?;
    if !yes && !crate::commands::edit::confirm(&mut out, "Restore it? [y/N] ")? {
        writeln!(out, "the policy was not changed")?;
        out.finish()?;
        return Ok(Code::Ok);
    }
    checkpoint.verify(home, &[])?;
    write_private(&home.policy_path(), previous.as_bytes())?;
    copy_or_remove(&base_backup, &home.policy_base_path())?;
    fs::remove_file(&policy_backup)
        .with_context(|| format!("removing {}", policy_backup.display()))?;
    remove_if_present(&base_backup)?;
    let binary = crate::install::hook_binary()?;
    let written = [home.policy_path()];
    let lock = integrity::repin_after(home, &binary, HookPins::Keep, &checkpoint, &written)?;
    writeln!(
        out,
        "✔ {} restored to before the upgrade",
        home.policy_path().display()
    )?;
    writeln!(out, "✔ lock re-pinned ({} files)", lock.entries.len())?;
    out.finish()?;
    Ok(Code::Ok)
}

/// Make `to` a copy of `from`, or absent when `from` is: a policy without a
/// recorded base gets none back on undo.
fn copy_or_remove(from: &Path, to: &Path) -> Result<()> {
    if from.is_file() {
        write_private(to, read_policy(from)?.as_bytes())
    } else {
        remove_if_present(to)
    }
}

fn remove_if_present(path: &Path) -> Result<()> {
    match fs::remove_file(path) {
        Err(e) if e.kind() != ErrorKind::NotFound => {
            Err(e).with_context(|| format!("removing {}", path.display()))
        }
        _ => Ok(()),
    }
}