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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
//! `moat guard --host <id>`: the hook entry point.
//!
//! Reads one hook payload from stdin, decides, records, and answers on stdout.
//! Every failure path produces a `deny` response and exit code 2: a kernel
//! that cannot evaluate must not let the action through.

use std::io::{self, Read as _, Write as _};
use std::time::{Duration, Instant};

use anyhow::{Context as _, Result, bail};
use openmoat_audit::KnownSecrets;
use openmoat_core::rule_id::{APPROVED_SESSION, HOOK_DEADLINE, KERNEL_ERROR, UNGOVERNED};
use openmoat_core::{CompiledPolicy, Decision, Verdict};
use openmoat_hosts::{HookEvent, HookRequest, Host};
use record::Recorded;
use relayed::relayed;

use crate::approvals::{self, Grants};
use crate::cli::GuardArgs;
use crate::context;
use crate::environment::{Snapshot, WithOwnBinary};
use crate::exit::Code;
use crate::guard_relay::{self, MAX_PAYLOAD_BYTES};
use crate::hangs::{self, Phase};
use crate::home::Home;
use crate::integrity::{self, Drift};
use crate::realpath::FsPathResolver;
use crate::{notice, push, render, secrets, session_code, taint, time};

mod capture;
mod config_change;
mod deadline;
mod drift;
mod entry;
mod loaded;
mod placed;
mod plugin;
mod post_tool_use;
mod record;
mod relayed;
mod required;
mod session_start;
mod shown;
mod unattended;
mod unseen;

/// How far into its host's deadline ([`deadline::of`]) the session's taint
/// may be folded, leaving time to record: a session too long to fold in time
/// is denied with a recorded reason, its progress kept, rather than by the
/// deadline's deny.
pub(crate) fn taint_budget(host: Host) -> Duration {
    deadline::of(host) * 2 / 3
}

/// The least time a call that got here late on a loaded machine still gets to
/// read on a few events from its session's cache row.
const MIN_TAINT_TIME: Duration = Duration::from_secs(1);

pub fn run(args: &GuardArgs) -> Code {
    let host = args.host;
    entry::set(args.event.clone());
    entry::set_package(args.plugin);
    // First, before anything that touches a file: whatever blocks below, the
    // host gets a deny before its own time limit (ADR-120). A heartbeat
    // decides no call.
    if !args.heartbeat
        && let Err(error) = deny_at_deadline(host, Instant::now(), args.home.is_some())
    {
        let error = anyhow::Error::new(error).context("starting the guard's deadline");
        return respond(host, &HookEvent::default(), &kernel_error(&error));
    }
    // The hook's command line names the state directory; the environment the
    // host gave the hook does not get to (ADR-071).
    if let Some(word) = &args.home
        && let Err(error) = crate::home::pin(word, std::env::var_os(crate::home::ENV).as_deref())
    {
        let error = error.context("the hook's state directory");
        if args.heartbeat {
            eprintln!("moat: {error:#}");
            return Code::Deny;
        }
        return respond(host, &HookEvent::default(), &kernel_error(&error));
    }
    // A package from the agent's own plugin channel (ADR-099), which starts
    // the budget's deny itself.
    if let Some(code) = plugin::answer(args) {
        return code;
    }
    if args.heartbeat {
        return loaded::report(host);
    }
    // A panic would exit 101, which Claude Code treats as a non-blocking hook
    // failure, i.e. the call would proceed. Turn it into an explicit deny.
    // The deny is in the format of the payload's event once it was read.
    let by_run = args.relayed;
    let mut event = HookEvent::default();
    let decided = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        decide_and_respond(host, by_run, &mut event)
    }));
    if let Ok(code) = decided {
        return code;
    }
    let decision = kernel_error(&anyhow::Error::msg("internal error while deciding"));
    respond(host, &event, &decision)
}

/// Debug builds panic where this variable names, so the end-to-end tests can
/// show that a panic on the guard path is a deny (invariant 4). Release builds
/// do not read it.
#[cfg(debug_assertions)]
const PANIC_ENV: &str = "MOAT_TEST_PANIC_AT";

/// Panic when [`PANIC_ENV`] names `point`: the test of invariant 4 needs a
/// real panic on the guard path.
#[cfg(debug_assertions)]
fn fault_point(point: &str) {
    assert!(
        std::env::var(PANIC_ENV).ok().is_none_or(|v| v != point),
        "{PANIC_ENV}={point}"
    );
}

#[cfg(not(debug_assertions))]
fn fault_point(_: &str) {}

/// A hook the host times out counts as failed, and most hosts then run the
/// call, so at its host's deadline ([`deadline::of`], below every time limit
/// the host was given) the guard denies on its own (ADR-120): in the form of
/// the payload's event once it was read ([`deadline::saw`]), else the default
/// event's; exit 2 denies whatever the event. The deny is recorded first in
/// the side file of [`hangs`], which names the phase the guard was in and how
/// long it had run, so a slow machine can be told from a stuck step; then,
/// where the audit log can still be written, as a row with rule
/// `hook-deadline`. Both are waited for a bounded time only: what is stuck may
/// be the log. `pin_named`: the hook command names a state directory, which
/// nothing is written to before it is pinned. Exiting while the main thread is
/// inside the audit store's `BEGIN IMMEDIATE` is deliberate (fail closed): the
/// OS drops the write lock, and the next open of the log drops the unfinished row.
fn deny_at_deadline(installed_for: Host, started: Instant, pin_named: bool) -> io::Result<()> {
    let after = deadline::of(installed_for);
    deadline::arm(after, move || {
        let phase = hangs::current();
        let (host, event) = deadline::seen(installed_for);
        let decision = deadline_deny(after, phase);
        if let Some(code) = answer_once(host, &Answer::To(&event), &decision) {
            if (!pin_named || crate::home::is_pinned())
                && let Ok(home) = Home::locate()
            {
                let elapsed_ms = started.elapsed().as_millis();
                let row = record::deadline_row(home.clone(), host, &decision);
                hangs::record(&home, host, (time::now_ms(), phase, elapsed_ms), row);
            }
            std::process::exit(code as i32);
        }
    })
}

/// The deny the deadline answers with: `kernel-error`, whose words and page
/// the block message uses, and `hook-deadline`, which says why.
fn deadline_deny(after: Duration, phase: Phase) -> Decision {
    let waited = if after.subsec_millis() == 0 {
        format!("{} s", after.as_secs())
    } else {
        format!("{} ms", after.as_millis())
    };
    let mut decision = kernel_error(&anyhow::Error::msg(format!(
        "no decision within {waited} (while {}), so it is denied before the agent's own time \
         limit could run it",
        phase.doing()
    )));
    decision.rules.push(HOOK_DEADLINE.to_owned());
    decision
}

/// The one answer the guard writes: the decision's or the deadline's deny,
/// whichever comes first.
static GATE: deadline::Gate = deadline::Gate::new();

/// [`answer_once`]; when the budget's deny came first, its exit code.
fn respond(host: Host, event: &HookEvent, decision: &Decision) -> Code {
    answer_once(host, &Answer::To(event), decision).unwrap_or(Code::Deny)
}

/// What a response answers: the call the payload described, or, when it could
/// not be read, only its event.
enum Answer<'a> {
    For(&'a HookRequest),
    To(&'a HookEvent),
}

/// Write `decision` for `answer` and return the exit code that goes with it, or
/// `None` when a response was already written.
fn answer_once(host: Host, answer: &Answer<'_>, decision: &Decision) -> Option<Code> {
    GATE.once(|| write_answer(host, answer, decision))
}

/// Write `decision` for `answer`, holding [`GATE`]; the exit code that goes with it.
fn write_answer(host: Host, answer: &Answer<'_>, decision: &Decision) -> Code {
    let response = match answer {
        Answer::For(request) => host.render_response_for(request, decision),
        Answer::To(event) => host.render_response(event, decision),
    };
    let mut stdout = io::stdout().lock();
    // An empty response is `defer` (ADR-025): no output at all, not even a newline.
    let written = if response.is_empty() {
        Ok(())
    } else {
        writeln!(stdout, "{response}")
    };
    if let Err(error) = written.and_then(|()| stdout.flush()) {
        // Without a response the host falls back to its own default, which
        // may be to proceed; exit 2 is the one signal every host honours.
        eprintln!("moat: could not write the hook response: {error}");
        return Code::Deny;
    }
    match decision.verdict {
        Verdict::Allow | Verdict::Defer | Verdict::Review => Code::Ok,
        // `Deny`, and any verdict added to the core later, blocks the call.
        _ => {
            // Hosts may show hook stderr in a terminal; the reason quotes the call.
            eprintln!(
                "{}",
                render::clean_lines(&openmoat_hosts::reason_line(decision))
            );
            deny_code(host)
        }
    }
}

/// The exit code of a deny whose response was written: 2, or 0 for a host
/// that reads the deny from its output and may ignore a non-zero exit
/// ([`openmoat_hosts::HostSpec::deny_exit`]).
fn deny_code(host: Host) -> Code {
    if host.spec().deny_exit == 0 {
        Code::Ok
    } else {
        Code::Deny
    }
}

/// `by_run`: `openmoat run` relayed the call from inside its sandbox
/// (`--relayed`). `event` is set to the payload's event as soon as it is read,
/// for the deny [`run`] answers with if this panics.
fn decide_and_respond(installed_for: Host, by_run: bool, event: &mut HookEvent) -> Code {
    let started = Instant::now();
    // Inside `moat run` the sandbox holds no OpenMoat home: the run decides
    // (ADR-028). Only there: a guard that can open its lock, or that no sandbox
    // of `openmoat run` holds, decides itself whatever its environment says.
    let env = |var: &str| std::env::var(var).ok();
    let stray_relay = match guard_relay::relay(&env, Home::locate().ok().as_ref()) {
        guard_relay::Relay::Inside(endpoint) => return relayed(installed_for, endpoint, started),
        guard_relay::Relay::Outside => true,
        guard_relay::Relay::Unset => false,
    };

    // The event is read separately so a payload that cannot be parsed is still
    // refused in the format its hook expects.
    let mut host = installed_for;
    let mut out = Evaluated::default();
    hangs::enter(Phase::Stdin);
    let (mut request, mut decision) = match read_stdin(installed_for) {
        Ok(payload) => {
            // The Continue CLI runs the Claude Code hook but cannot prompt.
            host = installed_for.sender(&payload, entry::caller_set());
            *event = host.event_of_as(&payload, entry::event());
            deadline::saw(host, event);
            // What a call returned: nothing to decide or record (ADR-057).
            if matches!(event, HookEvent::PostToolUse { .. }) {
                return post_tool_use::answer(host, &payload, event);
            }
            // Inside `openmoat run` only when the run relayed it and named its session.
            let run = std::env::var(taint::run::RUN_SESSION_ENV).ok();
            let within_run = by_run && taint::run::run_session(run.as_deref()).is_some();
            evaluate(host, &payload, &mut out, (started, within_run))
                .unwrap_or_else(|error| (None, kernel_error(&error)))
        }
        Err(error) => (None, kernel_error(&error)),
    };

    // In a mode that asks no person, `unattended: review` holds a defer (ADR-102).
    if let Some(r) = &mut request {
        unattended::apply(host, out.unattended, r, &mut decision);
    }
    // Where the host would approve a `review` no person sees, it is a deny.
    if let Some(r) = &mut request
        && decision.verdict == Verdict::Review
    {
        unseen::mark(host, r);
    }
    // Where the host has no flow of its own for `defer`, OpenMoat holds the call for review (ADR-025).
    // Last: a `review` a person approved from another device runs once, and
    // one not yet sent is sent (ADR-078), its answer waited for a bounded
    // time while the listener runs (ADR-093); anything else is left as it is.
    let mut approved = None;
    if let Some(r) = &request {
        let decided = host.decided(&r.event, decision);
        (decision, approved) = crate::remote::gated(r, decided, &out.known, (started, by_run));
    }
    // What the agent and its person read about a deny or review (ADR-059);
    // presentation only, never recorded. A deny that replaces the decision
    // below carries its own, without the call ([`kernel_error`]).
    let call = request
        .as_ref()
        .map(|r| (r.tool.as_str(), r.action.as_ref()));
    decision.notice = notice::of(&decision, &out.titles, call, &out.known);
    // The audit log is part of the decision: a call that cannot be recorded
    // is not allowed, so a missing or unwritable log cannot hide activity.
    let recorded = Recorded {
        request: request.as_ref(),
        decision: &decision,
        drifted: &out.drifted,
        started,
        known: out.known,
        cache: out.cache,
        provenance: out.provenance,
        relayed: by_run,
    };
    if let Some(deny) = record::refusal(host, recorded, out.proxy_credential.as_ref(), approved) {
        decision = deny;
    }
    if stray_relay {
        // A note beside the call's row; the call stays as decided.
        record::relay_outside(host, request.as_ref());
    }

    hangs::enter(Phase::Answer);
    let event = request
        .as_ref()
        .map_or_else(|| event.clone(), |r| r.event.clone());
    // What the host receives can be stricter than what was decided and recorded
    // (Codex and the Continue CLI cannot prompt, so a `review` reaches them as a `deny`).
    let decision = host.answer(&event, &decision);
    let code = match &request {
        Some(request) => answer_once(host, &Answer::For(request), &decision).unwrap_or(Code::Deny),
        None => respond(host, &event, &decision),
    };
    // Only once the host has its answer (ADR-081): live audit delivery runs
    // detached and changes nothing above.
    crate::delivery::kick_located();
    code
}

/// What deciding a call leaves for [`record::record()`], besides the decision.
#[derive(Default)]
struct Evaluated {
    /// The brokered secret values to mask in the audit row, set as soon as
    /// the policy is loaded, so it holds them even when a later step fails.
    known: KnownSecrets,
    /// The session's fold to store, written with the record so the call
    /// opens one writable handle.
    cache: Option<taint::CacheWrite>,
    /// The settings drift the lock let the call be decided through ([`integrity::check`]).
    drifted: Vec<Drift>,
    /// The file provenance rows the call adds when it runs (ADR-029).
    provenance: taint::provenance::Seen,
    /// A session start's `openmoat proxy` credential, written to the
    /// session's environment file once its row is recorded (ADR-044).
    proxy_credential: Option<session_start::Pending>,
    /// The titles the person's policy gives the decision's rules, for the
    /// block message (ADR-059).
    titles: notice::Titles,
    /// The person's policy's `unattended:` (ADR-102), set once it is loaded.
    unattended: openmoat_core::Unattended,
}

/// Decide one hook payload, filling `out` as it goes. `started` is when the
/// guard started, which its budget counts from; `within_run`, whether the call
/// runs inside `openmoat run`'s sandbox.
fn evaluate(
    host: Host,
    payload: &str,
    out: &mut Evaluated,
    (started, within_run): (Instant, bool),
) -> Result<(Option<HookRequest>, Decision)> {
    hangs::enter(Phase::Parse);
    let request = host
        .parse_request_as(payload, entry::event())
        .context("parsing hook payload")?;
    fault_point("evaluate");
    let home = Home::locate()?;

    if let HookEvent::SessionStart { .. } = &request.event {
        let env = |name: &str| std::env::var_os(name);
        let (decision, pending) = session_start::decision(&home, &request, &env, within_run)?;
        out.proxy_credential = pending;
        return Ok((Some(request), decision));
    }
    if let HookEvent::ConfigChange {
        source,
        change_type,
    } = &request.event
    {
        let change = change_type.as_deref().unwrap_or("changed");
        let decision = config_change::decision(&home, &request, source, change)?;
        return Ok((Some(request), decision));
    }
    // Lock before decide, ungoverned tools included: an `allow` while pinned
    // files drifted would tell whoever tampered that nothing noticed. Drift of
    // only Claude Code toggles and permission lists changes no decision, so the
    // call is decided as usual and the drift recorded (`integrity/relaxed.rs`).
    hangs::enter(Phase::Lock);
    let verified = integrity::check(&home)?;
    if let Some(decision) = verified.checked.deny {
        return Ok((Some(request), decision));
    }
    out.drifted = verified.checked.relaxed;
    // From here each pinned state file is read as the lock check matched it.
    let home = verified.home;
    hangs::enter(Phase::Placed);
    let request = placed::placed(&home, host, request, &out.drifted)?;
    // A server whose definition a person has not accepted runs a command
    // nobody reviewed; only its own tool calls are held back (ADR-026).
    if let Some(openmoat_core::Action::McpTool { name, .. }) = &request.action {
        let cwd = request.cwd.as_deref().map(std::path::Path::new);
        if let Some(decision) = crate::mcp::violation(&home, &verified.lock, host, cwd, name)? {
            return Ok((Some(request), decision));
        }
    }
    let Some(action) = &request.action else {
        let call = required::Call {
            home: &home,
            host,
            drifted: &out.drifted,
            within_run,
        };
        let decision = required::ungoverned(&call, &request, ungoverned(host));
        return Ok((Some(request), decision));
    };
    let cwd = request
        .cwd
        .as_deref()
        .map(std::path::PathBuf::from)
        .map_or_else(std::env::current_dir, Ok)
        .context("resolving working directory")?;
    hangs::enter(Phase::Context);
    let ctx = context::eval_context(&home, Some(&cwd), None)?;
    // The decoy keys a person had `init` plant (ADR-106): their paths are the
    // first deny rule, their values masked and refused below.
    let decoys = crate::canary::Record::load(&home)?.decoys();
    hangs::enter(Phase::Policy);
    let mut policy = crate::repo::effective_policy(&home, &ctx)?;
    decoys.guard(&mut policy);
    hangs::enter(Phase::Secrets);
    out.known = secrets::known_with(&policy.secrets, &ctx.home, &decoys.values)?;
    out.unattended = policy.unattended();
    // An agent below the level the policy requires gets no decision but this
    // deny, on every call (ADR-064); nothing to read when none is required.
    let call = required::Call {
        home: &home,
        host,
        drifted: &out.drifted,
        within_run,
    };
    if let Some(decision) = required::unmet(&call, &policy) {
        return Ok((Some(request), decision));
    }
    hangs::enter(Phase::Snapshot);
    let snapshot = Snapshot::load_in(&home)?;
    hangs::enter(Phase::Compile);
    let compiled = CompiledPolicy::compile(&policy, &ctx)?;
    hangs::enter(Phase::Decide);
    let programs = WithOwnBinary {
        snapshot: &snapshot,
        binary: &verified.lock.binary,
    };
    let decision = compiled.decide_with(action, &programs, &FsPathResolver);
    // A write that leaves a project settings file turning its host's hook off;
    // only tightens, and before the grant, which cannot lift a deny.
    let decision = crate::project_settings::written::checked(&home, &request, &ctx, decision);
    hangs::enter(Phase::Audit);
    let store = home.open_audit()?;
    hangs::enter(Phase::Taint);
    // A part of the call that came from untrusted output the session read
    // (ADR-057); before the grant, so a person's grant for this exact call
    // answers it.
    let session_of = (host, request.session_id.as_str());
    let decision =
        taint::injected::checked(&home, &store, session_of, &compiled, action, decision)?;
    // The policy's argument conditions (ADR-113): before the grant, as any
    // rule's review is.
    let arguments = crate::arguments::of_mcp(request.mcp_arguments.as_deref());
    let mut decision = taint::injected::with_lookup(&home, &store, session_of, |seen| {
        compiled.with_arguments(decision, action, &FsPathResolver, &arguments, seen)
    })?;
    // A grant a person made with `moat allow` turns a `review` or a `defer` into an
    // `allow` (Cursor's file tools get a review for a defer, so they need it); a deny stays a deny.
    if matches!(decision.verdict, Verdict::Review | Verdict::Defer)
        && let Some(reviewed) = approvals::approvable(action, Some(&ctx.cwd), &ctx.home)
        && Grants::load_in(&home)?.matches(
            approvals::Scope {
                host: host.id(),
                session_id: &request.session_id,
                project: &approvals::project_in(&ctx),
            },
            &reviewed,
            crate::time::now_ms(),
        )
    {
        decision = Decision::new(Verdict::Allow);
        decision.rules.push(APPROVED_SESSION.to_owned());
        decision
            .reasons
            .push("approved for this session with `openmoat allow`".to_owned());
    }
    // After the grant: taint only tightens, and a grant made before the
    // session read a secret did not approve sending that secret anywhere.
    // A grant made after the session read untrusted content answers that
    // content's review for this exact call (taint.rs).
    // A long fold saves what it reached as it goes, on a writable handle, so
    // the next call reads on even if this one runs out of time
    // (`CacheWrite::save_in` says why that handle comes from the key's module).
    let mut save = |write: &taint::CacheWrite| write.save_in(&home);
    let mut progress = taint::Progress {
        deadline: (started + taint_budget(host)).max(Instant::now() + MIN_TAINT_TIME),
        save: &mut save,
        every: taint::checkpoint_every(),
        folded: 0,
    };
    let (session, write) = taint::of_session(
        &store,
        host,
        &request.session_id,
        &compiled,
        &ctx.cwd,
        &mut progress,
    )?;
    out.cache = write;
    let seen = taint::provenance::Call {
        session: &request.session_id,
        action,
        content: request.content.as_deref(),
        edits: &request.edits,
        untrusted: session.taint.untrusted.as_deref(),
    };
    out.provenance = taint::provenance::observe(&store, &compiled, &seen)?;
    let tainted = compiled.with_taint(decision.clone(), action, &FsPathResolver, &session.taint);
    let call = taint::Call {
        home: &home,
        store: &store,
        host,
        session: &request.session_id,
        action,
        cwd: &ctx.cwd,
        user_home: &ctx.home,
    };
    let decision = taint::answered(
        &call,
        &compiled,
        &session,
        decision,
        tainted,
        crate::time::now_ms(),
    )?;
    // A send of data after the session collected files outside the project
    // (ADR-061, proposed): decided where a rule names `@staging-egress`,
    // otherwise only recorded in the reasons.
    let decision = compiled.with_staging(
        decision,
        action,
        &FsPathResolver,
        &session.staging,
        &taint::is_dir,
    );
    // Private data, untrusted content and a way out in one session (ADR-113);
    // after the grant, which did not see the session's reads.
    let decision = compiled.with_trifecta(decision, action, &FsPathResolver, &session.taint);
    // Code this session wrote, run with no OS sandbox below the hook; only
    // tightens (ADR-039). Part of the taint phase: it reads the audit log.
    let code = session_code::Call {
        home: &home,
        host,
        session: &request.session_id,
        action,
        cwd: &ctx.cwd,
        user_home: &ctx.home,
        writes: &out.provenance.written,
        within_run,
    };
    let sandboxed = || crate::protection::os_sandboxed_by_lock(&home, host, &out.drifted);
    let decision = session_code::checked(
        &code,
        &compiled,
        &store,
        decision,
        (crate::time::now_ms(), &sandboxed),
    )?;
    // Another MCP server's result carried into a tool that acts; only
    // tightens (ADR-058).
    let flow = crate::mcp::flow::Sink {
        home: &home,
        store: &store,
        host,
        session: &request.session_id,
        action,
        arguments: request.mcp_arguments.as_deref(),
        policy: compiled.policy(),
    };
    let decision = crate::mcp::flow::checked(&flow, decision)?;
    drop(store);
    // Last: a push is checked for what it would publish (push.rs); only tightens.
    let tainted = session.taint.untrusted.is_some() || !session.taint.secrets.is_empty();
    let pushes = compiled.pushes(action);
    let decision = push::check(&pushes, &snapshot, &out.known, tainted, decision);
    // A hook, plugin hook or git program this agent loads that no person
    // accepted since it was added or changed; only tightens, and after the
    // grant, which cannot answer it (ADR-109).
    let hold = crate::hook_ledger::violation(&home, &verified.lock, host, Some(&cwd), &compiled);
    let decision = crate::hook_ledger::tightened(decision, hold);
    // A decoy's value anywhere in the call, content and arguments included.
    let decision = decoys.checked_text(payload, decoys.checked(action, decision));
    out.titles = notice::Titles::of(compiled.policy(), &decision);
    Ok((Some(request), decision))
}

/// The hook payload on stdin, up to the limit for `host`: [`MAX_PAYLOAD_BYTES`]
/// for each copy of the call's arguments its payload carries
/// ([`openmoat_hosts::HostSpec::payload_copies`]), so a file is refused at the
/// same size whichever agent writes it.
fn read_stdin(host: Host) -> Result<String> {
    if let Some(payload) = entry::kept_payload() {
        return Ok(payload);
    }
    let limit = guard_relay::payload_limit(host);
    let mut payload = String::new();
    // One byte past the limit tells a payload that is too large from one that
    // only ends there; cut off, it would fail as malformed JSON instead.
    io::stdin()
        .lock()
        .take(limit + 1)
        .read_to_string(&mut payload)
        .context("reading hook payload from stdin (must be UTF-8)")?;
    if payload.len() as u64 > limit {
        bail!(
            "this tool call's arguments are larger than {} MiB, more than OpenMoat checks in \
             one call, so it is refused unchecked; write the file in smaller parts (create \
             it, then append to it)",
            MAX_PAYLOAD_BYTES / (1024 * 1024)
        );
    }
    if payload.trim().is_empty() {
        bail!("empty hook payload on stdin");
    }
    capture::keep(host, &payload);
    Ok(payload)
}

/// A tool OpenMoat does not govern is recorded, and the host decides it as if no
/// hook had answered (ADR-025): an `allow` would skip the host's own prompt and
/// permission rules for a tool nobody checked. A host whose hooks have no "no
/// decision" gets an `allow` instead (`Reviews::ungoverned`).
fn ungoverned(host: Host) -> Decision {
    let mut decision = Decision::new(host.spec().reviews.ungoverned);
    decision.rules.push(UNGOVERNED.to_owned());
    decision
        .reasons
        .push("tool is outside policy scope".to_owned());
    decision
}

fn kernel_error(error: &anyhow::Error) -> Decision {
    let mut decision = Decision::new(Verdict::Deny);
    decision.rules.push(KERNEL_ERROR.to_owned());
    decision
        .reasons
        .push(format!("kernel could not evaluate this action: {error:#}"));
    // Its words are OpenMoat's own (ADR-059), so the deny that answers a
    // panic, the budget or an unwritable log reads as every other one does.
    decision.notice = notice::of(
        &decision,
        &notice::Titles::default(),
        None,
        &KnownSecrets::default(),
    );
    decision
}