openmoat 0.3.0

Policy guard for AI coding agents: decides allow, 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
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
//! `moat doctor`: verify the installation and, from a terminal, accept changes.

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

use anyhow::{Result, bail};
use openmoat_audit::{ChainReport, Store};
use openmoat_core::Policy;
use openmoat_hosts::Host;

use crate::cli::DoctorArgs;
use crate::exit::Code;
use crate::home::Home;
use crate::install::{
    CONTINUE_CLI_WARNING, HookState, HostConfig, Recorded, dir_variable, env_config_dir, stale_hint,
};
use crate::integrity::{self, HookPinGap, HookPins, Lock};
use crate::protection;
use crate::render::Deferred;
use crate::sandbox::{Plan, install as host_sandbox};

use super::sandbox::write_report;

/// What a check is about, so accepting changes clears exactly the problems a
/// re-pin fixes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Area {
    State,
    Policy,
    Lock,
    Binary,
    Environment,
    Hook,
    Sandbox,
    Audit,
    Service,
}

/// The Standard tier: each present host's sandbox settings against the policy,
/// then how many places the translation loses or widens (each one with `verbose`).
fn sandboxes(
    report: &mut Report,
    policy: &Policy,
    lock: Option<&Lock>,
    recorded: &Recorded,
    verbose: bool,
) {
    let plan = match Plan::new(policy) {
        Ok(plan) => plan,
        Err(e) => {
            report.line(Area::Sandbox, false, format!("sandbox          {e:#}"));
            return;
        }
    };
    let mut present = false;
    for host in host_sandbox::HOSTS
        .into_iter()
        .filter(|h| !recorded.skipped(*h))
    {
        let name = host.display_name();
        let problems = host_sandbox::problems(host, &plan, lock);
        if let (Ok(Some(_)), Some(note)) = (&problems, host_sandbox::unavailable(host)) {
            report.note(&format!("{name:<16} {note}"));
            continue;
        }
        present |= !matches!(problems, Ok(None));
        let translation = host_sandbox::report(host, &plan);
        match problems {
            Ok(None) => continue,
            Ok(Some(problems)) if problems.is_empty() => {
                let details = if verbose {
                    ""
                } else {
                    "; --verbose for details"
                };
                report.line(
                    Area::Sandbox,
                    true,
                    format!(
                        "{name:<16} sandbox matches the policy ({} stricter, {} wider{details})",
                        translation.losses.len(),
                        translation.allowances.len()
                    ),
                );
            }
            Ok(Some(problems)) => {
                for problem in problems {
                    report.line(
                        Area::Sandbox,
                        false,
                        format!("{name:<16} sandbox: {problem}"),
                    );
                }
            }
            Err(e) => report.line(Area::Sandbox, false, format!("{name:<16} sandbox: {e:#}")),
        }
        if verbose {
            let _ = write_report(&mut report.out, translation);
        }
    }
    if let Some(port) = plan.proxy_port.filter(|_| present) {
        // A warning, not a problem: a stopped proxy fails closed.
        let (ok, text) = super::proxy::listening_line(port);
        let _ = writeln!(
            report.out,
            "{} moat proxy       {text}",
            if ok { "✔" } else { "!" }
        );
    }
}

/// The `moat doctor` line for the proxy user service (`moat proxy install`,
/// #272). A missing service is silent (opt-in); a drift-blocked or
/// crash-looping service is a problem; a running one is a check.
fn service(report: &mut Report, home: &Home) {
    if let Some((ok, text)) = super::proxy::service_line(home) {
        if ok {
            report.line(Area::Service, true, text);
        } else {
            report.line(Area::Service, false, text);
        }
    }
}

struct Report {
    problems: Vec<(Area, String)>,
    out: Deferred,
}

impl Report {
    fn line(&mut self, area: Area, ok: bool, text: String) {
        // `Deferred` keeps a write error for `finish`; it never returns one here.
        let _ = writeln!(self.out, "{} {text}", if ok { "✔" } else { "✗" });
        if !ok {
            self.problems.push((area, text));
        }
    }

    fn note(&mut self, text: &str) {
        let _ = writeln!(self.out, "· {text}");
    }
}

pub fn run(args: &DoctorArgs) -> Result<Code> {
    let home = Home::locate()?;
    let binary = crate::install::hook_binary()?;
    let mut report = Report {
        problems: Vec::new(),
        out: Deferred::default(),
    };

    report.line(
        Area::State,
        home.exists(),
        format!("state directory  {}", home.root().display()),
    );
    let policy = policies(&mut report, &home);
    let lock = load_lock(&mut report, &home);
    let drift = lock
        .as_ref()
        .map(|lock| verify_lock(&mut report, lock, &binary))
        .unwrap_or_default();
    environment(&mut report, &home);
    let hook_files = hooks(&mut report, &home, &binary)?;
    if let Some(lock) = &lock {
        hook_pins(&mut report, lock, &home, &hook_files);
    }
    if let Some(policy) = &policy {
        let recorded = Recorded::load(&home).unwrap_or_default();
        sandboxes(&mut report, policy, lock.as_ref(), &recorded, args.verbose);
    }
    service(&mut report, &home);
    for agent in protection::report(&home, &binary)? {
        if let Some(summary) = agent.summary() {
            report.note(&format!("{:<16} protection: {summary}", agent.name));
            report.note(&format!("{:<16} known gaps: {}", agent.name, agent.gaps));
        }
    }
    match Store::open_read_only(&home.audit_path()).and_then(|store| store.verify_chain()) {
        Ok(chain) => audit_line(&mut report, &chain),
        Err(e) => report.line(Area::Audit, false, format!("audit log        {e}")),
    }
    if args.accept {
        let intact = drift.is_empty() && lock.is_some();
        accept(&mut report, &home, &binary, policy.is_some(), intact)?;
    }
    finish(report)
}

/// The policy line and, in a project with one, the repository policy line;
/// the policy when it lints.
fn policies(report: &mut Report, home: &Home) -> Option<Policy> {
    let policy = match home.load_policy() {
        Ok(policy) => {
            let (deny, allow, ask) = policy.rule_count();
            report.line(
                Area::Policy,
                true,
                format!("policy           lints ({deny} deny, {allow} allow, {ask} ask)"),
            );
            Some(policy)
        }
        Err(e) => {
            report.line(Area::Policy, false, format!("policy           {e:#}"));
            None
        }
    };
    match crate::repo::summary(home) {
        Ok(Some(line)) => report.note(&format!("repo policy      {line}")),
        Ok(None) => {}
        Err(e) => report.line(
            Area::Policy,
            false,
            format!("repo policy      {e:#}; every call in this project is denied"),
        ),
    }
    policy
}

/// The lock, or the line saying why there is none.
fn load_lock(report: &mut Report, home: &Home) -> Option<Lock> {
    let lock_path = home.lock_path();
    match Lock::load(&lock_path) {
        Ok(lock) => Some(lock),
        Err(_) if !lock_path.exists() => {
            report.line(
                Area::Lock,
                false,
                "lock             missing; run `moat init`".to_owned(),
            );
            None
        }
        Err(e) => {
            report.line(Area::Lock, false, format!("lock             {e:#}"));
            None
        }
    }
}

/// The lock lines: what drifted, and whether the lock pins this binary;
/// returns the drift.
fn verify_lock(report: &mut Report, lock: &Lock, binary: &Path) -> Vec<integrity::Drift> {
    let drift = lock.verify();
    if drift.is_empty() {
        report.line(
            Area::Lock,
            true,
            format!(
                "lock             {} files pinned, all intact",
                lock.entries.len()
            ),
        );
    }
    for d in &drift {
        report.line(Area::Lock, false, format!("lock             {d}"));
    }
    if lock.binary != binary.to_string_lossy() {
        report.line(
            Area::Binary,
            false,
            format!(
                "binary           lock expects {}, running {}; run `moat init`",
                lock.binary,
                binary.display()
            ),
        );
    }
    drift
}

/// The search-path snapshot line.
fn environment(report: &mut Report, home: &Home) {
    match crate::environment::Snapshot::load(&home.environment_path()) {
        Ok(snapshot) => report.line(
            Area::Environment,
            true,
            format!(
                "environment      {} dirs, {} programs pinned",
                snapshot.path.len(),
                snapshot.programs.len()
            ),
        ),
        Err(e) => report.line(
            Area::Environment,
            false,
            format!("environment      {e:#}; run `moat init`"),
        ),
    }
}

/// Installed hook files the lock does not pin, and pinned ones this shell
/// does not use.
fn hook_pins(report: &mut Report, lock: &Lock, home: &Home, hook_files: &[PathBuf]) {
    let gap = HookPinGap::new(lock, home, hook_files);
    for path in gap.unpinned {
        report.line(
            Area::Hook,
            false,
            format!(
                "hook file        {} is not pinned by the lock; run `moat init` to pin it",
                path.display()
            ),
        );
    }
    for path in gap.elsewhere {
        report.note(&format!(
            "hook file        {} is pinned but not this shell's (CLAUDE_CONFIG_DIR, CODEX_HOME or CURSOR_CONFIG_DIR differ); re-pinning keeps it",
            path.display()
        ));
    }
}

/// `--accept`: re-pin from a terminal when the policy lints and the lock is
/// not intact, clearing the problems a re-pin fixes.
fn accept(
    report: &mut Report,
    home: &Home,
    binary: &Path,
    policy_lints: bool,
    intact: bool,
) -> Result<()> {
    if !crate::terminal::interactive() {
        bail!(
            "`moat doctor --accept` must be run by a person in a terminal, not from a hook or script"
        );
    }
    if !policy_lints {
        bail!(
            "refusing to pin a policy that does not lint; fix it, then run `moat doctor --accept` again"
        );
    }
    if intact {
        writeln!(report.out, "nothing to accept: lock is intact")?;
        return Ok(());
    }
    let lock = integrity::repin(home, binary, HookPins::Keep)?;
    writeln!(
        report.out,
        "✔ lock re-pinned for {} files",
        lock.entries.len()
    )?;
    report
        .problems
        .retain(|(area, _)| !matches!(area, Area::Lock | Area::Binary));
    Ok(())
}

/// The closing line, the output and the exit code.
fn finish(mut report: Report) -> Result<Code> {
    if report.problems.is_empty() {
        writeln!(report.out, "healthy")?;
        report.out.finish()?;
        return Ok(Code::Ok);
    }
    writeln!(
        report.out,
        "{} problem(s). `moat init` re-installs and re-pins; `moat doctor --accept` accepts edits you made yourself.",
        report.problems.len()
    )?;
    report.out.finish()?;
    Ok(Code::Usage)
}

/// One line per host's hook, then the Continue CLI warning; returns the
/// installed hook files.
fn hooks(report: &mut Report, home: &Home, binary: &Path) -> Result<Vec<PathBuf>> {
    let recorded = Recorded::load(home)?;
    let mut hook_files = Vec::new();
    for host in Host::ALL {
        let config = HostConfig::for_host(host)?;
        let name = host.display_name();
        // Every command follows the record; a variable naming another directory
        // is reported rather than silently ignored or followed.
        if let (Some(env), Some(dir)) = (env_config_dir(host)?, recorded.dir(host))
            && env != dir
        {
            let (var, _) = dir_variable(host)?;
            report.line(
                Area::Hook,
                false,
                format!(
                    "{name:<16} {var} is {}, but `moat init` set it up in {}, which moat uses; \
                     run `moat init` with {var} set to set up that directory instead",
                    env.display(),
                    dir.display()
                ),
            );
        }
        let state = config.state(binary);
        if recorded.skipped(host) && config.host_present() && matches!(state, HookState::Missing) {
            report.note(&format!(
                "{name:<16} not set up; `moat init --hosts {}` adds it",
                host.id()
            ));
            continue;
        }
        match state {
            HookState::Installed => {
                hook_files.push(config.settings_path.clone());
                report.line(
                    Area::Hook,
                    true,
                    format!(
                        "{name:<16} hook installed  {}",
                        config.settings_path.display()
                    ),
                );
            }
            HookState::Missing if !config.host_present() => {
                report.note(&format!("{name:<16} host not found"));
            }
            HookState::Missing => {
                report.line(
                    Area::Hook,
                    false,
                    format!("{name:<16} hook missing; run `moat init`"),
                );
            }
            HookState::Stale { command } => {
                report.line(
                    Area::Hook,
                    false,
                    format!("{name:<16} {}", stale_hint(&command)),
                );
            }
            HookState::Unreadable(e) => {
                report.line(Area::Hook, false, format!("{name:<16} {e}"));
            }
        }
    }
    if let Some(found) = crate::install::continue_cli()? {
        let name = Host::Continue.display_name();
        report.note(&format!(
            "{name:<16} {CONTINUE_CLI_WARNING}  {}",
            found.display()
        ));
    }
    Ok(hook_files)
}

/// The audit log line: event count and whether the hash chain holds.
fn audit_line(report: &mut Report, chain: &ChainReport) {
    if let Some(broken) = &chain.broken {
        report.line(
            Area::Audit,
            false,
            format!(
                "audit log        hash chain broken at event {}: {}; keep the file as evidence",
                broken.id,
                broken.kind.describe()
            ),
        );
        return;
    }
    report.line(
        Area::Audit,
        true,
        format!(
            "audit log        {} events, hash chain intact",
            chain.events
        ),
    );
    if let Some(head) = &chain.head {
        report.note(&format!(
            "audit log        head {head}; record it elsewhere, then `moat audit verify --anchor` a later export"
        ));
    }
    if chain.unchained > 0 {
        report.note(&format!(
            "audit log        {} events written before the hash chain existed are not covered",
            chain.unchained
        ));
    }
}