1use 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#[derive(Debug, Clone)]
20pub struct PolicyConfig {
21 pub max_auto_risk: RiskLevel,
23 pub blocked_actions: Vec<String>,
25 pub max_actions_per_batch: usize,
27 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
42pub struct PolicyEngine {
44 config: PolicyConfig,
45}
46
47impl PolicyEngine {
48 pub fn new(config: PolicyConfig) -> Self {
49 Self { config }
50 }
51
52 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 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 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 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 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 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 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
290fn 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
349struct 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}