openmoat 0.29.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
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
475
476
477
//! `moat status`: is the kernel installed, current and active? The short form
//! of `openmoat doctor`: what needs the person, one line per agent, OpenMoat's
//! own state and the latest decisions.

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

use anyhow::Result;
use openmoat_audit::Store;
use openmoat_hosts::Host;

use crate::approvals::{self, GRANT_TTL_MS, Grants};
use crate::cli::{Format, StatusArgs};
use crate::exit::Code;
use crate::home::Home;
use crate::integrity::{HookPinGap, Lock};
use crate::report::{Attention, Mark, Printer, Row};
use crate::sandbox::Plan;
use crate::{protection, render, time};

mod agents;
mod foreign_hooks;

/// How many of the newest audit events `status` lists.
const RECENT_EVENTS: usize = 5;

/// The rows `status` prints, by section.
#[derive(Default)]
struct Shown {
    attention: Attention,
    /// Under the agent rows: agents OpenMoat finds but cannot hook.
    agents: Vec<Row>,
    openmoat: Vec<Row>,
}

impl Shown {
    /// A problem (`✗`) or a warning (`!`) in `Needs your attention`.
    fn needs(&mut self, mark: Mark, label: &str, text: impl Into<String>) {
        self.attention.push(Row::new(mark, label, text));
    }

    fn state(&mut self, mark: Mark, label: &str, text: impl Into<String>) {
        self.openmoat.push(Row::new(mark, label, text));
    }
}

pub fn run(args: &StatusArgs) -> Result<Code> {
    let home = Home::locate()?;
    let binary = crate::install::hook_binary()?;
    // A newer default policy's changes reach a person only through `moat policy
    // upgrade`; say so wherever the installation is looked at.
    let update = crate::upgrade::available(&home);
    if args.format == Format::Json {
        render::json(&report(&home, &binary, update.as_ref())?)?;
        return Ok(Code::Ok);
    }
    let mut shown = Shown::default();
    let mut healthy = policies(&mut shown, &home)?;
    if let Some(update) = &update {
        let row = Row::new(Mark::Attention, "Policy", format!("{update} to review"))
            .fix("openmoat policy upgrade");
        shown.attention.push(row);
    }
    healthy &= lock(&mut shown, &home, &binary)?;
    healthy &= mcp_line(&mut shown, &home, &binary);
    healthy &= foreign_hooks::line(&mut shown, &home, &binary);
    // Warnings that leave `healthy` alone: servers that start outside what
    // OpenMoat checks are the person's choice to wrap (ADR-049).
    for line in mcp_outside(&home, &binary) {
        shown.needs(Mark::Attention, "MCP servers", line);
    }
    healthy &= approvals(&mut shown, &home);
    healthy &= agents::hooks(&mut shown, &home, &binary)?;
    // A warning that leaves `healthy` alone: OpenMoat is installed as it should
    // be, and only the person can judge a project's own settings.
    for warning in crate::project_settings::warnings_here(&home) {
        let text = format!("project settings {}", warning.text);
        shown.needs(Mark::Attention, warning.host.display_name(), text);
    }
    for warning in crate::project_settings::other_hooks::warnings_here(&home) {
        let text = format!("other hook {}", warning.text);
        shown.needs(Mark::Attention, warning.host.display_name(), text);
    }
    for warning in crate::project_settings::git_config::warnings_here() {
        shown.needs(
            Mark::Attention,
            "Repository",
            format!("git config {warning}"),
        );
    }
    if let Ok(policy) = home.load_policy() {
        healthy &= agents::sandboxes(&mut shown, &home, &Plan::new(&home, &policy)?, &binary);
    }
    let audit = audit(&mut shown, &home)?;
    healthy &= audit.is_some();
    opt_in(&mut shown, &home);

    // Only when a policy asks for it, so nothing changes without the setting.
    mcp_servers(&mut shown, &home, &binary);
    if let Some(boundary) = protection::run_boundary(&home, &binary) {
        healthy &= boundary.met;
        let mark = if boundary.met { Mark::Ok } else { Mark::Broken };
        if boundary.met {
            shown.state(mark, "Run boundary", boundary.describe());
        } else {
            shown.needs(mark, "Run boundary", boundary.describe());
        }
    }

    let agents = protection::report(&home, &binary)?;
    // An agent below the level the policy requires has every call denied.
    healthy &= agents.iter().all(protection::Protection::meets_required);
    // Hook-only agents `openmoat run` can confine here (ADR-108): warnings.
    let shims = crate::start::Record::load(&home).unwrap_or_default();
    let shimmed = |id: &str| shims.shims.iter().any(|s| s.host == id);
    let mut confined_by_row = Vec::new();
    for row in crate::report::hook_only_rows(&agents, &shimmed) {
        confined_by_row.extend(
            agents
                .iter()
                .filter(|a| a.name == row.label)
                .map(|a| a.host),
        );
        shown.attention.push(row);
    }
    let table = crate::report::agent_table(&agents, &shown.attention, false);
    let mut out = io::stdout().lock();
    let mut printer = Printer::stdout(&mut out);
    printer.title("status")?;
    printer.attention(&shown.attention)?;
    let mut table = table;
    table.rows.extend(crate::report::os_sandbox_rows_but(
        &agents,
        &confined_by_row,
    ));
    table.rows.append(&mut shown.agents);
    printer.agents(&table)?;
    printer.heading("OpenMoat")?;
    printer.rows(&shown.openmoat)?;
    if let Some(recent) = audit.filter(|r| !r.is_empty()) {
        printer.heading("Latest decisions")?;
        drop(printer);
        render::event_table(&recent)?;
    }
    Ok(if healthy { Code::Ok } else { Code::Usage })
}

/// What `status --format json` prints, which `openmoat serve` sends too.
pub(super) fn json() -> Result<serde_json::Value> {
    let home = Home::locate()?;
    let binary = crate::install::hook_binary()?;
    let update = crate::upgrade::available(&home);
    report(&home, &binary, update.as_ref())
}

/// The status document: each agent's protection level, the plugins, the
/// warnings, and what waits for a person. Reads files only.
fn report(home: &Home, binary: &Path, update: Option<&String>) -> Result<serde_json::Value> {
    let drift: Vec<String> = Lock::load(&home.lock_path())
        .map(|lock| lock.verify().iter().map(ToString::to_string).collect())
        .unwrap_or_default();
    let (plugins, hooks): (Vec<_>, Vec<_>) = crate::heartbeat::all(home, binary)
        .into_iter()
        .partition(|one| crate::heartbeat::has_plugin(one.of));
    Ok(serde_json::json!({
        "agents": protection::report(home, binary)?,
        "run_boundary": protection::run_boundary(home, binary),
        "mcp_servers": crate::mcp::status::report(
            home,
            binary,
            std::env::current_dir().ok().as_deref(),
        )
        .map(|found| found.servers)
        .unwrap_or_default(),
        "plugins": plugins,
        "hooks": hooks,
        "hook_warnings": hook_warnings(home, binary)?,
        "policy_update": update,
        "lock_drift": drift,
        "mcp_changes": mcp_changes(home, binary).unwrap_or_default(),
        "mcp_outside": mcp_outside(home, binary),
        "foreign_hooks": foreign_hooks::json(home, binary),
        "project_settings": crate::project_settings::warnings_here(home)
            .into_iter()
            .map(|warning| warning.text)
            .collect::<Vec<_>>(),
        "other_hooks": crate::project_settings::other_hooks::warnings_here(home)
            .into_iter()
            .map(|warning| warning.text)
            .collect::<Vec<_>>(),
        "repo_git_config": crate::project_settings::git_config::warnings_here(),
        "opt_in": crate::opt_in::rows(home, time::now_ms()),
        "own_sandbox_linux": agents::own_sandbox_linux(home, binary),
    }))
}

/// The opt-in choices of `openmoat init` (ADR-106): a decoy touched is an
/// alert first in the list, an agent that starts outside its shim a warning;
/// neither changes the exit code, which says whether OpenMoat is set up.
fn opt_in(shown: &mut Shown, home: &Home) {
    for row in crate::opt_in::rows(home, time::now_ms()) {
        match (row.alert, row.attention) {
            (true, _) => shown.needs(Mark::Broken, row.label, row.text),
            (false, true) => shown.needs(Mark::Attention, row.label, row.text),
            (false, false) => shown.state(Mark::Ok, row.label, row.text),
        }
    }
}

/// Advisory trust diagnostics, separate from protection levels and exit codes.
fn hook_warnings(home: &Home, binary: &Path) -> Result<Vec<String>> {
    let mut warnings = Vec::new();
    for host in Host::ALL {
        let config = crate::install::HostConfig::for_host(home, host)?;
        if config.set_up(binary)
            && let Some(warning) = config.trust_warning()
        {
            warnings.push(format!("{}: {warning}", host.display_name()));
        }
    }
    Ok(warnings)
}

/// One line per MCP server definition or held tool that waits for `moat mcp
/// accept` (ADR-026); empty when there is no lock, or nothing waits.
fn mcp_changes(home: &Home, binary: &Path) -> Result<Vec<String>> {
    let path = home.lock_path();
    if !path.is_file() {
        return Ok(Vec::new());
    }
    let lock = Lock::load(&path)?;
    let cwd = std::env::current_dir().ok();
    let found = crate::mcp::review(
        home,
        &lock,
        &crate::mcp::set_up_hosts(home, binary),
        cwd.as_deref(),
    )?;
    let mut lines = Vec::new();
    if found.pinned {
        lines.extend(
            found
                .changes
                .iter()
                .map(|c| c.describe().lines().next().unwrap_or_default().to_owned()),
        );
    }
    lines.extend(
        found
            .unreadable
            .iter()
            .map(|(p, why)| format!("{} cannot be read: {why}", p.display())),
    );
    for (_, pins) in crate::mcp::tools::all(home)? {
        if pins.held_count() > 0 {
            lines.push(format!(
                "MCP server `{}` lists {}",
                pins.server,
                pins.held_summary()
            ));
        }
    }
    Ok(lines)
}

/// One line per MCP server that starts outside what OpenMoat checks
/// (`mcp/outside.rs`), or why they cannot be listed.
fn mcp_outside(home: &Home, binary: &Path) -> Vec<String> {
    let cwd = std::env::current_dir().ok();
    match crate::mcp::outside::report(home, binary, cwd.as_deref()) {
        Ok(found) => found
            .iter()
            .map(crate::mcp::outside::Outside::describe)
            .collect(),
        Err(e) => vec![format!(
            "cannot list the servers that start outside OpenMoat: {e:#}"
        )],
    }
}

/// One row per MCP server OpenMoat can read, protected or not and why
/// (ADR-077); `require.run` counts the failures, in its own row.
fn mcp_servers(shown: &mut Shown, home: &Home, binary: &Path) {
    let cwd = std::env::current_dir().ok();
    match crate::mcp::status::report(home, binary, cwd.as_deref()) {
        Ok(found) => {
            for server in &found.servers {
                let mark = if server.protected {
                    Mark::Ok
                } else {
                    Mark::Attention
                };
                shown.state(mark, "MCP server", server.describe());
            }
        }
        Err(error) => shown.needs(
            Mark::Attention,
            "MCP servers",
            format!("cannot list them: {error:#}"),
        ),
    }
}

/// The MCP line; `false` when something waits for `moat mcp accept`.
fn mcp_line(shown: &mut Shown, home: &Home, binary: &Path) -> bool {
    match mcp_changes(home, binary) {
        Ok(lines) if lines.is_empty() => {
            let text = "nothing waits for `openmoat mcp accept`";
            shown.state(Mark::Ok, "MCP servers", text);
            true
        }
        Ok(lines) => {
            for line in lines {
                let row = Row::new(Mark::Broken, "MCP servers", line)
                    .fix("`openmoat mcp accept` shows it and asks");
                shown.attention.push(row);
            }
            false
        }
        Err(error) => {
            shown.needs(Mark::Broken, "MCP servers", format!("{error:#}"));
            false
        }
    }
}

/// The policy line and, in a project with one, the repository policy line;
/// `false` on any problem.
fn policies(shown: &mut Shown, home: &Home) -> Result<bool> {
    let mut healthy = true;
    let policy_path = home.policy_path();
    match home.load_policy() {
        Ok(policy) => {
            let bytes = fs::read(&policy_path)?;
            let digest = crate::integrity::sha256_hex(&bytes);
            let (deny, allow, review) = policy.rule_count();
            let text = format!(
                "{} · {deny} deny · {allow} allow · {review} review rules · sha256:{}",
                policy_path.display(),
                digest.get(..12).unwrap_or(&digest)
            );
            shown.state(Mark::Ok, "Policy", text);
        }
        Err(error) => {
            healthy = false;
            shown.needs(Mark::Broken, "Policy", format!("{error:#}"));
        }
    }
    match crate::repo::summary(home) {
        Ok(Some(line)) => shown.state(Mark::Info, "Repo policy", line),
        Ok(None) => {}
        Err(error) => {
            healthy = false;
            let text = format!("{error:#}; every call in this project is denied");
            shown.needs(Mark::Broken, "Repo policy", text);
        }
    }
    Ok(healthy)
}

/// The lock lines: drift, and hook files the lock does not pin; `false` on any
/// problem.
fn lock(shown: &mut Shown, home: &Home, binary: &Path) -> Result<bool> {
    let lock_path = home.lock_path();
    let lock = match Lock::load(&lock_path) {
        Ok(lock) => lock,
        Err(_) if !lock_path.exists() => {
            let row = Row::new(Mark::Broken, "Lock", "missing").fix("openmoat init");
            shown.attention.push(row);
            return Ok(false);
        }
        Err(error) => {
            shown.needs(Mark::Broken, "Lock", format!("{error:#}"));
            return Ok(false);
        }
    };
    let mut healthy = true;
    let drift = lock.verify();
    if drift.is_empty() {
        let text = format!("{} files pinned, intact", lock.entries.len());
        shown.state(Mark::Ok, "Lock", text);
    } else {
        healthy = false;
        for d in drift {
            let row = Row::new(Mark::Broken, "Lock", d.to_string()).fix("openmoat doctor");
            shown.attention.push(row);
        }
    }
    // The guard's own file against the lock's record (ADR-071).
    let own = crate::integrity::binary::check(home, &lock);
    if let Some(reason) = own.deny_reason() {
        healthy = false;
        let row = Row::new(Mark::Broken, "Binary", reason).fix("openmoat init");
        shown.attention.push(row);
    } else if let Some(note) = own.note() {
        shown.state(Mark::Info, "Binary", note);
    }
    let installed = crate::integrity::installed_hook_files(home, binary)?;
    let gap = HookPinGap::new(&lock, home, &installed);
    for path in gap.unpinned {
        healthy = false;
        let row = Row::new(
            Mark::Broken,
            "Lock",
            format!("{} is not pinned", path.display()),
        )
        .fix("openmoat init to pin it");
        shown.attention.push(row);
    }
    for path in gap.elsewhere {
        let text = format!(
            "{} is pinned but not this shell's hook file ({})",
            path.display(),
            HookPinGap::moved_by()
        );
        shown.state(Mark::Info, "Lock", text);
    }
    Ok(healthy)
}

/// The session grants line; `false` when the grants file is unreadable.
fn approvals(shown: &mut Shown, home: &Home) -> bool {
    let grants = match Grants::load(&home.grants_path()) {
        Ok(grants) => grants,
        Err(error) => {
            shown.needs(Mark::Broken, "Approvals", format!("{error:#}"));
            return false;
        }
    };
    let now = time::now_ms();
    let ages: Vec<i64> = grants.active(now).map(|g| now - g.granted_at_ms).collect();
    let text = match ages.iter().max() {
        Some(oldest) => format!(
            "{} active session grant(s), oldest {} old (each expires after {})",
            ages.len(),
            time::duration(*oldest),
            time::duration(GRANT_TTL_MS)
        ),
        None => "no active session grants".to_owned(),
    };
    shown.state(Mark::Info, "Approvals", text);
    // Standing grants `--for` gave an end: those that ended or end soon.
    let overlay = approvals::Overlay::load(&home.overlay_path());
    if let Some(text) = overlay
        .ok()
        .and_then(|o| approvals::expiry_summary(&o, now))
    {
        shown.state(Mark::Info, "Approvals", text);
    }
    // Written before grants named their project: they apply nowhere now.
    for grant in grants.active(now).filter(|g| g.unbound()) {
        let text = format!(
            "{} session {}: {} needs approving again: it names no project, so it no longer \
             applies (`openmoat allow --last` after its next review)",
            grant.host,
            grant.session_id,
            approvals::describe(&grant.action)
        );
        shown.needs(Mark::Attention, "Approvals", text);
    }
    true
}

/// The audit log line; the most recent events, `None` when the log is missing.
fn audit(shown: &mut Shown, home: &Home) -> Result<Option<Vec<openmoat_audit::Event>>> {
    let audit_path = home.audit_path();
    if !audit_path.is_file() {
        let row = Row::new(Mark::Broken, "Audit log", "missing").fix("openmoat init");
        shown.attention.push(row);
        return Ok(None);
    }
    let store = Store::open_read_only(&audit_path)?;
    let text = format!("{} · {} events", audit_path.display(), store.count()?);
    shown.state(Mark::Ok, "Audit log", text);
    Ok(Some(store.recent(RECENT_EVENTS)?))
}