Skip to main content

aios_core/
policy_engine.rs

1//! 策略引擎 — 校验 LLM 返回的意图是否合法
2//!
3//! 职责:
4//! 1. 检查风险等级是否允许自动执行 (引擎配置 + 后端能力双重)
5//! 2. 检查推荐的 action 是否在白名单内
6//! 3. 检查目标 app 是否可操作(必须在本窗口的上下文中出现过)
7//! 4. 输出逐 action 的裁决 (`PolicyActionDecision`),不再构造 `AuthorizedAction`
8
9use std::collections::BTreeSet;
10
11use aios_spec::governance::{PolicyActionDecision, PolicyVerdict};
12use aios_spec::intent::{
13    ActionType, ActionUrgency, CapabilityLevel, DenialReason, Intent, IntentBatch, RiskLevel,
14};
15use aios_spec::{SanitizedEventType, SourceTier, StructuredContext};
16use tracing::debug;
17
18/// 策略引擎配置
19#[derive(Debug, Clone)]
20pub struct PolicyConfig {
21    /// 允许自动执行的最大风险等级
22    pub max_auto_risk: RiskLevel,
23    /// 禁止的 action 类型 (按 Debug 名称子串匹配)
24    pub blocked_actions: Vec<String>,
25    /// 单次最多执行的动作数
26    pub max_actions_per_batch: usize,
27    /// 置信度下限——低于此值的意图直接拒绝
28    pub min_confidence: f32,
29}
30
31impl Default for PolicyConfig {
32    fn default() -> Self {
33        Self {
34            max_auto_risk: RiskLevel::Low,
35            blocked_actions: vec![],
36            max_actions_per_batch: 5,
37            min_confidence: 0.3,
38        }
39    }
40}
41
42/// 策略引擎
43pub struct PolicyEngine {
44    config: PolicyConfig,
45}
46
47impl PolicyEngine {
48    pub fn new(config: PolicyConfig) -> Self {
49        Self { config }
50    }
51
52    /// 校验整个 IntentBatch, 返回每个建议动作的策略裁决。
53    ///
54    /// 不检查后端能力等级,也不进行 target-not-in-context 检查——
55    /// 用于未指定后端 / 未携带窗口上下文的场景或向后兼容。
56    pub fn evaluate_batch(&self, batch: &IntentBatch) -> Vec<PolicyActionDecision> {
57        let capability = CapabilityLevel::for_route(aios_spec::DecisionRoute::Mock);
58        let mut decisions = Vec::new();
59        for (intent_ordinal, intent) in batch.intents.iter().enumerate() {
60            let intent_ordinal = intent_ordinal as u32;
61            decisions.extend(self.evaluate_intent(
62                intent,
63                intent_ordinal,
64                &capability,
65                None,
66                SourceTier::PublicApi,
67            ));
68        }
69        decisions
70    }
71
72    /// 校验整个 IntentBatch,同时执行后端能力等级检查。
73    pub fn evaluate_batch_with_capability(
74        &self,
75        batch: &IntentBatch,
76        capability: &CapabilityLevel,
77    ) -> Vec<PolicyActionDecision> {
78        let mut decisions = Vec::new();
79        for (intent_ordinal, intent) in batch.intents.iter().enumerate() {
80            let intent_ordinal = intent_ordinal as u32;
81            decisions.extend(self.evaluate_intent(
82                intent,
83                intent_ordinal,
84                capability,
85                None,
86                SourceTier::PublicApi,
87            ));
88        }
89        decisions
90    }
91
92    /// 完整的校验入口:风险 + 能力 + 上下文。
93    ///
94    /// 当上下文 (`ctx`) 提供时,引擎会拒绝任何 `target` 指向未在本窗口
95    /// 出现过的 package/path 的动作。这是封堵 LLM 凭空指定目标的关键门。
96    pub fn evaluate_batch_with_context(
97        &self,
98        batch: &IntentBatch,
99        capability: &CapabilityLevel,
100        ctx: &StructuredContext,
101    ) -> Vec<PolicyActionDecision> {
102        let known = Some(KnownTargets::from_context(ctx));
103        let source_tier = ctx.summary.source_tier;
104        let mut decisions = Vec::new();
105        for (intent_ordinal, intent) in batch.intents.iter().enumerate() {
106            let intent_ordinal = intent_ordinal as u32;
107            decisions.extend(self.evaluate_intent(
108                intent,
109                intent_ordinal,
110                capability,
111                known.as_ref(),
112                source_tier,
113            ));
114        }
115        decisions
116    }
117
118    fn evaluate_intent(
119        &self,
120        intent: &Intent,
121        intent_ordinal: u32,
122        capability: &CapabilityLevel,
123        known: Option<&KnownTargets>,
124        source_tier: SourceTier,
125    ) -> Vec<PolicyActionDecision> {
126        debug!(
127            intent_id = %intent.intent_id,
128            ?source_tier,
129            "policy evaluating intent with source tier"
130        );
131
132        // 1. 后端能力等级检查 — 先于通用策略
133        if !capability.allows_risk(intent.risk_level) {
134            return self.denied_all(
135                intent,
136                intent_ordinal,
137                DenialReason::RiskExceedsCapability,
138                "risk exceeds backend capability",
139            );
140        }
141
142        // 2. 通用风险等级检查
143        if intent.risk_level as u8 > self.config.max_auto_risk as u8 {
144            return self.denied_all(
145                intent,
146                intent_ordinal,
147                DenialReason::RiskExceedsConfig,
148                "risk exceeds engine config",
149            );
150        }
151
152        // 3. 置信度下限
153        if intent.confidence < self.config.min_confidence {
154            return self.denied_all(
155                intent,
156                intent_ordinal,
157                DenialReason::ConfidenceTooLow,
158                "confidence below floor",
159            );
160        }
161
162        // 4. 过滤动作,逐 action 产出裁决
163        let mut decisions = Vec::new();
164        let mut approved_count = 0usize;
165
166        for (action_ordinal, action) in intent.suggested_actions.iter().enumerate() {
167            let action_ordinal = action_ordinal as u32;
168
169            if approved_count >= self.config.max_actions_per_batch {
170                debug!(
171                    intent_id = %intent.intent_id,
172                    reason = ?DenialReason::BatchActionCapExceeded,
173                    "policy denial"
174                );
175                decisions.push(PolicyActionDecision {
176                    intent_ordinal,
177                    action_ordinal,
178                    verdict: PolicyVerdict::Denied(DenialReason::BatchActionCapExceeded),
179                });
180                continue;
181            }
182
183            let action_name = format!("{:?}", action.action_type);
184            if self
185                .config
186                .blocked_actions
187                .iter()
188                .any(|blocked| action_name.contains(blocked))
189            {
190                debug!(
191                    intent_id = %intent.intent_id,
192                    reason = ?DenialReason::ActionTypeBlocked,
193                    action = %action_name,
194                    "policy denial"
195                );
196                decisions.push(PolicyActionDecision {
197                    intent_ordinal,
198                    action_ordinal,
199                    verdict: PolicyVerdict::Denied(DenialReason::ActionTypeBlocked),
200                });
201                continue;
202            }
203
204            if matches!(action.urgency, ActionUrgency::Deferred) {
205                debug!(
206                    intent_id = %intent.intent_id,
207                    reason = ?DenialReason::ActionUrgencyDeferred,
208                    "policy denial"
209                );
210                decisions.push(PolicyActionDecision {
211                    intent_ordinal,
212                    action_ordinal,
213                    verdict: PolicyVerdict::Denied(DenialReason::ActionUrgencyDeferred),
214                });
215                continue;
216            }
217
218            if !capability.allows_action(&action.action_type) {
219                debug!(
220                    intent_id = %intent.intent_id,
221                    reason = ?DenialReason::ActionCapabilityDenied,
222                    action = %action_name,
223                    "policy denial"
224                );
225                decisions.push(PolicyActionDecision {
226                    intent_ordinal,
227                    action_ordinal,
228                    verdict: PolicyVerdict::Denied(DenialReason::ActionCapabilityDenied),
229                });
230                continue;
231            }
232
233            if let Some(k) = known {
234                if let Some(reason) = check_target(&action.action_type, action.target.as_deref(), k)
235                {
236                    debug!(
237                        intent_id = %intent.intent_id,
238                        reason = ?reason,
239                        target = ?action.target,
240                        "policy denial"
241                    );
242                    decisions.push(PolicyActionDecision {
243                        intent_ordinal,
244                        action_ordinal,
245                        verdict: PolicyVerdict::Denied(reason),
246                    });
247                    continue;
248                }
249            }
250
251            approved_count += 1;
252            decisions.push(PolicyActionDecision {
253                intent_ordinal,
254                action_ordinal,
255                verdict: PolicyVerdict::Approved,
256            });
257        }
258
259        decisions
260    }
261
262    fn denied_all(
263        &self,
264        intent: &Intent,
265        intent_ordinal: u32,
266        reason: DenialReason,
267        log_msg: &'static str,
268    ) -> Vec<PolicyActionDecision> {
269        debug!(
270            intent_id = %intent.intent_id,
271            reason = ?reason,
272            "policy denial: {log_msg}"
273        );
274        (0..intent.suggested_actions.len())
275            .map(|action_ordinal| PolicyActionDecision {
276                intent_ordinal,
277                action_ordinal: action_ordinal as u32,
278                verdict: PolicyVerdict::Denied(reason),
279            })
280            .collect()
281    }
282}
283
284impl Default for PolicyEngine {
285    fn default() -> Self {
286        Self::new(PolicyConfig::default())
287    }
288}
289
290/// 检查 (action_type, target) 是否通过 target 校验。返回 Some(reason)
291/// 即拒绝。规则:
292///
293/// - `NoOp` — 不关心 target。
294/// - `PreWarmProcess` — executor 强制要求 target;None 视为 hallucinated。
295/// - `KeepAlive` / `ReleaseMemory` / `PrefetchFile` — None 是合法的"系统/窗口
296///   范围"语义;如果给了 Some(target) 则必须在 KnownTargets 中。
297///
298/// 这一切都是为了拦截 LLM 凭空指定 package:宁可拒绝一条可疑动作,
299/// 也不让从未在窗口里出现过的实体被执行器接受。
300fn check_target(
301    action: &ActionType,
302    target: Option<&str>,
303    known: &KnownTargets,
304) -> Option<DenialReason> {
305    match action {
306        ActionType::NoOp => None,
307        ActionType::PreWarmProcess => match target {
308            Some(t) if is_allowed_prewarm_target(t, known) => None,
309            _ => Some(DenialReason::TargetNotInContext),
310        },
311        ActionType::KeepAlive | ActionType::ReleaseMemory | ActionType::PrefetchFile => {
312            match target {
313                None => None,
314                Some("") => Some(DenialReason::TargetNotInContext),
315                Some(t) if is_allowed_low_risk_target(action, t, known) => None,
316                Some(_) => Some(DenialReason::TargetNotInContext),
317            }
318        },
319    }
320}
321
322fn is_allowed_prewarm_target(target: &str, known: &KnownTargets) -> bool {
323    if target.starts_with("own:") || target.starts_with("notif:") {
324        return true;
325    }
326    if let Some(package) = target.strip_prefix("pkg:") {
327        return known.packages.contains(package);
328    }
329    !target.is_empty() && (known.packages.contains(target) || known.files.contains(target))
330}
331
332fn is_allowed_low_risk_target(action: &ActionType, target: &str, known: &KnownTargets) -> bool {
333    match action {
334        ActionType::KeepAlive if target.starts_with("work:") => true,
335        ActionType::ReleaseMemory if matches!(target, "cache:prefetch" | "cache:all") => true,
336        ActionType::PrefetchFile if target.starts_with("url:") || target.starts_with("uri:") => {
337            true
338        },
339        _ => {
340            if let Some(package) = target.strip_prefix("pkg:") {
341                known.packages.contains(package)
342            } else {
343                known.packages.contains(target) || known.files.contains(target)
344            }
345        },
346    }
347}
348
349/// 一次窗口上下文中"已知"的可操作实体。
350///
351/// 由 [`StructuredContext`] 派生:所有出现在 sanitized 事件里的 package
352/// 名以及 ContextSummary 汇总里的 foreground/notified apps。当前不收集
353/// 具体文件路径(脱敏阶段已经丢弃),但保留 `files` 字段以便未来扩展。
354struct KnownTargets {
355    packages: BTreeSet<String>,
356    files: BTreeSet<String>,
357}
358
359impl KnownTargets {
360    fn from_context(ctx: &StructuredContext) -> Self {
361        let mut packages: BTreeSet<String> = BTreeSet::new();
362        for pkg in &ctx.summary.foreground_apps {
363            packages.insert(pkg.clone());
364        }
365        for pkg in &ctx.summary.notified_apps {
366            packages.insert(pkg.clone());
367        }
368        for event in &ctx.events {
369            if let Some(pkg) = event.app_package.as_ref() {
370                packages.insert(pkg.clone());
371            }
372            match &event.event_type {
373                SanitizedEventType::AppTransition { package_name, .. } => {
374                    packages.insert(package_name.clone());
375                },
376                SanitizedEventType::Notification { source_package, .. } => {
377                    packages.insert(source_package.clone());
378                },
379                SanitizedEventType::ProcessResource {
380                    package_name: Some(p),
381                    ..
382                } => {
383                    packages.insert(p.clone());
384                },
385                _ => {},
386            }
387        }
388        Self {
389            packages,
390            files: BTreeSet::new(),
391        }
392    }
393}