Skip to main content

harn_vm/
autonomy.rs

1use std::cell::RefCell;
2use std::collections::{BTreeMap, BTreeSet};
3use std::future::Future;
4use std::pin::Pin;
5
6use serde::{Deserialize, Serialize};
7use serde_json::Value as JsonValue;
8use uuid::Uuid;
9
10use crate::event_log::{active_event_log, EventLog, LogEvent, Topic};
11use crate::stdlib::hitl::append_approval_request_on;
12use crate::triggers::dispatcher::current_dispatch_context;
13use crate::trust_graph::{append_trust_record, AutonomyTier, TrustOutcome, TrustRecord};
14use crate::value::{categorized_error, ErrorCategory, VmError, VmValue};
15
16/// Stable diagnostic prefix for a deny driven by the `needs-human` autonomy
17/// class. Approval surfaces (Slack, IDE, portal) match on this code to render
18/// the deny distinctly from a normal tier-based block.
19pub const HARN_AUT_NEEDS_HUMAN_CODE: &str = "HARN-AUT-NEEDS-HUMAN";
20
21/// Canonical string value of the `needs-human` autonomy class. Mirrors
22/// `RepairSafety::NeedsHuman.as_str()` from `harn-parser` so the autonomy
23/// surface and the repair-safety surface stay in lockstep.
24pub const NEEDS_HUMAN_AUTONOMY_CLASS: &str = "needs-human";
25
26thread_local! {
27    static AUTONOMY_POLICY_STACK: RefCell<Vec<AutonomyPolicy>> = const { RefCell::new(Vec::new()) };
28}
29
30#[derive(Clone, Debug, Default, Deserialize, Serialize)]
31#[serde(default)]
32pub struct AutonomyPolicy {
33    pub agent_id: Option<String>,
34    pub autonomy_tier: Option<AutonomyTier>,
35    pub tier: Option<AutonomyTier>,
36    pub action_tiers: BTreeMap<String, AutonomyTier>,
37    pub agent_tiers: BTreeMap<String, AutonomyTier>,
38    pub agent_action_tiers: BTreeMap<String, BTreeMap<String, AutonomyTier>>,
39    pub reviewers: Vec<String>,
40    /// Mark the whole policy as `needs-human`: every side-effecting builtin
41    /// covered by this policy raises a structured `HARN-AUT-NEEDS-HUMAN`
42    /// deny, regardless of the resolved `autonomy_tier`.
43    #[serde(default)]
44    pub requires_human: bool,
45    /// Per-action or per-class needs-human tags. Entries match either the
46    /// builtin name (`write_file`) or the action class (`fs.write`).
47    /// Mutually exclusive with auto-apply: an entry here always wins over
48    /// any tier resolution.
49    #[serde(default, alias = "action_requires_human")]
50    pub requires_human_actions: BTreeSet<String>,
51    /// Per-agent needs-human tags. If an agent is listed here, every side
52    /// effect it attempts is treated as needs-human.
53    #[serde(default)]
54    pub requires_human_agents: BTreeSet<String>,
55}
56
57impl AutonomyPolicy {
58    fn effective_tier_for(
59        &self,
60        agent_id: &str,
61        action: &SideEffectAction,
62    ) -> Option<AutonomyTier> {
63        self.agent_action_tiers
64            .get(agent_id)
65            .and_then(|tiers| {
66                tiers
67                    .get(action.builtin)
68                    .or_else(|| tiers.get(action.class))
69                    .copied()
70            })
71            .or_else(|| self.agent_tiers.get(agent_id).copied())
72            .or_else(|| {
73                self.action_tiers
74                    .get(action.builtin)
75                    .or_else(|| self.action_tiers.get(action.class))
76                    .copied()
77            })
78            .or(self.autonomy_tier)
79            .or(self.tier)
80    }
81
82    /// Resolve whether a given (agent, action) is tagged `needs-human` under
83    /// this policy. Any positive signal — blanket `requires_human`, a
84    /// per-agent tag, or a per-builtin/per-class tag — flips the action into
85    /// the needs-human discipline.
86    fn is_needs_human(&self, agent_id: &str, action: &SideEffectAction) -> bool {
87        if self.requires_human {
88            return true;
89        }
90        if self.requires_human_agents.contains(agent_id) {
91            return true;
92        }
93        if self.requires_human_actions.contains(action.builtin)
94            || self.requires_human_actions.contains(action.class)
95        {
96            return true;
97        }
98        false
99    }
100}
101
102fn action(
103    builtin: &'static str,
104    class: &'static str,
105    capability: &'static str,
106) -> SideEffectAction {
107    SideEffectAction {
108        builtin,
109        class,
110        capability,
111    }
112}
113
114fn workspace_write_action(builtin: &'static str, class: &'static str) -> SideEffectAction {
115    action(builtin, class, "workspace.write_text")
116}
117
118fn first_matching_action(
119    name: &str,
120    builtins: &[&'static str],
121    class: &'static str,
122    capability: &'static str,
123) -> Option<SideEffectAction> {
124    builtins
125        .iter()
126        .find(|builtin| **builtin == name)
127        .map(|builtin| action(builtin, class, capability))
128}
129
130fn first_workspace_write_action(
131    name: &str,
132    builtins: &[&'static str],
133    class: &'static str,
134) -> Option<SideEffectAction> {
135    builtins
136        .iter()
137        .find(|builtin| **builtin == name)
138        .map(|builtin| workspace_write_action(builtin, class))
139}
140
141#[derive(Clone, Copy, Debug, PartialEq, Eq)]
142pub struct SideEffectAction {
143    pub builtin: &'static str,
144    pub class: &'static str,
145    pub capability: &'static str,
146}
147
148#[derive(Clone, Debug)]
149struct AutonomyIdentity {
150    agent_id: String,
151    trace_id: String,
152    tier: AutonomyTier,
153    reviewers: Vec<String>,
154    /// Whether this (agent, action) is tagged `needs-human` by the
155    /// currently-active autonomy policy. When true the dispatcher MUST
156    /// deny auto-apply regardless of `tier`.
157    requires_human: bool,
158}
159
160#[derive(Clone, Debug)]
161pub enum AutonomyDecision {
162    Skip(VmValue),
163    AllowApproved,
164}
165
166pub struct AutonomyPolicyGuard;
167
168impl Drop for AutonomyPolicyGuard {
169    fn drop(&mut self) {
170        AUTONOMY_POLICY_STACK.with(|stack| {
171            stack.borrow_mut().pop();
172        });
173    }
174}
175
176pub fn push_autonomy_policy(policy: AutonomyPolicy) -> AutonomyPolicyGuard {
177    AUTONOMY_POLICY_STACK.with(|stack| stack.borrow_mut().push(policy));
178    AutonomyPolicyGuard
179}
180
181pub fn current_autonomy_policy() -> Option<AutonomyPolicy> {
182    AUTONOMY_POLICY_STACK.with(|stack| stack.borrow().last().cloned())
183}
184
185/// Per-task ambient-scope swap of the autonomy-policy stack. See
186/// `orchestration::ambient_scope`: a worker inherits its parent's autonomy
187/// tier, and `push_autonomy_policy` guards are held across `.await`, so the
188/// stack must follow the task rather than leak to interleaved siblings.
189pub(crate) fn swap_autonomy_policy_stack(next: Vec<AutonomyPolicy>) -> Vec<AutonomyPolicy> {
190    AUTONOMY_POLICY_STACK.with(|stack| std::mem::replace(&mut *stack.borrow_mut(), next))
191}
192
193pub fn is_side_effecting_builtin(name: &str) -> bool {
194    side_effect_action_for_builtin(name).is_some()
195}
196
197pub fn needs_async_side_effect_enforcement(name: &str) -> bool {
198    let Some(action) = side_effect_action_for_builtin(name) else {
199        return false;
200    };
201    current_identity(&action)
202        // `needs-human` always needs the async enforcement path so the
203        // dispatcher can emit the structured deny + approval-request,
204        // even when the resolved tier is `ActAuto`.
205        .is_some_and(|identity| identity.requires_human || identity.tier != AutonomyTier::ActAuto)
206}
207
208pub fn enforce_builtin_side_effect_boxed<'a>(
209    name: &'a str,
210    args: &'a [VmValue],
211) -> Pin<Box<dyn Future<Output = Result<Option<AutonomyDecision>, VmError>> + Send + 'a>> {
212    Box::pin(enforce_builtin_side_effect(name, args))
213}
214
215pub fn side_effect_action_for_builtin(name: &str) -> Option<SideEffectAction> {
216    first_workspace_write_action(
217        name,
218        &["write_file", "write_file_bytes", "append_file"],
219        "fs.write",
220    )
221    .or_else(|| first_workspace_write_action(name, &["mkdir"], "fs.mkdir"))
222    .or_else(|| first_workspace_write_action(name, &["mkdtemp"], "fs.mkdtemp"))
223    .or_else(|| {
224        first_workspace_write_action(name, &["mkdtemp_in_workspace"], "fs.mkdtemp_in_workspace")
225    })
226    .or_else(|| first_workspace_write_action(name, &["copy_file"], "fs.copy"))
227    .or_else(|| first_matching_action(name, &["delete_file"], "fs.delete", "workspace.delete"))
228    .or_else(|| first_workspace_write_action(name, &["move_file"], "fs.move"))
229    .or_else(|| {
230        first_matching_action(
231            name,
232            &["exec", "exec_at", "shell", "shell_at"],
233            "process.exec",
234            "process.exec",
235        )
236    })
237    .or_else(|| first_matching_action(name, &["host_call"], "host.call", "host.call"))
238    .or_else(|| {
239        first_matching_action(
240            name,
241            &["store_set", "store_delete", "store_save", "store_clear"],
242            "store.write",
243            "store.write",
244        )
245    })
246    .or_else(|| {
247        first_matching_action(
248            name,
249            &[
250                "metadata_set",
251                "metadata_save",
252                "metadata_refresh_hashes",
253                "invalidate_facts",
254                "path_metadata_set",
255                "verification_profiles_set",
256                "verification_profile_record_run",
257            ],
258            "metadata.write",
259            "metadata.write",
260        )
261    })
262    .or_else(|| {
263        first_matching_action(
264            name,
265            &["checkpoint", "checkpoint_delete", "checkpoint_clear"],
266            "checkpoint.write",
267            "checkpoint.write",
268        )
269    })
270    .or_else(|| {
271        first_matching_action(
272            name,
273            &[
274                "sse_server_response",
275                "sse_server_send",
276                "sse_server_heartbeat",
277                "sse_server_flush",
278                "sse_server_close",
279                "sse_server_cancel",
280                "sse_server_mock_receive",
281                "sse_server_mock_disconnect",
282            ],
283            "network.sse.write",
284            "network.sse",
285        )
286    })
287    .or_else(|| {
288        first_matching_action(
289            name,
290            &[
291                "__agent_state_write",
292                "__agent_state_delete",
293                "__agent_state_handoff",
294            ],
295            "agent_state.write",
296            "agent_state.write",
297        )
298    })
299    .or_else(|| first_matching_action(name, &["mcp_release"], "mcp.release", "mcp.release"))
300    .or_else(|| {
301        first_matching_action(
302            name,
303            &[
304                "git.worktree.create",
305                "git.worktree.remove",
306                "git.fetch",
307                "git.rebase",
308                "git.push",
309            ],
310            "git.write",
311            "git.write",
312        )
313    })
314}
315
316pub async fn enforce_builtin_side_effect(
317    name: &str,
318    args: &[VmValue],
319) -> Result<Option<AutonomyDecision>, VmError> {
320    let Some(action) = side_effect_action_for_builtin(name) else {
321        return Ok(None);
322    };
323    let Some(identity) = current_identity(&action) else {
324        return Ok(None);
325    };
326    // `needs-human` is a transverse discipline: it forbids auto-apply even
327    // when the resolved tier is `ActAuto`. Check this *before* tier
328    // dispatch so no tier can ever override it.
329    if identity.requires_human {
330        emit_proposal_event(identity.tier, action, args).await?;
331        let request_id = append_needs_human_approval_request(&identity, action, args).await?;
332        append_enforcement_record(
333            &identity,
334            action,
335            args,
336            TrustOutcome::Denied,
337            Some(request_id.clone()),
338        )
339        .await?;
340        return Err(needs_human_deny_error(&identity, action, &request_id));
341    }
342    match identity.tier {
343        AutonomyTier::ActAuto => Ok(None),
344        AutonomyTier::Shadow => {
345            emit_proposal_event(identity.tier, action, args).await?;
346            append_enforcement_record(&identity, action, args, TrustOutcome::Denied, None).await?;
347            Ok(Some(AutonomyDecision::Skip(VmValue::Nil)))
348        }
349        AutonomyTier::Suggest => {
350            emit_proposal_event(identity.tier, action, args).await?;
351            let request_id = append_nonblocking_approval_request(&identity, action, args).await?;
352            append_enforcement_record(
353                &identity,
354                action,
355                args,
356                TrustOutcome::Denied,
357                Some(request_id),
358            )
359            .await?;
360            Ok(Some(AutonomyDecision::Skip(VmValue::Nil)))
361        }
362        AutonomyTier::ActWithApproval => {
363            let approval = request_approval_before_effect(&identity, action, args).await?;
364            append_enforcement_record(
365                &identity,
366                action,
367                args,
368                TrustOutcome::Success,
369                approval.request_id,
370            )
371            .await?;
372            Ok(Some(AutonomyDecision::AllowApproved))
373        }
374    }
375}
376
377fn current_identity(action: &SideEffectAction) -> Option<AutonomyIdentity> {
378    let scoped = current_autonomy_policy();
379    let dispatch = current_dispatch_context();
380    let agent_id = scoped
381        .as_ref()
382        .and_then(|policy| policy.agent_id.clone())
383        .or_else(|| dispatch.as_ref().map(|context| context.agent_id.clone()))
384        .unwrap_or_else(|| "runtime".to_string());
385    let tier = scoped
386        .as_ref()
387        .and_then(|policy| policy.effective_tier_for(&agent_id, action))
388        .or_else(|| dispatch.as_ref().map(|context| context.autonomy_tier))?;
389    let trace_id = dispatch
390        .as_ref()
391        .map(|context| context.trigger_event.trace_id.0.clone())
392        .unwrap_or_else(|| format!("trace-{}", Uuid::now_v7()));
393    let reviewers = scoped
394        .as_ref()
395        .map(|policy| policy.reviewers.clone())
396        .filter(|reviewers| !reviewers.is_empty())
397        .unwrap_or_default();
398    let requires_human = scoped
399        .as_ref()
400        .map(|policy| policy.is_needs_human(&agent_id, action))
401        .unwrap_or(false);
402    Some(AutonomyIdentity {
403        agent_id,
404        trace_id,
405        tier,
406        reviewers,
407        requires_human,
408    })
409}
410
411fn detail_for(action: SideEffectAction, args: &[VmValue]) -> JsonValue {
412    serde_json::json!({
413        "builtin": action.builtin,
414        "action_class": action.class,
415        "args": args.iter().map(crate::llm::vm_value_to_json).collect::<Vec<_>>(),
416    })
417}
418
419fn needs_human_detail(action: SideEffectAction, args: &[VmValue]) -> JsonValue {
420    let mut detail = detail_for(action, args);
421    if let Some(obj) = detail.as_object_mut() {
422        obj.insert(
423            "autonomy_class".to_string(),
424            JsonValue::String(NEEDS_HUMAN_AUTONOMY_CLASS.to_string()),
425        );
426        obj.insert("requires_human".to_string(), JsonValue::Bool(true));
427        obj.insert(
428            "deny_code".to_string(),
429            JsonValue::String(HARN_AUT_NEEDS_HUMAN_CODE.to_string()),
430        );
431    }
432    detail
433}
434
435async fn emit_proposal_event(
436    tier: AutonomyTier,
437    action: SideEffectAction,
438    args: &[VmValue],
439) -> Result<(), VmError> {
440    let Some(context) = current_dispatch_context() else {
441        return Ok(());
442    };
443    let Some(log) = active_event_log() else {
444        return Ok(());
445    };
446    let topic = Topic::new(crate::TRIGGER_OUTBOX_TOPIC)
447        .map_err(|error| VmError::Runtime(format!("autonomy proposal topic error: {error}")))?;
448    let mut headers = BTreeMap::new();
449    headers.insert(
450        "trace_id".to_string(),
451        context.trigger_event.trace_id.0.clone(),
452    );
453    headers.insert("agent".to_string(), context.agent_id.clone());
454    headers.insert("autonomy_tier".to_string(), tier.as_str().to_string());
455    let payload = serde_json::json!({
456        "agent": context.agent_id,
457        "action": context.action,
458        "builtin": action.builtin,
459        "action_class": action.class,
460        "args": args.iter().map(crate::llm::vm_value_to_json).collect::<Vec<_>>(),
461        "trace_id": context.trigger_event.trace_id.0,
462        "replay_of_event_id": context.replay_of_event_id,
463        "autonomy_tier": tier,
464        "proposal": true,
465    });
466    log.append(
467        &topic,
468        LogEvent::new("dispatch_proposed", payload).with_headers(headers),
469    )
470    .await
471    .map(|_| ())
472    .map_err(|error| VmError::Runtime(format!("failed to append autonomy proposal: {error}")))
473}
474
475async fn append_nonblocking_approval_request(
476    identity: &AutonomyIdentity,
477    action: SideEffectAction,
478    args: &[VmValue],
479) -> Result<String, VmError> {
480    let log = active_event_log().ok_or_else(|| {
481        categorized_error(
482            "autonomy approval requires an active event log",
483            ErrorCategory::ToolRejected,
484        )
485    })?;
486    append_approval_request_on(
487        &log,
488        identity.agent_id.clone(),
489        identity.trace_id.clone(),
490        action.class.to_string(),
491        detail_for(action, args),
492        identity.reviewers.clone(),
493    )
494    .await
495}
496
497/// Emit a non-blocking approval request tagged with the `needs-human`
498/// autonomy class. Surfaces (Slack-approval, IDE, portal) match on the
499/// `autonomy_class` field in the request payload's `detail` to render the
500/// pending row distinctly from a normal tier-driven approval ask.
501async fn append_needs_human_approval_request(
502    identity: &AutonomyIdentity,
503    action: SideEffectAction,
504    args: &[VmValue],
505) -> Result<String, VmError> {
506    let log = active_event_log().ok_or_else(|| {
507        categorized_error(
508            "needs-human autonomy class requires an active event log",
509            ErrorCategory::ToolRejected,
510        )
511    })?;
512    append_approval_request_on(
513        &log,
514        identity.agent_id.clone(),
515        identity.trace_id.clone(),
516        format!("{}#needs-human", action.class),
517        needs_human_detail(action, args),
518        identity.reviewers.clone(),
519    )
520    .await
521}
522
523/// Build the structured deny returned when a `needs-human`-tagged side
524/// effect is attempted. The message is prefixed with [`HARN_AUT_NEEDS_HUMAN_CODE`]
525/// so approval surfaces and structured-error consumers can match on a stable
526/// token rather than substring-matching the human-readable text.
527fn needs_human_deny_error(
528    identity: &AutonomyIdentity,
529    action: SideEffectAction,
530    request_id: &str,
531) -> VmError {
532    categorized_error(
533        format!(
534            "{code}: side effect `{builtin}` ({class}) is tagged `needs-human` for agent `{agent}`; \
535             auto-apply is forbidden regardless of autonomy tier `{tier}`. \
536             Approval request `{request_id}` was queued.",
537            code = HARN_AUT_NEEDS_HUMAN_CODE,
538            builtin = action.builtin,
539            class = action.class,
540            agent = identity.agent_id,
541            tier = identity.tier.as_str(),
542            request_id = request_id,
543        ),
544        ErrorCategory::ToolRejected,
545    )
546}
547
548struct ApprovalOutcome {
549    request_id: Option<String>,
550}
551
552async fn request_approval_before_effect(
553    identity: &AutonomyIdentity,
554    action: SideEffectAction,
555    args: &[VmValue],
556) -> Result<ApprovalOutcome, VmError> {
557    active_event_log().ok_or_else(|| {
558        categorized_error(
559            "act_with_approval requires an active event log",
560            ErrorCategory::ToolRejected,
561        )
562    })?;
563    let detail = detail_for(action, args);
564    let approval = crate::stdlib::hitl::request_approval_for_side_effect(
565        action.class,
566        detail,
567        identity.agent_id.clone(),
568        identity.reviewers.clone(),
569        vec![action.capability.to_string()],
570    )
571    .await?;
572    let request_id = approval
573        .as_dict()
574        .and_then(|dict| dict.get("request_id"))
575        .map(VmValue::display);
576    Ok(ApprovalOutcome { request_id })
577}
578
579async fn append_enforcement_record(
580    identity: &AutonomyIdentity,
581    action: SideEffectAction,
582    args: &[VmValue],
583    outcome: TrustOutcome,
584    request_id: Option<String>,
585) -> Result<(), VmError> {
586    let Some(log) = active_event_log() else {
587        return Ok(());
588    };
589    let mut record = TrustRecord::new(
590        identity.agent_id.clone(),
591        action.class.to_string(),
592        None,
593        outcome,
594        identity.trace_id.clone(),
595        identity.tier,
596    );
597    let enforcement = if identity.requires_human {
598        // `needs-human` always denies regardless of tier — record the
599        // distinct enforcement label so audit consumers can filter on it
600        // without re-deriving the discipline from policy snapshots.
601        "needs_human_denied"
602    } else {
603        match identity.tier {
604            AutonomyTier::Shadow => "shadow_noop",
605            AutonomyTier::Suggest => "suggest_approval_request",
606            AutonomyTier::ActWithApproval => "approval_granted",
607            AutonomyTier::ActAuto => "auto",
608        }
609    };
610    record.metadata.insert(
611        "autonomy.enforcement".to_string(),
612        serde_json::json!(enforcement),
613    );
614    record
615        .metadata
616        .insert("builtin".to_string(), serde_json::json!(action.builtin));
617    record
618        .metadata
619        .insert("action_class".to_string(), serde_json::json!(action.class));
620    // Every record carries an explicit autonomy class so the trust-graph
621    // record (`TrustRecord.metadata.autonomy_class`) flows downstream into
622    // approval surfaces and receipt envelopes. `needs-human` is mutually
623    // exclusive with the tier-based labels.
624    let autonomy_class = if identity.requires_human {
625        NEEDS_HUMAN_AUTONOMY_CLASS.to_string()
626    } else {
627        identity.tier.as_str().to_string()
628    };
629    record.metadata.insert(
630        "autonomy_class".to_string(),
631        serde_json::json!(autonomy_class),
632    );
633    record.metadata.insert(
634        "requires_human".to_string(),
635        serde_json::json!(identity.requires_human),
636    );
637    if identity.requires_human {
638        record.metadata.insert(
639            "deny_code".to_string(),
640            serde_json::json!(HARN_AUT_NEEDS_HUMAN_CODE),
641        );
642    }
643    record.metadata.insert(
644        "args".to_string(),
645        serde_json::json!(args
646            .iter()
647            .map(crate::llm::vm_value_to_json)
648            .collect::<Vec<_>>()),
649    );
650    if let Some(request_id) = request_id {
651        record.metadata.insert(
652            "approval_request_id".to_string(),
653            serde_json::json!(request_id),
654        );
655    }
656    append_trust_record(&log, &record)
657        .await
658        .map(|_| ())
659        .map_err(|error| VmError::Runtime(format!("autonomy trust graph append: {error}")))
660}