openmoat 0.9.0

Policy checks for AI coding agents: decides allow, defer, ask or deny for every tool call from Claude Code, Codex and Cursor, configures Claude Code's and Codex'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
//! Idempotent edits to a host's JSON hook file.
//!
//! Claude Code (`settings.json`) and Codex (`hooks.json`) share the shape
//! `{"hooks": {"<Event>": [{"matcher": …, "hooks": [{type, command, args, timeout}]}]}}`.
//! Gemini CLI's `settings.json` has the same nesting with one shell string as
//! the `command` ([`gemini`]). Our entries are recognised by their `args`
//! (`guard --host <id>`), or the end of that command string, so re-running
//! `init` updates the binary path and matcher in place and never duplicates.
//! Unrelated settings are preserved byte-for-byte as JSON values.

use std::fs;
use std::path::Path;

use anyhow::{Context as _, Result, bail};
use serde_json::{Map, Value, json};

use super::{HOOK_BACKUP, HookFormat, HookSpec, HostConfig, openclaw, pi};
use crate::home::{Home, write_private};

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Outcome {
    Unchanged,
    Updated,
    Installed,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HookState {
    Missing,
    Installed,
    /// Present but pointing at a different binary or matcher, or missing one event.
    Stale {
        command: String,
    },
    Unreadable(String),
}

pub fn install(home: &Home, config: &HostConfig, binary: &Path, dry_run: bool) -> Result<Outcome> {
    // pi's hook file is OpenMoat's extension itself, not JSON.
    if config.format == HookFormat::Pi {
        return pi::install(home, config, binary, dry_run);
    }
    let path = &config.settings_path;
    let mut root = read_host(config)?;
    let edited = upsert_all(&mut root, config, binary)?;
    if edited != Outcome::Unchanged && config.format == HookFormat::OpenClaw {
        openclaw::read_for_edit(path)?;
    }
    // OpenClaw's hook is a plugin file in its state directory.
    let plugin = config.format == HookFormat::OpenClaw && !openclaw::plugin_current(config, binary);
    let outcome = if plugin {
        edited.max(Outcome::Updated)
    } else {
        edited
    };
    if outcome == Outcome::Unchanged || dry_run {
        return Ok(outcome);
    }
    if plugin {
        openclaw::write_plugin(config, binary)?;
    }
    if edited != Outcome::Unchanged {
        super::back_up(home, path, HOOK_BACKUP)?;
        let text = serde_json::to_string_pretty(&root)? + "\n";
        write_private(path, text.as_bytes())?;
    }
    Ok(outcome)
}

/// `current` (the text of the host's hook file, empty when there is none)
/// with OpenMoat's hooks in it, as [`install`] would write it; `None` when it
/// would not change. Writes nothing.
pub fn render(config: &HostConfig, binary: &Path, current: &str) -> Result<Option<String>> {
    if config.format == HookFormat::Pi {
        return pi::render(binary, current);
    }
    if config.format == HookFormat::OpenClaw {
        let parsed = openclaw::parse(current)
            .with_context(|| format!("parsing {}", config.settings_path.display()))?;
        let mut root = parsed.value.clone();
        if upsert_all(&mut root, config, binary)? == Outcome::Unchanged {
            return Ok(None);
        }
        openclaw::refuse_comments(&parsed, &config.settings_path)?;
        return Ok(Some(serde_json::to_string_pretty(&root)? + "\n"));
    }
    let mut root = crate::sandbox::install::parse_json(current)?;
    if upsert_all(&mut root, config, binary)? == Outcome::Unchanged {
        return Ok(None);
    }
    Ok(Some(serde_json::to_string_pretty(&root)? + "\n"))
}

fn upsert_all(root: &mut Value, config: &HostConfig, binary: &Path) -> Result<Outcome> {
    if config.format == HookFormat::OpenClaw {
        return openclaw::upsert(root, config);
    }
    let mut outcome = Outcome::Unchanged;
    for spec in config.hooks {
        outcome = outcome.max(upsert(root, config, spec, binary)?);
    }
    Ok(outcome)
}

/// The hook's state for `binary`. A hook that runs `binary`'s `moat` alias
/// counts as installed: hooks written before the rename keep working through
/// it, and `init` rewrites them to `binary` ([`upsert`] compares exactly).
pub fn state(config: &HostConfig, binary: &Path) -> HookState {
    let exact = state_for(config, binary);
    if exact == HookState::Installed {
        return exact;
    }
    match super::alias_of(binary) {
        Some(alias) if state_for(config, &alias) == HookState::Installed => HookState::Installed,
        _ => exact,
    }
}

/// Whether the installed hook runs `binary`'s `moat` alias, not `binary`.
pub fn runs_alias(config: &HostConfig, binary: &Path) -> bool {
    state_for(config, binary) != HookState::Installed
        && super::alias_of(binary)
            .is_some_and(|alias| state_for(config, &alias) == HookState::Installed)
}

fn state_for(config: &HostConfig, binary: &Path) -> HookState {
    let path = &config.settings_path;
    if !path.exists() {
        return HookState::Missing;
    }
    if config.format == HookFormat::Pi {
        return pi::state(config, binary);
    }
    let root = match read_host(config) {
        Ok(v) => v,
        Err(e) => return HookState::Unreadable(format!("{e:#}")),
    };
    if config.format == HookFormat::OpenClaw {
        return openclaw::state(config, binary, &root);
    }
    let mut found = 0;
    let mut stale_command = None;
    for spec in config.hooks {
        let ours = root
            .pointer(&format!("/hooks/{}", spec.event))
            .and_then(Value::as_array)
            .and_then(|entries| entries.iter().find(|e| is_ours(e, config)));
        match ours {
            Some(entry)
                if *entry == desired_entry(config, spec, binary, block(config, spec, entry)) =>
            {
                found += 1;
            }
            Some(entry) => {
                stale_command.get_or_insert_with(|| {
                    hook_binary(entry, config).unwrap_or_else(|| "?".into())
                });
            }
            None => {}
        }
    }
    match (found, stale_command) {
        (n, None) if n == config.hooks.len() => HookState::Installed,
        (0, None) => HookState::Missing,
        (_, Some(command)) => HookState::Stale { command },
        (_, None) => HookState::Stale {
            command: binary.to_string_lossy().into_owned(),
        },
    }
}

/// Whether our entry for `spec` carries `"onFailure": "block"`: it does when it
/// already has the key, so a shell without `claude` on `PATH` never takes the
/// key away, and otherwise when the host's version knows it.
fn block(config: &HostConfig, spec: &HookSpec, existing: &Value) -> bool {
    config.format == HookFormat::Nested
        && (has_block(existing) || (spec.block_on_failure && (config.blocks_on_failure)()))
}

/// [`block`] for an event with no entry of ours yet.
fn block_new(config: &HostConfig, spec: &HookSpec) -> bool {
    config.format == HookFormat::Nested && spec.block_on_failure && (config.blocks_on_failure)()
}

fn has_block(entry: &Value) -> bool {
    entry.pointer("/hooks/0/onFailure") == Some(&json!("block"))
}

fn desired_entry(config: &HostConfig, spec: &HookSpec, binary: &Path, block: bool) -> Value {
    match config.format {
        HookFormat::Nested => {
            let mut hook = json!({
                "type": "command",
                "command": binary.to_string_lossy(),
                "args": ["guard", "--host", config.host.id()],
                "timeout": spec.timeout,
            });
            if block {
                // Claude Code v2.1.295+: a hook that fails to start, crashes,
                // exits other than 0 or 2, or times out blocks the call as exit 2
                // does (<https://code.claude.com/docs/en/hooks>, "Block the
                // action when a hook fails"); without it the call runs.
                hook["onFailure"] = json!("block");
            }
            json!({ "matcher": spec.matcher, "hooks": [hook] })
        }
        HookFormat::Copilot => copilot::entry(config, spec, binary),
        HookFormat::Gemini => json!({
            "matcher": spec.matcher,
            "hooks": [{
                "name": gemini::NAME,
                "type": "command",
                "command": gemini::command(binary, config.host.id()),
                "timeout": spec.timeout * 1000,
            }],
        }),
        // OpenClaw's file is edited by `openclaw` and pi's written by `pi`,
        // before any entry is built here.
        HookFormat::Cursor | HookFormat::OpenClaw | HookFormat::Pi => json!({
            "command": cursor_command(config, binary),
            "timeout": spec.timeout,
            "failClosed": true,
        }),
    }
}

/// Cursor takes one shell string; the binary path is quoted so spaces survive.
fn cursor_command(config: &HostConfig, binary: &Path) -> String {
    let path = binary.to_string_lossy().replace('"', "\\\"");
    format!("\"{path}\" guard --host {}", config.host.id())
}

/// The binary one of our entries runs, unquoted from Cursor's shell string.
fn hook_binary(entry: &Value, config: &HostConfig) -> Option<String> {
    if config.format == HookFormat::Copilot {
        return copilot::binary(entry, config);
    }
    if config.format == HookFormat::Cursor {
        let suffix = format!(" guard --host {}", config.host.id());
        let quoted = entry
            .get("command")?
            .as_str()?
            .trim_end()
            .strip_suffix(&suffix)?;
        return Some(quoted.trim().trim_matches('"').replace("\\\"", "\""));
    }
    let command = entry.pointer("/hooks/0/command").and_then(Value::as_str)?;
    if config.format == HookFormat::Gemini {
        return gemini::binary_of(command, config.host.id());
    }
    Some(command.to_owned())
}

fn is_ours(entry: &Value, config: &HostConfig) -> bool {
    if config.format == HookFormat::Copilot {
        return copilot::is_ours(entry, config);
    }
    if config.format == HookFormat::Gemini {
        return entry
            .get("hooks")
            .and_then(Value::as_array)
            .is_some_and(|hooks| {
                hooks.iter().any(|h| {
                    h.get("command")
                        .and_then(Value::as_str)
                        .is_some_and(|c| gemini::binary_of(c, config.host.id()).is_some())
                })
            });
    }
    if config.format == HookFormat::Cursor {
        let suffix = format!(" guard --host {}", config.host.id());
        return entry
            .get("command")
            .and_then(Value::as_str)
            .is_some_and(|c| c.trim_end().ends_with(&suffix));
    }
    entry
        .get("hooks")
        .and_then(Value::as_array)
        .is_some_and(|hooks| {
            hooks.iter().any(|h| {
                h.get("args").and_then(Value::as_array).is_some_and(|args| {
                    let args: Vec<&str> = args.iter().filter_map(Value::as_str).collect();
                    args == ["guard", "--host", config.host.id()]
                })
            })
        })
}

fn upsert(
    root: &mut Value,
    config: &HostConfig,
    spec: &HookSpec,
    binary: &Path,
) -> Result<Outcome> {
    let Value::Object(top) = root else {
        bail!("{} is not a JSON object", config.settings_path.display());
    };
    if has_version(config) {
        top.entry("version").or_insert_with(|| json!(1));
    }
    let hooks = top
        .entry("hooks")
        .or_insert_with(|| Value::Object(Map::new()));
    let Value::Object(hooks) = hooks else {
        bail!(
            "`hooks` in {} is not an object",
            config.settings_path.display()
        );
    };
    let entries = hooks
        .entry(spec.event)
        .or_insert_with(|| Value::Array(Vec::new()));
    let Value::Array(entries) = entries else {
        bail!(
            "`hooks.{}` in {} is not an array",
            spec.event,
            config.settings_path.display()
        );
    };
    let Some(existing) = entries.iter_mut().find(|e| is_ours(e, config)) else {
        entries.push(desired_entry(config, spec, binary, block_new(config, spec)));
        return Ok(Outcome::Installed);
    };
    let desired = desired_entry(config, spec, binary, block(config, spec, existing));
    if *existing == desired {
        return Ok(Outcome::Unchanged);
    }
    *existing = desired;
    Ok(Outcome::Updated)
}

/// Whether one of our entries that should block a call when `moat guard`
/// fails ([`HookSpec::block_on_failure`]) has no `onFailure`.
pub fn lacks_on_failure(config: &HostConfig) -> bool {
    let Ok(root) = read_or_empty(&config.settings_path) else {
        return false;
    };
    config.format == HookFormat::Nested
        && config
            .hooks
            .iter()
            .filter(|spec| spec.block_on_failure)
            .filter_map(|spec| {
                root.pointer(&format!("/hooks/{}", spec.event))
                    .and_then(Value::as_array)
                    .and_then(|entries| entries.iter().find(|e| is_ours(e, config)))
            })
            .any(|entry| !has_block(entry))
}

/// The inverse of [`install`] on a parsed file: remove every entry of ours, then
/// the events and `hooks` object that leaves empty, and Cursor's `version` when
/// nothing else remains. Returns whether anything was removed.
pub fn remove(root: &mut Value, config: &HostConfig) -> bool {
    if config.format == HookFormat::OpenClaw {
        return openclaw::remove(root);
    }
    let Value::Object(top) = root else {
        return false;
    };
    let Some(Value::Object(hooks)) = top.get_mut("hooks") else {
        return false;
    };
    let mut removed = false;
    hooks.retain(|_, entries| {
        let Value::Array(list) = entries else {
            return true;
        };
        let before = list.len();
        list.retain(|e| !is_ours(e, config));
        removed |= list.len() != before;
        list.len() == before || !list.is_empty()
    });
    if removed && hooks.is_empty() {
        top.remove("hooks");
    }
    if removed && has_version(config) && top.len() == 1 {
        top.retain(|key, value| key != "version" || *value != json!(1));
    }
    removed
}

/// Whether the layout carries `"version": 1` beside `hooks` (Cursor, Copilot).
fn has_version(config: &HostConfig) -> bool {
    matches!(config.format, HookFormat::Cursor | HookFormat::Copilot)
}

/// `config`'s hook file parsed, an empty object when there is none; OpenClaw's
/// as JSON5.
pub fn read_host(config: &HostConfig) -> Result<Value> {
    if config.format == HookFormat::OpenClaw {
        return openclaw::read(&config.settings_path);
    }
    read_or_empty(&config.settings_path)
}

pub fn read_or_empty(path: &Path) -> Result<Value> {
    if !path.exists() {
        return Ok(Value::Object(Map::new()));
    }
    let text = fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
    if text.trim().is_empty() {
        return Ok(Value::Object(Map::new()));
    }
    serde_json::from_str(&text).with_context(|| format!("parsing {}", path.display()))
}

mod copilot;
mod gemini;
#[cfg(test)]
mod tests;