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
//! The calls the guard denied because no decision came within its budget.
//!
//! The audit log cannot hold them: what hangs may be the audit log itself. The
//! guard's watchdog appends one line, `<ms since the epoch> <host> <phase>
//! <elapsed ms>`, to a side file in the state directory instead, from a thread
//! it waits for only briefly, and ignores any failure: the deny never depends
//! on the record. The phase is the step the guard was in when the budget ran
//! out, and the elapsed time is measured from the guard's start, so a line
//! tells a slow step (machine load) from a stuck one. Builds before the phase
//! wrote `<ms> <host>` only; those lines still count.

use std::collections::HashMap;
use std::fs;
use std::io::{self, Write as _};
use std::path::Path;
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::mpsc;
use std::thread;
use std::time::Duration;

use openmoat_hosts::Host;

use crate::home::{self, Home};

mod times;

pub use times::spent;

/// The side file stops growing at this size, so a stream of hangs cannot fill
/// the disk; 64 KiB holds a few thousand lines.
const MAX_BYTES: u64 = 64 * 1024;

/// How long the watchdog waits for its line before it exits anyway. The host
/// sees the deny's exit code only when the guard exits, so the budget plus this
/// wait stays below every host's hook timeout (the test below). 200 ms lost
/// lines on Windows runners when several guards gave up at once.
const WRITE_WAIT: Duration = Duration::from_secs(2);

/// The step `moat guard` is in, in the order it takes them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Phase {
    /// Reading the hook payload.
    Stdin,
    /// Inside `moat run`: waiting for the run's process outside the sandbox
    /// to decide (its own guard records the phase it reached).
    Relay,
    /// Parsing the payload into a call and finding the state directory.
    Parse,
    /// Checking the policy lock.
    Lock,
    /// Placing the call (its paths and agent) and checking its MCP server.
    Placed,
    /// Loading the call's context (project, home, search path) and the decoy keys.
    Context,
    /// Loading the person's policy with the project's.
    Policy,
    /// Reading the secret values to mask and the required protection level.
    Secrets,
    /// Loading `moat init`'s snapshot of the search path and its programs.
    Snapshot,
    /// Compiling the policy.
    Compile,
    /// Deciding the call: resolving its paths and programs on disk.
    Decide,
    /// Opening the audit log.
    Audit,
    /// Reading the session's earlier calls from the audit log.
    Taint,
    /// Waiting for an approver's answer from another device (ADR-093).
    Approval,
    /// Writing the session cache.
    Cache,
    /// Recording the decision in the audit log.
    Record,
    /// Writing the answer to the host.
    Answer,
}

const PHASES: [Phase; 17] = [
    Phase::Stdin,
    Phase::Relay,
    Phase::Parse,
    Phase::Lock,
    Phase::Placed,
    Phase::Context,
    Phase::Policy,
    Phase::Secrets,
    Phase::Snapshot,
    Phase::Compile,
    Phase::Decide,
    Phase::Audit,
    Phase::Taint,
    Phase::Approval,
    Phase::Cache,
    Phase::Record,
    Phase::Answer,
];

impl Phase {
    /// The name in a hangs line.
    pub fn name(self) -> &'static str {
        match self {
            Self::Stdin => "stdin",
            Self::Relay => "relay",
            Self::Parse => "parse",
            Self::Lock => "lock",
            Self::Placed => "placed",
            Self::Context => "context",
            Self::Policy => "policy",
            Self::Secrets => "secrets",
            Self::Snapshot => "snapshot",
            Self::Compile => "compile",
            Self::Decide => "decide",
            Self::Audit => "audit",
            Self::Taint => "taint",
            Self::Approval => "approval",
            Self::Cache => "cache",
            Self::Record => "record",
            Self::Answer => "answer",
        }
    }

    /// What the guard was doing, for `moat doctor`.
    pub fn doing(self) -> &'static str {
        match self {
            Self::Stdin => "reading the tool call",
            Self::Relay => "waiting for `openmoat run` to decide",
            Self::Parse => "parsing the tool call",
            Self::Lock => "checking the policy lock",
            Self::Placed => "placing the call and checking its MCP server",
            Self::Context => "loading the call's context",
            Self::Policy => "loading the policy",
            Self::Secrets => "reading the secrets to mask",
            Self::Snapshot => "loading the search path snapshot",
            Self::Compile => "compiling the policy",
            Self::Decide => "deciding",
            Self::Audit => "opening the audit log",
            Self::Taint => "reading the session's earlier calls",
            Self::Approval => "waiting for an approver's answer",
            Self::Cache => "writing the session cache",
            Self::Record => "writing the audit log",
            Self::Answer => "answering the host",
        }
    }

    /// Where the guard takes this phase among the others: 0 for the first.
    pub fn order(self) -> usize {
        PHASES
            .iter()
            .position(|p| *p == self)
            .unwrap_or(PHASES.len())
    }

    /// The phase named `name` in a hangs line.
    pub fn from_name(name: &str) -> Option<Self> {
        PHASES.into_iter().find(|p| p.name() == name)
    }
}

/// The guard's current phase, as an index into [`PHASES`]; one guard per process.
static CURRENT: AtomicU8 = AtomicU8::new(0);

/// The guard moves on to `phase`; the time since the last phase began goes
/// to that phase ([`spent`]).
pub fn enter(phase: Phase) {
    let index = PHASES.iter().position(|p| *p == phase).unwrap_or(0);
    CURRENT.store(u8::try_from(index).unwrap_or(0), Ordering::Relaxed);
    times::entered(phase);
    stall_at(phase);
}

/// Debug builds stop for good on entering the phase this variable names
/// (`lock`, `record`, …), so the end-to-end tests can show the deadline's deny
/// arrives whatever step is stuck (ADR-120). Release builds do not read it.
#[cfg(debug_assertions)]
const STALL_ENV: &str = "MOAT_TEST_STALL_AT";

#[cfg(debug_assertions)]
fn stall_at(phase: Phase) {
    if std::env::var(STALL_ENV).is_ok_and(|v| v == phase.name()) {
        // Only the deadline's exit ends the process now.
        loop {
            thread::sleep(Duration::from_secs(1));
        }
    }
}

#[cfg(not(debug_assertions))]
fn stall_at(_: Phase) {}

/// The phase the guard is in now.
pub fn current() -> Phase {
    PHASES
        .get(usize::from(CURRENT.load(Ordering::Relaxed)))
        .copied()
        .unwrap_or(Phase::Stdin)
}

/// Record that `host`'s call was denied at `now_ms` with no decision, while in
/// `phase` after `elapsed_ms`, then run `then` (the audit row, ADR-120) on the
/// same thread, waiting at most [`WRITE_WAIT`] for both: the line comes first,
/// so a stuck audit log cannot keep it from being written.
pub fn record(
    home: &Home,
    host: Host,
    (now_ms, phase, elapsed_ms): (i64, Phase, u128),
    then: impl FnOnce() + Send + 'static,
) {
    let (done, written) = mpsc::channel();
    let path = home.hangs_path();
    let line = line(now_ms, host, phase, elapsed_ms);
    let writer = thread::Builder::new().spawn(move || {
        let _ = append(&path, &line);
        then();
        let _ = done.send(());
    });
    if writer.is_ok() {
        let _ = written.recv_timeout(WRITE_WAIT);
    }
}

fn line(now_ms: i64, host: Host, phase: Phase, elapsed_ms: u128) -> String {
    format!("{now_ms} {} {} {elapsed_ms}\n", host.id(), phase.name())
}

/// Append `line` to `path` unless it is something other than a regular file
/// (a symlink, or a FIFO that would block) or already full. The state
/// directory is not created: without it there is no installation to report on.
fn append(path: &Path, line: &str) -> io::Result<()> {
    if let Ok(meta) = fs::symlink_metadata(path)
        && (!meta.is_file() || meta.len() >= MAX_BYTES)
    {
        return Err(io::ErrorKind::InvalidInput.into());
    }
    home::private_append_options()
        .open(path)?
        .write_all(line.as_bytes())
}

/// The hangs of a time window.
#[derive(Debug, PartialEq, Eq)]
pub struct Hangs {
    /// How many.
    pub count: usize,
    /// When the newest was.
    pub newest_ms: i64,
    /// The phase most of them were in; `None` when no line names one.
    pub common_phase: Option<Phase>,
}

/// The hangs `path` records at or after `since_ms`; `None` when there are none
/// or the file cannot be read.
pub fn since(path: &Path, since_ms: i64) -> Option<Hangs> {
    if !fs::symlink_metadata(path).ok()?.is_file() {
        return None;
    }
    let text = fs::read_to_string(path).ok()?;
    let lines: Vec<(i64, Option<Phase>)> = text
        .lines()
        .filter_map(parse)
        .filter(|(ms, _)| *ms >= since_ms)
        .collect();
    let newest_ms = lines.iter().map(|(ms, _)| *ms).max()?;
    let mut counts: HashMap<Phase, usize> = HashMap::new();
    for phase in lines.iter().filter_map(|(_, p)| *p) {
        *counts.entry(phase).or_default() += 1;
    }
    // Ties go to the earliest phase, so the answer does not depend on hashing.
    let common_phase = PHASES
        .into_iter()
        .filter_map(|p| Some((p, *counts.get(&p)?)))
        .fold(None::<(Phase, usize)>, |best, (p, n)| match best {
            Some((_, m)) if m >= n => best,
            _ => Some((p, n)),
        })
        .map(|(p, _)| p);
    Some(Hangs {
        count: lines.len(),
        newest_ms,
        common_phase,
    })
}

/// How many hangs each agent had from `since_ms` up to, not including,
/// `until_ms`, in the order commands list agents; empty when there are none
/// or the file cannot be read. A line naming no agent this build knows is
/// left out.
pub fn per_host(path: &Path, since_ms: i64, until_ms: i64) -> Vec<(Host, u64)> {
    let Some(text) = fs::symlink_metadata(path)
        .ok()
        .filter(fs::Metadata::is_file)
        .and_then(|_| fs::read_to_string(path).ok())
    else {
        return Vec::new();
    };
    let mut counts: HashMap<Host, u64> = HashMap::new();
    for line in text.lines() {
        let mut fields = line.split(' ');
        let Some(ms) = fields.next().and_then(|ms| ms.parse::<i64>().ok()) else {
            continue;
        };
        let Some(host) = fields.next().and_then(|id| id.parse::<Host>().ok()) else {
            continue;
        };
        if (since_ms..until_ms).contains(&ms) {
            *counts.entry(host).or_default() += 1;
        }
    }
    Host::EVERY
        .into_iter()
        .filter_map(|h| Some((h, *counts.get(&h)?)))
        .collect()
}

/// The time and phase of one line; a line without a phase (an older build's)
/// or with one this build does not know has none.
fn parse(line: &str) -> Option<(i64, Option<Phase>)> {
    let mut fields = line.split(' ');
    let ms = fields.next()?.parse().ok()?;
    let phase = fields.nth(1).and_then(Phase::from_name);
    Some((ms, phase))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_deadline_and_the_write_wait_end_before_any_host_times_out() {
        // The margin the deadline keeps covers this wait, with room to spare.
        assert!(WRITE_WAIT < Duration::from_secs(openmoat_hosts::DEADLINE_MARGIN_S));
        for host in Host::EVERY {
            let spec = host.spec();
            let gone = Duration::from_secs(spec.guard_deadline_s()) + WRITE_WAIT;
            let limits = spec
                .hook_failure
                .timeout_s
                .map(u64::from)
                .into_iter()
                .chain(
                    spec.install
                        .iter()
                        .flat_map(|i| i.hooks.iter().map(|h| h.timeout)),
                );
            for limit in limits {
                assert!(
                    Duration::from_secs(limit) > gone,
                    "{host:?}: {limit} s leaves no margin after {gone:?}"
                );
            }
        }
    }

    #[test]
    fn concurrent_writers_lose_no_line() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("guard-hangs.log");
        let writers: Vec<_> = (0..16)
            .map(|i| {
                let path = path.clone();
                thread::spawn(move || append(&path, &format!("{i} codex stdin 30000\n")).unwrap())
            })
            .collect();
        for writer in writers {
            writer.join().unwrap();
        }
        let text = fs::read_to_string(&path).unwrap();
        assert_eq!(text.lines().count(), 16, "{text}");
        assert!(text.lines().all(|l| l.split(' ').count() == 4), "{text}");
    }

    #[test]
    fn lines_are_counted_from_a_time_on() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("guard-hangs.log");
        assert_eq!(since(&path, 0), None);
        for line in ["100 codex\n", "not a line\n", "300 claude-code\n"] {
            append(&path, line).unwrap();
        }
        let all = since(&path, 0).unwrap();
        assert_eq!((all.count, all.newest_ms, all.common_phase), (2, 300, None));
        assert_eq!(since(&path, 200).unwrap().count, 1);
        assert_eq!(since(&path, 301), None);
    }

    /// `openmoat audit stats` counts each agent's hangs inside its window,
    /// in the order agents are listed; an unknown agent or a bad line is left out.
    #[test]
    fn hangs_are_counted_per_agent_in_a_window() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("guard-hangs.log");
        assert_eq!(per_host(&path, 0, i64::MAX), Vec::new());
        let (a, b) = (Host::ALL[0], Host::ALL[1]);
        for line in [
            format!("100 {} record 30001\n", b.id()),
            format!("200 {}\n", a.id()),
            format!("300 {} lock 30002\n", b.id()),
            "250 no-such-agent\n".to_owned(),
            "garbage\n".to_owned(),
        ] {
            append(&path, &line).unwrap();
        }
        assert_eq!(per_host(&path, 0, i64::MAX), [(a, 1), (b, 2)]);
        assert_eq!(
            per_host(&path, 150, 300),
            [(a, 1)],
            "the end is not included"
        );
        assert_eq!(per_host(dir.path(), 0, i64::MAX), Vec::new());
    }

    #[test]
    fn a_full_file_or_a_directory_is_left_alone() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("guard-hangs.log");
        fs::write(&path, vec![b'\n'; usize::try_from(MAX_BYTES).unwrap()]).unwrap();
        assert!(append(&path, "1 codex\n").is_err());
        assert_eq!(fs::metadata(&path).unwrap().len(), MAX_BYTES);
        assert!(append(dir.path(), "1 codex\n").is_err());
        assert_eq!(since(dir.path(), 0), None);
    }

    #[test]
    fn every_phase_has_a_distinct_name_that_reads_back() {
        let mut names: Vec<&str> = PHASES.iter().map(|p| p.name()).collect();
        for phase in PHASES {
            // The audit store keeps only such names (ADR-130).
            let name = phase.name();
            assert!(name.len() <= 16 && name.bytes().all(|b| b.is_ascii_lowercase()));
            assert_eq!(Phase::from_name(name), Some(phase));
            enter(phase);
            assert_eq!(current(), phase);
        }
        names.sort_unstable();
        names.dedup();
        assert_eq!(names.len(), PHASES.len());
        assert_eq!(Phase::from_name("nap"), None);
    }

    #[test]
    fn a_line_names_the_time_host_phase_and_elapsed_ms() {
        let host = Host::EVERY[0];
        let line = line(1_700, host, Phase::Record, 30_012);
        assert_eq!(line, format!("1700 {} record 30012\n", host.id()));
        assert_eq!(parse(line.trim_end()), Some((1_700, Some(Phase::Record))));
        assert_eq!(parse("1700 codex"), Some((1_700, None)), "an older line");
        assert_eq!(parse("1700 codex later 5"), Some((1_700, None)));
    }

    #[test]
    fn the_most_common_phase_is_reported_and_older_lines_still_count() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("guard-hangs.log");
        let text = "10 codex\n20 codex taint 30001\n30 cursor record 30002\n\
                    40 claude-code record 30500\n";
        fs::write(&path, text).unwrap();
        let hangs = since(&path, 0).unwrap();
        assert_eq!(hangs.count, 4);
        assert_eq!(hangs.newest_ms, 40);
        assert_eq!(hangs.common_phase, Some(Phase::Record));
        fs::write(&path, "20 codex taint 1\n30 codex record 1\n").unwrap();
        assert_eq!(since(&path, 0).unwrap().common_phase, Some(Phase::Taint));
    }
}