1use std::time::Instant;
7
8use aios_spec::{
9 ActionType, ActionUrgency, AppTransition, DecisionBackendResult, DecisionRoute, Intent,
10 IntentBatch, IntentType, RiskLevel, SanitizedEventType, SemanticHint, StructuredContext,
11 SuggestedAction,
12};
13
14use crate::{new_id, DecisionBackend};
15
16pub struct RuleBasedBackend;
17
18const MEMORY_PRESSURE_RSS_MB: u32 = 1024;
23const MEMORY_PRESSURE_SWAP_MB: u32 = 128;
26
27impl RuleBasedBackend {
28 fn generate_intents(&self, context: &StructuredContext) -> Vec<Intent> {
30 let mut intents = Vec::new();
31 let summary = &context.summary;
32
33 let mut has_file_mention = false;
34 let mut observed_foreground_apps: Vec<String> = Vec::new();
35 let mut has_screen_on = false;
36 let mut is_low_battery = false;
37 let mut memory_pressure: Option<(u32, Option<String>)> = None;
40 let notified_apps: Vec<String> = summary.notified_apps.clone();
41
42 for event in &context.events {
43 match &event.event_type {
44 SanitizedEventType::Notification { semantic_hints, .. }
45 if semantic_hints.contains(&SemanticHint::FileMention) =>
46 {
47 has_file_mention = true;
48 },
49 SanitizedEventType::AppTransition {
50 package_name,
51 transition: AppTransition::Foreground,
52 ..
53 } if !observed_foreground_apps.contains(package_name) => {
54 observed_foreground_apps.push(package_name.clone());
55 },
56 SanitizedEventType::Screen { state } => {
57 if matches!(state, aios_spec::ScreenState::Interactive) {
58 has_screen_on = true;
59 }
60 },
61 SanitizedEventType::SystemStatus {
62 battery_pct: Some(pct),
63 ..
64 } if *pct < 20 => {
65 is_low_battery = true;
66 },
67 SanitizedEventType::ProcessResource {
68 package_name,
69 vm_rss_mb,
70 vm_swap_mb,
71 ..
72 } if *vm_rss_mb >= MEMORY_PRESSURE_RSS_MB
73 || *vm_swap_mb >= MEMORY_PRESSURE_SWAP_MB =>
74 {
75 let is_worse = memory_pressure
77 .as_ref()
78 .is_none_or(|(rss, _)| *vm_rss_mb > *rss);
79 if is_worse {
80 memory_pressure = Some((*vm_rss_mb, package_name.clone()));
81 }
82 },
83 _ => {},
101 }
102 }
103
104 if has_file_mention {
105 let from_app = notified_apps.first().cloned().unwrap_or_default();
106 intents.push(Intent {
107 intent_id: new_id(),
108 intent_type: IntentType::OpenApp(from_app.clone()),
109 confidence: 0.70,
110 risk_level: RiskLevel::Low,
111 suggested_actions: vec![SuggestedAction {
112 action_type: ActionType::KeepAlive,
113 target: Some(from_app),
114 urgency: ActionUrgency::Immediate,
115 }],
116 rationale_tags: vec!["file_received".into()],
117 });
118 }
119
120 if !has_file_mention {
121 if let Some(app) = notified_apps.first().cloned() {
122 intents.push(Intent {
123 intent_id: new_id(),
124 intent_type: IntentType::OpenApp(app.clone()),
125 confidence: 0.55,
126 risk_level: RiskLevel::Low,
127 suggested_actions: vec![SuggestedAction {
128 action_type: ActionType::KeepAlive,
129 target: Some(app),
130 urgency: ActionUrgency::IdleTime,
131 }],
132 rationale_tags: vec!["notification_engagement".into()],
133 });
134 }
135 }
136
137 if let Some(target) = observed_foreground_apps.first().cloned() {
138 intents.push(Intent {
139 intent_id: new_id(),
140 intent_type: IntentType::SwitchToApp(target.clone()),
141 confidence: 0.80,
142 risk_level: RiskLevel::Low,
143 suggested_actions: vec![SuggestedAction {
144 action_type: ActionType::KeepAlive,
145 target: Some(target),
146 urgency: ActionUrgency::Immediate,
147 }],
148 rationale_tags: vec!["app_foreground_observed".into()],
149 });
150 }
151
152 if has_screen_on {
153 intents.push(Intent {
154 intent_id: new_id(),
155 intent_type: IntentType::Idle,
156 confidence: 0.60,
157 risk_level: RiskLevel::Low,
158 suggested_actions: vec![SuggestedAction {
159 action_type: ActionType::KeepAlive,
160 target: Some("work:collector_heartbeat".into()),
161 urgency: ActionUrgency::IdleTime,
162 }],
163 rationale_tags: vec!["screen_on".into()],
164 });
165 }
166
167 if is_low_battery {
168 intents.push(Intent {
169 intent_id: new_id(),
170 intent_type: IntentType::Idle,
171 confidence: 0.80,
172 risk_level: RiskLevel::Low,
173 suggested_actions: vec![SuggestedAction {
174 action_type: ActionType::ReleaseMemory,
175 target: Some("cache:prefetch".into()),
176 urgency: ActionUrgency::Immediate,
177 }],
178 rationale_tags: vec!["low_battery".into()],
179 });
180 }
181
182 if let Some((_, target)) = memory_pressure {
188 intents.push(Intent {
189 intent_id: new_id(),
190 intent_type: IntentType::Idle,
191 confidence: 0.65,
192 risk_level: RiskLevel::Low,
193 suggested_actions: vec![SuggestedAction {
194 action_type: ActionType::ReleaseMemory,
195 target,
196 urgency: ActionUrgency::Immediate,
197 }],
198 rationale_tags: vec!["memory_pressure".into()],
199 });
200 }
201
202 if intents.is_empty() {
203 intents.push(Intent {
204 intent_id: new_id(),
205 intent_type: IntentType::Idle,
206 confidence: 0.50,
207 risk_level: RiskLevel::Low,
208 suggested_actions: vec![SuggestedAction {
209 action_type: ActionType::NoOp,
210 target: None,
211 urgency: ActionUrgency::IdleTime,
212 }],
213 rationale_tags: vec!["idle_window".into()],
214 });
215 }
216
217 tracing::debug!(
218 window_id = %context.window_id,
219 event_count = context.events.len(),
220 intent_count = intents.len(),
221 "RuleBasedBackend generated intents"
222 );
223
224 intents
225 }
226}
227
228impl DecisionBackend for RuleBasedBackend {
229 fn evaluate(&self, context: &StructuredContext) -> DecisionBackendResult {
230 let start = Instant::now();
231 let intents = self.generate_intents(context);
232 let intent_batch = IntentBatch {
233 window_id: context.window_id.clone(),
234 intents,
235 generated_at_ms: context.window_end_ms,
236 model: "rule-based-v0.3".to_string(),
237 };
238 let rationale_tags = intent_batch
239 .intents
240 .iter()
241 .flat_map(|intent| intent.rationale_tags.iter().cloned())
242 .collect();
243
244 DecisionBackendResult {
245 route: DecisionRoute::RuleBased,
246 intent_batch,
247 rationale_tags,
248 latency_us: start.elapsed().as_micros() as u64,
249 error: None,
250 }
251 }
252}