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