openmoat 0.11.0

Policy checks for AI coding agents: decides allow, defer, ask or deny for every tool call from Claude Code, Codex, Cursor, OpenClaw, GitHub Copilot CLI, pi and Gemini CLI, 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
//! `moat uninstall`: take OpenMoat's hooks and sandbox settings out of the agents.
//!
//! Each host file is undone by removing exactly what `moat init` writes. When
//! what is left equals one of the backups `init` took, that backup's bytes are
//! written back, so an untouched file comes back byte for byte; when it is
//! empty and no backup matches, `init` created the file and it is deleted.
//! Otherwise the user changed the file since, and their changes stay. Only the
//! backups `hosts.json` records as OpenMoat's are deleted: a file of the
//! user's at a backup's name stays.

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

use anyhow::{Context as _, Result, bail, ensure};
use openmoat_hosts::Host;
use serde_json::{Value, json};
use toml_edit::DocumentMut;

use crate::cli::UninstallArgs;
use crate::exit::Code;
use crate::home::{Home, user_home, write_private};
use crate::install::{self, HookLayout, HostConfig, Recorded, read_or_empty};
use crate::integrity;
use crate::render::Deferred;
use crate::sandbox::backend::{SandboxBackend, Undo};
use crate::sandbox::install as host_sandbox;

pub fn run(args: &UninstallArgs) -> Result<Code> {
    crate::terminal::refuse_agent("openmoat uninstall")?;
    if !crate::terminal::interactive() {
        bail!(
            "`openmoat uninstall` must be run by a person in a terminal, not from a hook or script"
        );
    }
    let home = Home::locate()?;
    let hosts = match &args.hosts {
        Some(explicit) => explicit.clone(),
        None => Host::ALL
            .into_iter()
            .filter(|h| HostConfig::for_host(&home, *h).is_ok())
            .collect(),
    };
    let mut out = Deferred::default();
    // Before the record forgets where each agent is: the wrapped servers point at
    // `moat mcp proxy`, which outlives the hooks only as a dangling path.
    if let Err(e) = super::mcp::unwrap_servers(&home, &hosts, &[], &mut out) {
        writeln!(
            out,
            "! mcp servers      {e:#}; `openmoat mcp unwrap` restores the wrapped ones"
        )?;
    }
    let mut undone = Vec::new();
    let mut recorded = Recorded::load(&home)?;
    for host in hosts.iter().copied() {
        let config = HostConfig::for_host(&home, host)?;
        let sandbox = host_sandbox::backend(host).map(SandboxBackend::undo);
        // A sandbox kept in the same file as the hooks goes with them.
        let with_hooks = match sandbox {
            Some(Undo::WithHooks(remove)) => Some(remove),
            _ => None,
        };
        let owned = &recorded.claude_rules;
        let ours = &recorded.backups;
        let strip = |root: &mut Value| {
            config.remove(root) | with_hooks.is_some_and(|remove| remove(root, owned))
        };
        let path = &config.settings_path;
        let plugin = matches!(config.layout, HookLayout::Plugin(_));
        // A hook file OpenMoat owns whole (pi's extension, OpenCode's plugin) is not JSON.
        let hook = match config.layout {
            HookLayout::Owned(file) => undo_whole(path, ours, |text| file.is_ours(text))?,
            HookLayout::Yaml(layout) => undo_yaml(&config, layout, ours)?,
            HookLayout::Entries(_) | HookLayout::Plugin(_) => {
                undo_host_json(path, ours, strip, plugin)?
            }
        };
        let mut files = vec![(path.clone(), hook)];
        // The host's record of consent to OpenMoat's hook (Hermes Agent's allowlist).
        if let Some((consent_path, consent)) = install::consent::of(&config) {
            let id = host.id();
            let undone = undo_consent(&consent_path, ours, consent, id)?;
            files.push((consent_path, undone));
        }
        // A sandbox in a file of its own.
        match sandbox {
            Some(Undo::Toml(remove)) => {
                let path = host_sandbox::settings_path(&home, host)?;
                files.push((path.clone(), undo_toml(&path, ours, remove)?));
            }
            Some(Undo::Json(remove)) => {
                let path = host_sandbox::settings_path(&home, host)?;
                files.push((path.clone(), undo_json(&path, ours, remove)?));
            }
            Some(Undo::WithHooks(_)) | None => {}
        }
        // OpenClaw's hook is the plugin file `init` wrote, which nothing else owns.
        if plugin && let Some(plugin) = install::openclaw::remove_plugin(&config)? {
            files.push((plugin, Some(Undone::Deleted)));
        }
        if files.iter().all(|(_, done)| done.is_none()) {
            writeln!(out, "· {:<16} not set up", host.display_name())?;
        }
        for (path, done) in files {
            if let Some(done) = done {
                writeln!(
                    out,
                    "✔ {:<16} {} {done}",
                    host.display_name(),
                    path.display()
                )?;
                undone.push(path);
            }
        }
    }
    // The files are undone first: until then the record says where they are.
    let before = recorded.dirs.len();
    recorded
        .dirs
        .retain(|id, _| !hosts.iter().any(|h| h.id() == id));
    recorded
        .files
        .retain(|id, _| !hosts.iter().any(|h| h.id() == id));
    let forgot_rules = hosts
        .iter()
        .filter_map(|h| host_sandbox::backend(*h))
        .any(|b| matches!(b.undo(), Undo::WithHooks(_)))
        && !recorded.claude_rules.is_empty();
    if forgot_rules {
        recorded.claude_rules.clear();
    }
    let backups_before = recorded.backups.len();
    recorded.backups.retain(|b| b.exists());
    let mut rewritten = Vec::new();
    if recorded.dirs.len() != before || forgot_rules || recorded.backups.len() != backups_before {
        recorded.save(&home)?;
        rewritten.push(home.hosts_path());
    }
    integrity::unpin(&home, &undone, &rewritten)?;
    // If the proxy service was installed, stop and remove it alongside the
    // hooks: leaving it behind would keep listening with a stale binary
    // reference once hooks are gone.
    match super::service::manager(&home).and_then(|m| m.uninstall()) {
        Ok(Some(path)) => writeln!(out, "✔ proxy service    removed: {}", path.display())?,
        Ok(None) => {}
        Err(e) => writeln!(
            out,
            "! proxy service    {e:#}; `openmoat proxy uninstall` removes it by hand"
        )?,
    }
    if args.purge {
        purge(&home)?;
        writeln!(out, "✔ state directory  {} deleted", home.root().display())?;
    } else if home.exists() {
        writeln!(
            out,
            "· state directory  {} kept (policy, audit log); `openmoat uninstall --purge` deletes it",
            home.root().display()
        )?;
    }
    out.finish()?;
    Ok(Code::Ok)
}

/// What happened to one host file, worded to follow its path.
enum Undone {
    Restored(PathBuf),
    Deleted,
    Stripped(Vec<PathBuf>),
}

impl std::fmt::Display for Undone {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Restored(backup) => write!(f, "restored from {}", backup.display()),
            Self::Deleted => write!(f, "deleted (openmoat init created it)"),
            Self::Stripped(kept) if kept.is_empty() => {
                write!(f, "OpenMoat's entries removed, your changes kept")
            }
            Self::Stripped(kept) => {
                let kept: Vec<String> = kept.iter().map(|p| p.display().to_string()).collect();
                write!(
                    f,
                    "OpenMoat's entries removed, your changes kept (backup kept: {})",
                    kept.join(", ")
                )
            }
        }
    }
}

/// `strip` is run on the backups too: one it changes was taken between two
/// OpenMoat edits (the sandbox backup of a file the hook edit created), so it
/// is not the user's original. `ours` are the backups OpenMoat created.
fn undo_json(
    path: &Path,
    ours: &[PathBuf],
    strip: impl Fn(&mut Value) -> bool,
) -> Result<Option<Undone>> {
    undo_host_json(path, ours, strip, false)
}

/// [`undo_json`]; `plugin` (OpenClaw's `openclaw.json`) reads the file and its
/// backups as JSON5 and refuses to write back a file whose comments that would
/// drop.
fn undo_host_json(
    path: &Path,
    ours: &[PathBuf],
    strip: impl Fn(&mut Value) -> bool,
    plugin: bool,
) -> Result<Option<Undone>> {
    if !path.is_file() {
        return Ok(None);
    }
    let read = |p: &Path| {
        if plugin {
            install::openclaw::read(p)
        } else {
            read_or_empty(p)
        }
    };
    let mut root = read(path)?;
    if !strip(&mut root) {
        return Ok(None);
    }
    let backups = install::backups(path);
    let originals: Vec<(&PathBuf, Value)> = backups
        .iter()
        .filter_map(|b| Some((b, read(b).ok()?)))
        .filter(|(_, v)| !strip(&mut v.clone()))
        .collect();
    let original = originals.iter().find(|(_, v)| *v == root).map(|(b, _)| *b);
    let created = originals.is_empty() && root == json!({});
    if plugin && original.is_none() && !created {
        install::openclaw::read_for_edit(path)?;
    }
    let text = serde_json::to_string_pretty(&root)? + "\n";
    finish(path, &owned(&backups, ours), original, created, &text).map(Some)
}

/// A YAML hook file (Hermes Agent's `config.yaml`): OpenMoat's lines taken
/// out as text, so the rest stays as the person and the host left it; the
/// backup's bytes when what is left is the document it holds.
fn undo_yaml(
    config: &HostConfig,
    layout: &'static dyn openmoat_hosts::HookFile,
    ours: &[PathBuf],
) -> Result<Option<Undone>> {
    let path = &config.settings_path;
    if !path.is_file() {
        return Ok(None);
    }
    let text = fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
    let Some(stripped) = install::yaml::remove(config, layout, &text)? else {
        return Ok(None);
    };
    let left = openmoat_hosts::yaml_hooks::parse(&stripped).ok();
    let backups = install::backups(path);
    let originals: Vec<(&PathBuf, Option<Value>)> = backups
        .iter()
        .filter_map(|b| {
            let text = fs::read_to_string(b).ok()?;
            let unchanged = install::yaml::remove(config, layout, &text).ok()?.is_none();
            unchanged.then(|| (b, openmoat_hosts::yaml_hooks::parse(&text).ok()))
        })
        .collect();
    let original = originals
        .iter()
        .find(|(_, doc)| doc.is_some() && *doc == left)
        .map(|(b, _)| *b);
    let created = originals.is_empty() && stripped.trim().is_empty();
    finish(path, &owned(&backups, ours), original, created, &stripped).map(Some)
}

/// The host's consent file: OpenMoat's commands taken out; deleted when `init`
/// created it and nothing else is left in it.
fn undo_consent(
    path: &Path,
    ours: &[PathBuf],
    consent: &dyn openmoat_hosts::ConsentFile,
    id: &str,
) -> Result<Option<Undone>> {
    if !path.is_file() {
        return Ok(None);
    }
    let mut root = read_or_empty(path)?;
    if !consent.remove(&mut root, id) {
        return Ok(None);
    }
    let backups = install::backups(path);
    let originals: Vec<(&PathBuf, Value)> = backups
        .iter()
        .filter_map(|b| Some((b, read_or_empty(b).ok()?)))
        .filter(|(_, v)| !consent.remove(&mut v.clone(), id))
        .collect();
    let original = originals.iter().find(|(_, v)| *v == root).map(|(b, _)| *b);
    let created = originals.is_empty() && consent.is_empty(&root);
    let text = serde_json::to_string_pretty(&root)? + "\n";
    finish(path, &owned(&backups, ours), original, created, &text).map(Some)
}

/// A hook file that is OpenMoat's whole (pi's extension, OpenCode's plugin):
/// deleted, or the person's file `init` backed up before writing it given
/// back. A file there
/// that `is_ours` does not recognise is the person's and stays.
fn undo_whole(
    path: &Path,
    ours: &[PathBuf],
    is_ours: impl Fn(&str) -> bool,
) -> Result<Option<Undone>> {
    if !path.is_file() {
        return Ok(None);
    }
    let text = fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
    if !is_ours(&text) {
        return Ok(None);
    }
    let backups = install::backups(path);
    let original = backups
        .iter()
        .find(|b| fs::read_to_string(b).is_ok_and(|t| !is_ours(&t)));
    finish(
        path,
        &owned(&backups, ours),
        original,
        original.is_none(),
        "",
    )
    .map(Some)
}

/// [`undo_json`] for a TOML file, `strip` removing OpenMoat's part.
fn undo_toml(
    path: &Path,
    ours: &[PathBuf],
    strip: fn(&mut DocumentMut) -> bool,
) -> Result<Option<Undone>> {
    if !path.is_file() {
        return Ok(None);
    }
    let read = crate::sandbox::install::read_toml;
    let mut doc = read(path)?;
    if !strip(&mut doc) {
        return Ok(None);
    }
    let text = doc.to_string();
    let backups = install::backups(path);
    let originals: Vec<&PathBuf> = backups
        .iter()
        .filter(|b| read(b).is_ok_and(|mut d| !strip(&mut d)))
        .collect();
    let original = originals
        .iter()
        .find(|b| fs::read_to_string(b).is_ok_and(|t| t == text))
        .copied();
    let created = originals.is_empty() && text.trim().is_empty();
    finish(path, &owned(&backups, ours), original, created, &text).map(Some)
}

/// The `backups` OpenMoat created: the only ones uninstall deletes or lists.
fn owned(backups: &[PathBuf], ours: &[PathBuf]) -> Vec<PathBuf> {
    backups
        .iter()
        .filter(|b| ours.contains(b))
        .cloned()
        .collect()
}

/// Write the undone file: the original backup's bytes; nothing when `init`
/// `created` it; else `text`. OpenMoat's backups go once the file is back as
/// it was; `original` may be any file at a backup's name whose content matches.
fn finish(
    path: &Path,
    backups: &[PathBuf],
    original: Option<&PathBuf>,
    created: bool,
    text: &str,
) -> Result<Undone> {
    let undone = match original {
        Some(backup) => {
            let bytes =
                fs::read(backup).with_context(|| format!("reading {}", backup.display()))?;
            write_private(path, &bytes)?;
            Undone::Restored(backup.clone())
        }
        None if created => {
            fs::remove_file(path).with_context(|| format!("deleting {}", path.display()))?;
            Undone::Deleted
        }
        None => {
            write_private(path, text.as_bytes())?;
            return Ok(Undone::Stripped(backups.to_vec()));
        }
    };
    for backup in backups {
        fs::remove_file(backup).with_context(|| format!("deleting {}", backup.display()))?;
    }
    Ok(undone)
}

/// Delete the state directory, but only one that looks like OpenMoat's:
/// `MOAT_HOME` may point anywhere, the home directory included.
fn purge(home: &Home) -> Result<()> {
    if !home.exists() {
        return Ok(());
    }
    let root = home.root();
    ensure!(
        root != user_home()? && (home.policy_path().is_file() || home.lock_path().is_file()),
        "{} does not look like OpenMoat's state directory; delete it yourself",
        root.display()
    );
    fs::remove_dir_all(root).with_context(|| format!("deleting {}", root.display()))
}