openmoat 0.28.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
//! `moat bench`: the `MoatBench` scenarios (`docs/MOATBENCH.md`) sent as each
//! host's own hook payloads to OpenMoat, or to any hook command (`--hook`), in a
//! throwaway home. Scenario commands are never executed; only the hook runs.
//!
//! Against OpenMoat the kernel verdict of each step is read back from the
//! throwaway audit log and checked against the scenario, and the host's reading
//! of the reply must carry that verdict. Against another hook, the reply is
//! classified by the host's hook protocol and compared with the scenario.

mod hook;
mod hosts;
mod proof;
pub(crate) mod scenario;
mod score;
#[cfg(test)]
mod tests;

use std::ffi::OsString;
use std::io::{self, Write as _};

use anyhow::{Context as _, Result, ensure};
use openmoat_audit::Store;
use openmoat_core::Verdict;
use openmoat_hosts::Host;
use serde::Serialize;

use crate::cli::{BenchArgs, BenchFormat};
use crate::exit::Code;
use crate::home::Home;
use crate::render;
use hook::Scratch;
use hosts::{Answer, Place};
use scenario::{Call, Scenario, Step, scenarios};
use score::{Outcome, Run, Scorecard, StepResult};

/// What the scenarios run against.
enum Target {
    /// This `moat`, installed in the throwaway home; verdicts read from its audit log.
    OpenMoat { exe: OsString, audit: Store },
    /// A hook command line, run through the system shell.
    Hook(String),
}

impl Target {
    fn command(&self, scratch: &Scratch, host: Host) -> std::process::Command {
        match self {
            Self::OpenMoat { exe, .. } => {
                let args = ["guard", "--host", host.id()].map(OsString::from);
                scratch.command(exe, &args)
            }
            Self::Hook(line) => {
                let (shell, args) = hook::shell(line);
                scratch.command(shell, &args)
            }
        }
    }
}

#[derive(Serialize)]
struct Report<'a> {
    target: &'a str,
    hosts: Vec<&'static str>,
    #[serde(flatten)]
    scorecard: &'a Scorecard,
    /// Host behaviour when the hook fails, from the documentation; not measured.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    hook_failure: Vec<HostFailure>,
    /// Against OpenMoat: the disturbance figures (`openmoat audit stats`) of
    /// the benign and workflow steps, read back from the throwaway audit log.
    #[serde(skip_serializing_if = "Option::is_none")]
    ordinary_work: Option<crate::disturbance::Disturbance>,
}

#[derive(Serialize)]
struct HostFailure {
    host: &'static str,
    behaviour: &'static str,
}

pub fn run(args: &BenchArgs) -> Result<Code> {
    ensure!(
        args.format != BenchFormat::Markdown || args.report,
        "--format markdown needs --report"
    );
    let mut scenarios = scenarios()?;
    if args.report {
        // The proof report needs only the scenarios its promises name.
        scenarios.retain(|(_, s)| proof::scenario_ids().any(|id| id == s.id));
    }
    let scratch = Scratch::new(args.scratch_dir.as_deref())?;
    let hosts: Vec<Host> = args.host.map_or_else(|| Host::ALL.to_vec(), |h| vec![h]);
    let target = match &args.hook {
        Some(line) => Target::Hook(line.clone()),
        None => install(&scratch)?,
    };
    if args.verbose {
        describe(&target, &scratch)?;
    }
    let markers = matches!(target, Target::OpenMoat { .. });
    let mut card = Scorecard::default();
    let mut checked = Vec::new();
    let mut ordinary = Vec::new();
    for (category, scenario) in &scenarios {
        if let Some(issue) = scenario.gap.as_ref().filter(|_| markers) {
            card.note_gap(&scenario.id, issue);
        }
        for &host in &hosts {
            if let Some(result) = run_scenario(&target, &scratch, scenario, host, args.verbose)? {
                checked.push(proof::Checked {
                    scenario: scenario.id.clone(),
                    host,
                    policy: result.policy.clone(),
                    hook: result.hook.clone(),
                });
                if score::ordinary(category) {
                    ordinary.push(format!("{}@{}", scenario.id, host.id()));
                }
                card.add(category, &scenario.id, host.id(), result);
            }
        }
    }
    if args.report {
        return proof::report(&target, &scratch, &hosts, &checked, args.format);
    }
    if markers {
        card.check_gaps();
    }
    let hook_failure = match &target {
        Target::OpenMoat { .. } => Vec::new(),
        Target::Hook(_) => hosts
            .iter()
            .map(|&host| HostFailure {
                host: host.id(),
                behaviour: hosts::failure(host),
            })
            .collect(),
    };
    let ordinary_work = match &target {
        Target::OpenMoat { audit, .. } => Some(ordinary_work(audit, &ordinary)?),
        Target::Hook(_) => None,
    };
    let report = Report {
        target: args.hook.as_deref().unwrap_or("openmoat"),
        hosts: hosts.iter().map(|h| h.id()).collect(),
        scorecard: &card,
        hook_failure,
        ordinary_work,
    };
    match args.format {
        BenchFormat::Json => render::json(&report)?,
        BenchFormat::Text | BenchFormat::Markdown => print_text(&report)?,
    }
    Ok(Code::Ok)
}

/// `moat init --yes` of this binary in the throwaway home.
fn install(scratch: &Scratch) -> Result<Target> {
    let exe = std::env::current_exe().context("locating the moat binary")?;
    let out = scratch
        .command(&exe, &["init".into(), "--yes".into()])
        .output()
        .context("running openmoat init in the throwaway home")?;
    ensure!(
        out.status.success(),
        "openmoat init in the throwaway home failed: {}",
        String::from_utf8_lossy(&out.stderr).trim()
    );
    let path = Home::under(&scratch.home).audit_path();
    let audit =
        Store::open_read_only(&path).with_context(|| format!("opening {}", path.display()))?;
    Ok(Target::OpenMoat {
        exe: exe.into_os_string(),
        audit,
    })
}

/// The disturbance figures of the `sessions` of ordinary work, from the
/// throwaway audit log: the same figures `openmoat audit stats` gives.
fn ordinary_work(audit: &Store, sessions: &[String]) -> Result<crate::disturbance::Disturbance> {
    let mut events = Vec::new();
    for session in sessions {
        events.extend(audit.session(session)?);
    }
    events.sort_by_key(|e| e.id.0);
    Ok(crate::disturbance::of(&events, &[]))
}

/// `--verbose`: what every hook run gets besides its payload.
fn describe(target: &Target, scratch: &Scratch) -> Result<()> {
    let mut err = io::stderr().lock();
    let hook = match target {
        Target::OpenMoat { exe, .. } => format!("{} guard --host <host>", exe.to_string_lossy()),
        Target::Hook(line) => line.clone(),
    };
    writeln!(err, "hook: {hook}")?;
    writeln!(err, "working directory: {}", scratch.project.display())?;
    writeln!(err, "environment (nothing else is passed):")?;
    for (name, value) in scratch.environment() {
        writeln!(err, "  {name}={}", value.to_string_lossy())?;
    }
    writeln!(err, "time limit: {} s per call", hook::TIMEOUT.as_secs())?;
    Ok(())
}

/// Run `scenario` on `host`; `None` when the host has no tool for one of its steps.
fn run_scenario(
    target: &Target,
    scratch: &Scratch,
    scenario: &Scenario,
    host: Host,
    verbose: bool,
) -> Result<Option<Run>> {
    let session = format!("{}@{}", scenario.id, host.id());
    let calls = scenario
        .steps
        .iter()
        .map(Step::call)
        .collect::<Result<Vec<_>>>()?;
    let payloads = calls.iter().enumerate().map(|(i, call)| {
        let call_id = format!("{session}#{i}");
        let at = Place {
            home: &scratch.home,
            project: &scratch.project,
            session: &session,
            call_id: &call_id,
        };
        hosts::payload(host, call, &at)
    });
    let Some(payloads) = payloads.collect::<Option<Vec<_>>>() else {
        return Ok(None);
    };
    let mut answers = Vec::new();
    let mut causes = Vec::new();
    for (i, (call, payload)) in calls.iter().zip(&payloads).enumerate() {
        let reply = hook::send(&mut target.command(scratch, host), payload);
        if verbose {
            eprintln!("> {session}#{i}\n{payload}\n< {}", reply.describe());
        }
        let answer = hosts::classify(host, call, &reply);
        causes.push((answer == Answer::Error).then(|| reply.cause()));
        answers.push(answer);
    }
    let mut problems = Vec::new();
    let verdicts = match target {
        Target::OpenMoat { audit, .. } => recorded(
            audit,
            &session,
            &calls,
            (&answers, &causes),
            host,
            &mut problems,
        )?,
        Target::Hook(_) => answers.iter().map(|&a| (a, None)).collect(),
    };
    Ok(Some(compare(
        scenario,
        host,
        &calls,
        &verdicts,
        &causes,
        problems,
        matches!(target, Target::OpenMoat { .. }),
    )))
}

/// The answer's word, with why the host reads it as an error when it does
/// (`cause`), so a mismatch says what the hook did.
fn read_as(answer: Answer, cause: Option<&String>) -> String {
    match cause {
        Some(cause) => format!("{} ({cause})", answer.word()),
        None => answer.word().to_owned(),
    }
}

/// OpenMoat's verdict and rules for each step, from the audit log; a reply the
/// host would read differently from that verdict is a problem.
fn recorded(
    audit: &Store,
    session: &str,
    calls: &[Call],
    (answers, causes): (&[Answer], &[Option<String>]),
    host: Host,
    problems: &mut Vec<String>,
) -> Result<Vec<(Answer, Option<Vec<String>>)>> {
    let events = audit.session(session)?;
    if events.len() != calls.len() {
        problems.push(format!(
            "{} audit events for {} steps",
            events.len(),
            calls.len()
        ));
        return Ok(answers.iter().map(|&a| (a, None)).collect());
    }
    for (i, ((event, call), answer)) in events.iter().zip(calls).zip(answers).enumerate() {
        let want = hosts::seen(host, call, event.verdict);
        if *answer != want {
            problems.push(format!(
                "step {i}: kernel said {}, host reads {}",
                event.verdict.as_str(),
                read_as(*answer, causes.get(i).and_then(Option::as_ref))
            ));
        }
    }
    Ok(events
        .into_iter()
        .map(|e| (e.verdict.into(), Some(e.rules)))
        .collect())
}

/// Compare each step's answer with its expectation. Gap markers name OpenMoat
/// issues, so they apply only to OpenMoat (`markers`).
fn compare(
    scenario: &Scenario,
    host: Host,
    calls: &[Call],
    verdicts: &[(Answer, Option<Vec<String>>)],
    causes: &[Option<String>],
    hook: Vec<String>,
    markers: bool,
) -> Run {
    // The host's reading of the reply came first (`recorded`); the kernel's
    // verdict against the scenario follows. The proof report keeps them apart.
    let mut problems = Vec::new();
    let mut known = Vec::new();
    // Gap markers on steps that pass: the bench's own bookkeeping, not the policy's.
    let mut stale = Vec::new();
    let mut steps = Vec::new();
    // `openmoat init --yes` in the throwaway home put the host's OS sandbox in
    // place wherever OpenMoat has one on this OS; another hook has none.
    let sandboxed = markers
        && crate::sandbox::install::format(host).is_some()
        && crate::sandbox::install::unavailable(host).is_none();
    for (i, ((step, call), (got, rules))) in
        scenario.steps.iter().zip(calls).zip(verdicts).enumerate()
    {
        // OpenMoat is checked on its kernel verdict; another hook on what the host does.
        let (expect, rule) = step.expected(sandboxed);
        let want = if markers {
            expect.into()
        } else {
            hosts::seen(host, call, expect)
        };
        let ok = got.meets(want);
        let gap = step.gap.as_ref().filter(|_| markers);
        let rules = rules.as_ref();
        let got_word = read_as(*got, causes.get(i).and_then(Option::as_ref));
        match (gap, ok) {
            (Some(issue), false) => known.push(format!(
                "step {i} {issue}: expected {}, got {got_word} {rules:?}",
                want.word(),
            )),
            (Some(issue), true) => stale.push(format!(
                "step {i}: marked as gap {issue} but passes; remove the marker"
            )),
            (None, false) => problems.push(format!(
                "step {i}: expected {}, got {got_word}",
                want.word(),
            )),
            (None, true) => {
                if let (Some(rule), Some(rules)) = (rule, rules)
                    && !rules.iter().any(|r| r == rule)
                {
                    problems.push(format!(
                        "step {i}: {} without rule {rule} ({rules:?})",
                        got.word()
                    ));
                }
            }
        }
        steps.push(StepResult {
            got: *got,
            expects_review: expect == Verdict::Review,
            ok,
            gap: gap.is_some(),
            sandbox: if sandboxed && step.sandboxed.is_some() && ok {
                score::Sandbox::Expected
            } else {
                score::Sandbox::NotExpected
            },
        });
    }
    // A known gap is a policy that does not hold, whatever its marker says.
    let policy: Vec<String> = problems.iter().chain(&known).cloned().collect();
    let problems: Vec<String> = hook.iter().cloned().chain(problems).chain(stale).collect();
    let outcome = match (
        scenario.gap.as_ref().filter(|_| markers),
        problems.is_empty(),
    ) {
        (_, true) if known.is_empty() => Outcome::Pass,
        (_, true) => Outcome::Gap(known),
        (Some(issue), false) => Outcome::Gap(vec![format!("{issue}: {}", problems.join("; "))]),
        (None, false) => Outcome::Fail(problems),
    };
    Run {
        steps,
        outcome,
        policy,
        hook,
    }
}

fn print_text(report: &Report<'_>) -> Result<()> {
    let mut out = io::stdout().lock();
    writeln!(
        out,
        "MoatBench mini: {} ({})",
        report.target,
        report.hosts.join(", ")
    )?;
    write!(out, "{}", report.scorecard)?;
    if let Some(work) = &report.ordinary_work {
        let f = &work.overall;
        let latency = f.latency.map_or_else(
            || "no decision times".to_owned(),
            |l| {
                format!(
                    "decision time p50 {} µs, p95 {} µs, p99 {} µs",
                    l.p50, l.p95, l.p99
                )
            },
        );
        writeln!(
            out,
            "ordinary work (benign and workflows): {} calls, {latency} on this machine; \
             {:.2} reviews and {:.2} denies per 100 calls (`openmoat audit stats` figures)",
            f.calls, f.per_100_calls.review, f.per_100_calls.deny
        )?;
    }
    if !report.hook_failure.is_empty() {
        writeln!(
            out,
            "hook failure (host behaviour from docs/THREAT_MODEL.md §5, not tested here):"
        )?;
        for failure in &report.hook_failure {
            writeln!(out, "  {}: {}", failure.host, failure.behaviour)?;
        }
    }
    Ok(())
}