Skip to main content

mur_common/hitl/
mod.rs

1//! Risk-tiered HITL vocabulary shared across the executor, runtime, and surfaces.
2
3use serde::{Deserialize, Serialize};
4
5pub mod approval_token;
6pub mod bash_class;
7pub mod builtin_tier;
8pub mod dest;
9pub mod floor_waiver;
10mod heredoc_data;
11pub mod intent;
12pub mod label;
13mod opaque_shell;
14pub mod pin;
15pub mod signed_time;
16pub mod tool_tier;
17
18pub use signed_time::{HITL_CLOCK_SKEW_SECS, TimeFault, check_answer_time, check_fresh};
19
20/// Approvals and denials settle a gate for this long. Content staleness is
21/// already handled by the hash pin (any input change = a different hash); the
22/// TTL bounds TIME staleness, so a weeks-old approval cannot release a gate
23/// nobody remembers granting. Measured on the signed `issued_at` only — see
24/// [`signed_time`]. Shared by gate A (`mur-core::hitl::gate`) and
25/// gate B (`mur-agent-runtime::hitl::store`) — one number, or the two gates
26/// remember for different lengths and the Hub cannot explain why.
27pub const APPROVAL_TTL_SECS: i64 = 7 * 24 * 60 * 60;
28
29/// `message/send` param: `false` makes this turn's tool approvals one-shot —
30/// gate B neither answers them from the agent's remembered decisions nor
31/// records the human's answer there. Absent means `true` (chat behaviour).
32/// A `mur fleet review` turn sends `false`: its gate always asks (#1783).
33pub const REMEMBER_DECISIONS_PARAM: &str = "remember_decisions";
34
35/// How risky an action is. `Ord` is severity order: `Read` < … < `Privileged`.
36/// Tier is resolved most-restrictive-wins and is NEVER LLM-asserted.
37#[derive(
38    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, schemars::JsonSchema,
39)]
40#[serde(rename_all = "kebab-case")]
41pub enum RiskTier {
42    Read,
43    Write,
44    NetworkEgress,
45    Spend,
46    Destructive,
47    Privileged,
48}
49
50/// What the gate does for a tier.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
52#[serde(rename_all = "lowercase")]
53pub enum HitlMode {
54    /// Run unattended (read tier): a post-hoc audit event is fine.
55    Auto,
56    /// Pre-execution human approval required.
57    Ask,
58    /// Refuse pre-emptively.
59    Deny,
60}
61
62/// Default gate mode for a tier. Read runs unattended; everything mutating asks.
63/// A channel policy floor (future) may tighten Ask→Deny but never loosen.
64pub fn default_mode(tier: RiskTier) -> HitlMode {
65    match tier {
66        RiskTier::Read => HitlMode::Auto,
67        _ => HitlMode::Ask,
68    }
69}
70
71/// What an Ask-tier gate does when nobody has answered yet.
72///
73/// This is a policy floor, chosen by the run's owner — it may only tighten the
74/// outcome, never approve anything. `Deny` short-circuits before any lookup so
75/// a fleet declared free of risk-tiered work stays that way even if some older
76/// approval for the same action is still on the channel.
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
78#[serde(rename_all = "lowercase")]
79pub enum Unanswered {
80    /// Park the request durably and report the step blocked. Nobody waits; an
81    /// approval arriving later releases the gate on a subsequent run. The
82    /// default when no human is watching.
83    Defer,
84    /// Block the caller, polling until the gate timeout. The default when a
85    /// terminal is attached, and the right choice for an unattended run that
86    /// somebody IS watching on another surface.
87    Wait,
88    /// Refuse every Ask-tier action outright, without writing a request. For a
89    /// run that must never reach for a human — the failure is immediate and
90    /// legible instead of a request nobody will answer.
91    Deny,
92}
93
94impl Default for Unanswered {
95    /// The strict end of the three: a policy built without stating a mode must
96    /// never be the one that waits or lets something through.
97    fn default() -> Self {
98        Unanswered::Defer
99    }
100}
101
102/// May a run's owner take standing responsibility for this tier in config —
103/// i.e. pre-approve it once instead of being asked every time?
104///
105/// Capped at `Write` deliberately. A standing grant is real authority handed
106/// to an unattended process, so widening it is a decision to make in code with
107/// its reasoning written down, never something a user acquires by typing one
108/// more word into a YAML file. `Spend`, `Destructive` and `Privileged` are
109/// exactly the actions whose cost a human cannot undo by noticing later, and
110/// `NetworkEgress` is how data leaves — none of them belongs behind a config
111/// line today.
112pub fn tier_may_be_granted(tier: RiskTier) -> bool {
113    matches!(tier, RiskTier::Read | RiskTier::Write)
114}
115
116/// How far the agent carries a turn on its own before handing back.
117///
118/// ORTHOGONAL to `HitlMode`/`RiskTier`. Those answer "may this ACTION run?"
119/// and are enforced per tool call; this answers "is the TURN over?" and is
120/// enforced once, at the loop's termination branch. Neither may overrule the
121/// other: `Continue` never releases a risk gate, and an approved gate never
122/// extends a turn. Issue #001 is what happens when only the prompt layer
123/// carries this — the model reads "已授權工作持續推進" as a suggestion because
124/// nothing in the runtime ever re-entered the loop.
125#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
126#[serde(rename_all = "kebab-case")]
127pub enum Autonomy {
128    /// Mode 1, 持續推進 — a turn that ends with work still open is nudged back
129    /// into the loop instead of returning. Never implicit, not even for
130    /// unattended runs: handing an agent the right to keep going is written
131    /// down in a profile, because nobody is in the room to take it back.
132    Continue,
133    /// Mode 2, 需要再審核 — the agent finishes its own work but must present it
134    /// for review before anything further; the turn ends where it would anyway.
135    Review,
136    /// Mode 3, 用戶審核 — hand back at every natural stop. The strictest of the
137    /// three and the default when nothing is stated.
138    Ask,
139}
140
141impl Default for Autonomy {
142    /// The strict end, matching `Unanswered::default()`: a policy assembled
143    /// without stating a mode must never be the one that keeps going by
144    /// itself.
145    fn default() -> Self {
146        Autonomy::Ask
147    }
148}
149
150/// How many times one turn may be nudged onward. Bounded, and small: the
151/// iteration ceiling and the stuck clock are the real budgets, and a
152/// continuation that could fire endlessly would quietly convert both into a
153/// suggestion. One nudge is enough to fix #001 (the model stopped once, mid
154/// task) without inventing a second, parallel loop.
155pub const MAX_CONTINUATIONS: u32 = 1;
156
157/// Why a turn was NOT continued. Every variant is a thing the settlement card
158/// can print, because "it just stopped" is the bug being fixed.
159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
160pub enum ContinueVeto {
161    /// Policy says hand back — `Review` or `Ask`.
162    Policy,
163    /// A1: the turn did not end cleanly (ceiling, loop, deadline, stuck,
164    /// truncation). Those stops already have their own graceful exit and a
165    /// nudge would fight it.
166    UnCleanStop,
167    /// A2: a risk gate blocked, denied or deferred something this turn. The
168    /// human IS the next step; nudging would spin against a closed gate.
169    GateBlocked,
170    /// The nudge budget for this turn is spent.
171    BudgetSpent,
172}
173
174/// The whole continuation decision, as one pure function so the policy is
175/// testable without a model, a gate, or a clock.
176///
177/// `clean_stop` is "the model ended the turn of its own accord". `gate_blocked`
178/// is "at least one action this turn was refused, denied or parked". Both are
179/// facts the loop already holds at the termination branch.
180pub fn should_continue(
181    autonomy: Autonomy,
182    clean_stop: bool,
183    gate_blocked: bool,
184    continuations_used: u32,
185) -> Result<(), ContinueVeto> {
186    if autonomy != Autonomy::Continue {
187        return Err(ContinueVeto::Policy);
188    }
189    if !clean_stop {
190        return Err(ContinueVeto::UnCleanStop);
191    }
192    if gate_blocked {
193        return Err(ContinueVeto::GateBlocked);
194    }
195    if continuations_used >= MAX_CONTINUATIONS {
196        return Err(ContinueVeto::BudgetSpent);
197    }
198    Ok(())
199}
200
201/// `EventKind::HitlRequest` payload: the durable, pinned approval request.
202#[derive(Debug, Clone, Serialize, Deserialize)]
203pub struct HitlRequest {
204    pub hitl_id: String,
205    /// SHA-256 of the canonical action (see `mur-core` `hitl::pin`).
206    pub action_hash: String,
207    pub tier: RiskTier,
208    pub tool_name: String,
209    pub tool_input: serde_json::Value,
210    pub step_or_call_id: String,
211    pub agent_id: String,
212    pub timeout_ms: u64,
213    pub summary: String,
214    /// When the router asked. Inside the payload, so inside the signature —
215    /// unlike the store-assigned `ChannelEvent::ts`, which any process that
216    /// can write the log can rewrite (#1764). `None` is a request written
217    /// before this field existed; it answers nothing (fail closed).
218    #[serde(default, skip_serializing_if = "Option::is_none")]
219    pub issued_at: Option<chrono::DateTime<chrono::Utc>>,
220}
221
222/// `EventKind::HitlResponse` payload: the human's decision, echoing the pin.
223#[derive(Debug, Clone, Serialize, Deserialize)]
224pub struct HitlResponse {
225    pub hitl_id: String,
226    pub action_hash: String,
227    pub allow: bool,
228    #[serde(default)]
229    pub reason: String,
230    /// "cli" | "hub" | "ios" | "auto".
231    pub surface: String,
232    /// When the answer was given; signed for the same reason as
233    /// [`HitlRequest::issued_at`]. `None` (an older writer) settles nothing.
234    #[serde(default, skip_serializing_if = "Option::is_none")]
235    pub issued_at: Option<chrono::DateTime<chrono::Utc>>,
236    /// What was decided, for `mur agent hitl list` (#1806): tool name plus a
237    /// redacted, truncated summary built by [`label::decision_label`]. It is
238    /// written into a signed append-only log, so it must never carry raw
239    /// input. `None` = an older writer, or a surface that has no tool call.
240    #[serde(default, skip_serializing_if = "Option::is_none")]
241    pub label: Option<String>,
242}
243
244/// `message/send`-style A2A methods for gate B's remembered decisions (#1806).
245pub const HITL_LIST_METHOD: &str = "hitl/list";
246pub const HITL_FORGET_METHOD: &str = "hitl/forget";
247
248/// #2085: lists the approvals a running agent is waiting on right now, so a
249/// human can answer one from another terminal (`mur agent hitl pending`).
250pub const HITL_PENDING_METHOD: &str = "hitl/pending";
251
252/// #2085: `message/send` param. With `can_approve: false`, an `Ask` call
253/// nobody has decided is parked for at most this many seconds (clamped to the
254/// turn's deadline) instead of refused at once; `mur agent hitl approve`
255/// answers it. Absent = refuse at once, the #2087 behaviour.
256pub const WAIT_APPROVAL_PARAM: &str = "wait_approval_secs";
257
258/// How long `mur agent send --wait-approval` (no value) parks a call. The
259/// turn's deadline still wins when it comes first.
260pub const DEFAULT_WAIT_APPROVAL_SECS: u64 = 30 * 60;
261
262/// Key inside an `EventKind::Note` payload that marks a gate-B revocation.
263/// A `Note` rather than a new `EventKind` so a reader built before #1806
264/// still parses the channel (an unknown kind would fail the whole line).
265pub const REVOCATION_PAYLOAD_KEY: &str = "hitl_revocation";
266
267/// Which remembered decisions a revocation covers.
268#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
269#[serde(rename_all = "snake_case", tag = "scope", content = "action_hash")]
270pub enum RevocationScope {
271    One(String),
272    All,
273}
274
275/// A signed "forget": every decision covered by `scope` whose signed
276/// `issued_at` is not after this one's `issued_at` stops settling the gate.
277/// Nothing is deleted — the log stays append-only (#1770).
278#[derive(Debug, Clone, Serialize, Deserialize)]
279pub struct HitlRevocation {
280    #[serde(flatten)]
281    pub scope: RevocationScope,
282    pub issued_at: chrono::DateTime<chrono::Utc>,
283}
284
285impl HitlRevocation {
286    pub fn to_payload(&self) -> serde_json::Value {
287        serde_json::json!({ REVOCATION_PAYLOAD_KEY: self })
288    }
289
290    /// `None` = not a revocation note (or a malformed one, which revokes
291    /// nothing — the safe reading is "still remembered", and the gate asked
292    /// when that decision was recorded).
293    pub fn from_payload(payload: &serde_json::Value) -> Option<Self> {
294        serde_json::from_value(payload.get(REVOCATION_PAYLOAD_KEY)?.clone()).ok()
295    }
296
297    pub fn covers(&self, action_hash: &str) -> bool {
298        match &self.scope {
299            RevocationScope::All => true,
300            RevocationScope::One(h) => h == action_hash,
301        }
302    }
303}
304
305#[cfg(test)]
306mod tests {
307    use super::*;
308
309    #[test]
310    fn tier_orders_by_severity_and_maps_mode() {
311        assert!(RiskTier::Read < RiskTier::Destructive);
312        assert!(RiskTier::Write < RiskTier::Privileged);
313        assert_eq!(default_mode(RiskTier::Read), HitlMode::Auto);
314        assert_eq!(default_mode(RiskTier::Destructive), HitlMode::Ask);
315    }
316
317    #[test]
318    fn hitl_payloads_round_trip() {
319        let req = HitlRequest {
320            hitl_id: "h1".into(),
321            action_hash: "abc".into(),
322            tier: RiskTier::Destructive,
323            tool_name: "bash".into(),
324            tool_input: serde_json::json!({ "cmd": "rm -rf x" }),
325            step_or_call_id: "s0".into(),
326            agent_id: "mur".into(),
327            timeout_ms: 300_000,
328            summary: "delete x".into(),
329            issued_at: Some(chrono::Utc::now()),
330        };
331        let s = serde_json::to_string(&req).unwrap();
332        let back: HitlRequest = serde_json::from_str(&s).unwrap();
333        assert_eq!(back.tier, RiskTier::Destructive);
334        assert_eq!(back.action_hash, "abc");
335    }
336
337    /// The grantable ceiling. Widening this list is a security decision that
338    /// belongs in a commit message, not a YAML typo — the test exists so the
339    /// reviewer has to read the reasoning right here.
340    #[test]
341    fn tier_grant_ceiling_is_write() {
342        assert!(tier_may_be_granted(RiskTier::Read));
343        assert!(tier_may_be_granted(RiskTier::Write));
344        assert!(!tier_may_be_granted(RiskTier::NetworkEgress));
345        assert!(!tier_may_be_granted(RiskTier::Spend));
346        assert!(!tier_may_be_granted(RiskTier::Destructive));
347        assert!(!tier_may_be_granted(RiskTier::Privileged));
348    }
349
350    /// #001 §6 A0: the safe default. An `Autonomy` nobody stated must be the
351    /// one that hands back, never the one that drives itself.
352    #[test]
353    fn autonomy_defaults_to_the_strictest_mode() {
354        assert_eq!(Autonomy::default(), Autonomy::Ask);
355    }
356
357    /// The happy path this whole feature exists for: unattended work, a clean
358    /// stop, no blocked gate, budget unspent → carry on.
359    #[test]
360    fn continue_mode_resumes_a_clean_unblocked_turn() {
361        assert_eq!(should_continue(Autonomy::Continue, true, false, 0), Ok(()));
362    }
363
364    /// The other two modes are handbacks by construction. This is the test
365    /// that keeps "持續推進" from silently becoming the behaviour of all three.
366    #[test]
367    fn review_and_ask_never_continue() {
368        for mode in [Autonomy::Review, Autonomy::Ask] {
369            assert_eq!(
370                should_continue(mode, true, false, 0),
371                Err(ContinueVeto::Policy),
372                "{mode:?} must hand back"
373            );
374        }
375    }
376
377    /// #001 §6 A1: a turn stopped by a budget (ceiling / loop / deadline /
378    /// stuck) already has a graceful exit. Nudging it would fight that exit.
379    #[test]
380    fn an_unclean_stop_is_never_continued() {
381        assert_eq!(
382            should_continue(Autonomy::Continue, false, false, 0),
383            Err(ContinueVeto::UnCleanStop)
384        );
385    }
386
387    /// #001 §6 A2 — THE SAFETY BOUNDARY. Continuation and the risk gate are
388    /// orthogonal: when a gate blocked, denied or deferred something, the
389    /// human is the next step and no autonomy setting may route around them.
390    /// If this test ever goes green with `Ok(())`, `Autonomy::Continue` has
391    /// become a privilege escalation.
392    #[test]
393    fn continuation_never_routes_around_a_blocked_gate() {
394        assert_eq!(
395            should_continue(Autonomy::Continue, true, true, 0),
396            Err(ContinueVeto::GateBlocked)
397        );
398    }
399
400    /// Bounded, and the bound is enforced here rather than by hoping the loop
401    /// converges.
402    #[test]
403    fn continuation_budget_is_spent_after_max() {
404        assert_eq!(
405            should_continue(Autonomy::Continue, true, false, MAX_CONTINUATIONS),
406            Err(ContinueVeto::BudgetSpent)
407        );
408        assert_eq!(
409            should_continue(Autonomy::Continue, true, false, MAX_CONTINUATIONS + 9),
410            Err(ContinueVeto::BudgetSpent)
411        );
412    }
413
414    /// Policy is checked before anything else, so a `Ask` run reports "policy"
415    /// rather than leaking why it would ALSO have been stopped.
416    #[test]
417    fn policy_veto_precedes_every_other_veto() {
418        assert_eq!(
419            should_continue(Autonomy::Ask, false, true, 99),
420            Err(ContinueVeto::Policy)
421        );
422    }
423
424    #[test]
425    fn autonomy_round_trips_as_kebab_case() {
426        let y = serde_yaml::to_string(&Autonomy::Continue).unwrap();
427        assert!(y.contains("continue"), "got {y}");
428        let back: Autonomy = serde_yaml::from_str("review").unwrap();
429        assert_eq!(back, Autonomy::Review);
430    }
431
432    #[test]
433    fn revocation_payload_round_trips_and_ignores_other_notes() {
434        let at = chrono::Utc::now();
435        for scope in [RevocationScope::All, RevocationScope::One("abc".into())] {
436            let r = HitlRevocation {
437                scope: scope.clone(),
438                issued_at: at,
439            };
440            let back = HitlRevocation::from_payload(&r.to_payload()).expect("round trip");
441            assert_eq!(back.scope, scope);
442            assert_eq!(back.issued_at, at);
443        }
444        let one = HitlRevocation {
445            scope: RevocationScope::One("abc".into()),
446            issued_at: at,
447        };
448        assert!(one.covers("abc") && !one.covers("abd"));
449        assert!(HitlRevocation::from_payload(&serde_json::json!({"review": {}})).is_none());
450        assert!(HitlRevocation::from_payload(&serde_json::json!({"hitl_revocation": 1})).is_none());
451    }
452
453    #[test]
454    fn a_response_without_label_still_parses() {
455        let v = serde_json::json!({"hitl_id": "h", "action_hash": "a", "allow": true, "surface": "hub"});
456        let r: HitlResponse = serde_json::from_value(v).unwrap();
457        assert!(r.label.is_none());
458        assert!(!serde_json::to_string(&r).unwrap().contains("label"));
459    }
460}