openmoat 0.17.0

Policy checks for AI coding agents: decides allow, defer, review 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
//! `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 crate::cli::{DoctorArgs, Format};
use crate::exit::Code;
use crate::home::Home;
use crate::integrity::{self, HookPinGap, HookPins, Lock};
use crate::protection;
use crate::render::Deferred;
use crate::report::{Mark, Row};
use human::Place;
use rows::Report;

mod bundle;
mod hooks;
mod human;
mod json;
mod mcp;
mod rows;
mod sandboxes;
mod warnings;

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

/// 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) {
        report.line(Area::Service, ok, text);
    }
}

pub fn run(args: &DoctorArgs) -> Result<Code> {
    let home = Home::locate()?;
    let binary = crate::install::hook_binary()?;
    let as_json = args.format == Format::Json;
    let mut report = Report::new(if as_json || args.bundle.is_some() {
        Deferred::quiet()
    } else {
        Deferred::default()
    });

    report.line(
        Area::State,
        home.exists(),
        format!("state directory  {}", home.root().display()),
    );
    let policy = policies(&mut report, &home);
    if let Some(update) = crate::upgrade::available(&home) {
        report.warn_as(
            &format!("policy update    {update}: `openmoat policy upgrade` shows them and asks"),
            Row::new(Mark::Attention, "Policy", format!("{update} to review"))
                .fix("openmoat policy upgrade"),
        );
    }
    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::hooks(&mut report, &home, &binary)?;
    if let Some(lock) = &lock {
        hook_pins(&mut report, lock, &home, &hook_files);
        mcp::lines(&mut report, &home, lock, &binary);
    }
    if let Some(policy) = &policy {
        sandboxes::sandboxes(
            &mut report,
            &home,
            policy,
            lock.as_ref(),
            &binary,
            args.verbose,
        );
    }
    service(&mut report, &home);
    let open = warnings::tiocsti_open(&home, &binary)?;
    let tiocsti = warnings::tiocsti(open, warnings::legacy_tiocsti().as_deref());
    let hangs = warnings::hangs(&home, crate::time::now_ms());
    let linux = cfg!(target_os = "linux");
    let state = policy
        .as_ref()
        .and_then(|policy| warnings::state_in_grant(&home, policy, linux));
    let macos = warnings::old_macos(crate::os_version::macos().as_deref());
    let network = super::run::port_only_network();
    let lightweight = super::run::tier::doctor_warning(super::run::bubblewrap());
    let alias = warnings::alias_hooks(&home, &binary);
    for warning in [tiocsti, hangs, state, macos, network, lightweight]
        .into_iter()
        .flatten()
        .chain(alias)
    {
        report.warn(&warning);
    }
    report.note(warnings::RENAMED);
    // Loaded when a session starts here, where no `ConfigChange` fires.
    for warning in crate::project_settings::warnings_here(&home) {
        let name = warning.host.display_name();
        report.warn(&format!("{name:<16} project settings {}", warning.text));
    }
    for warning in crate::project_settings::other_hooks::warnings_here(&home) {
        let name = warning.host.display_name();
        report.warn(&format!("{name:<16} other hook {}", warning.text));
    }
    // Run by the agent's own git when a session starts, before any hook.
    for warning in crate::project_settings::git_config::warnings_here() {
        report.warn(&format!("{:<16} git config {warning}", "Repository"));
    }
    protections(&mut report, &home, &binary)?;
    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 let Some(last) = crate::anchor::Last::load(&home) {
        let text = format!(
            "audit anchor     last made {} (event {}) in {}",
            crate::time::timestamp(last.anchored_ms),
            last.event,
            last.to
        );
        report.note_at(&text, Place::OpenMoat);
    }
    if !as_json && args.bundle.is_none() {
        let agents = std::mem::take(&mut report.agents);
        human::sections(&mut report, &agents, args.verbose);
    }
    if args.accept {
        let intact = drift.is_empty() && lock.is_some();
        accept(&mut report, &home, &binary, policy.is_some(), intact)?;
    }
    if let Some(path) = &args.bundle {
        return bundle::write(&home, &binary, &report.rows, path, args.bundle_events);
    }
    if as_json {
        return json::finish(&report.rows, report.problems.len());
    }
    finish(report, args.verbose)
}

/// Each agent's protection level, its limit and its known gaps; the text
/// output shows the level in its `Agents` section, the rest with `--verbose`.
fn protections(report: &mut Report, home: &Home, binary: &Path) -> Result<()> {
    let agents = protection::report(home, binary)?;
    for agent in &agents {
        if let Some(line) = crate::install::trust_note::protection_line(agent) {
            report.note(&line);
            if let Some(limit) = agent.limit {
                // Shown under the agent's row (`report::agent_table`).
                let text = format!("{:<16} limit: {limit}", agent.name);
                report.warn_at(&text, Place::Details);
            }
            report.note(&format!("{:<16} known gaps: {}", agent.name, agent.gaps));
        }
    }
    report.agents = agents;
    Ok(())
}

/// 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, review) = policy.rule_count();
            report.line_as(
                Area::Policy,
                true,
                format!("policy           lints ({deny} deny, {allow} allow, {review} review)"),
                Place::OpenMoat,
                Row::new(
                    Mark::Ok,
                    "Policy",
                    format!("{deny} deny · {allow} allow · {review} review rules"),
                ),
            );
            Some(policy)
        }
        Err(e) => {
            report.line(Area::Policy, false, format!("policy           {e:#}"));
            None
        }
    };
    match crate::repo::summary(home) {
        Ok(Some(line)) => report.note_at(&format!("repo policy      {line}"), Place::OpenMoat),
        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 `openmoat 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 let Some(warning) = warnings::alias_lock(&lock.binary, binary) {
        report.warn(&warning);
    } else if lock.binary != binary.to_string_lossy() {
        report.line(
            Area::Binary,
            false,
            format!(
                "binary           lock expects {}, running {}; run `openmoat 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 `openmoat 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 `openmoat init` to pin it",
                path.display()
            ),
        );
    }
    for path in gap.elsewhere {
        let (path, moved) = (path.display(), HookPinGap::moved_by());
        report.note_at(
            &format!(
                "hook file        {path} is pinned but not this shell's ({moved}); re-pinning keeps it"
            ),
            Place::OpenMoat,
        );
    }
}

/// `--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<()> {
    crate::terminal::refuse_agent("openmoat doctor --accept")?;
    if !crate::terminal::interactive() {
        bail!(
            "`openmoat 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 `openmoat doctor --accept` again"
        );
    }
    writeln!(report.out)?;
    if intact {
        // MCP definitions are not files of the lock: accepted on their own, after
        // a person has seen each change.
        if home.lock_path().is_file() {
            mcp::accept(report, home, binary)?;
        }
        writeln!(report.out, "nothing else 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));
    mcp::accept(report, home, binary)
}

/// The closing line, the output and the exit code.
fn finish(mut report: Report, verbose: bool) -> Result<Code> {
    human::footer(&mut report, verbose);
    let healthy = report.problems.is_empty();
    report.out.finish()?;
    Ok(if healthy { Code::Ok } else { Code::Usage })
}

/// 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
        ),
    );
    // Shown without --verbose: the head is what a person records elsewhere.
    if let Some(head) = &chain.head {
        report.note_at(
            &format!(
                "audit log        head {head}; record it elsewhere (`openmoat audit anchor`), then `openmoat audit verify --against` it later"
            ),
            Place::OpenMoat,
        );
    }
    if chain.unchained > 0 {
        report.note_at(
            &format!(
                "audit log        {} events written before the hash chain existed are not covered",
                chain.unchained
            ),
            Place::OpenMoat,
        );
    }
}