Skip to main content

aios_agent/backends/predictive/
backend.rs

1//! PredictiveLocalBackend: DecisionBackend implementation for next-app prediction.
2
3use std::collections::BTreeSet;
4use std::time::Instant;
5
6use aios_spec::{
7    ActionType, ActionUrgency, AppTransition, DecisionBackendResult, DecisionRoute, Intent,
8    IntentBatch, IntentType, ModelInput, RiskLevel, SanitizedEventType, StructuredContext,
9    SuggestedAction,
10};
11
12use super::{
13    hour_bucket, weekday, NextAppAlgorithm, NextAppModelArtifact, NextAppPredictor,
14    PredictionFeatures, MAX_BACKEND_INTENTS, MODEL_NAME,
15};
16use crate::DecisionBackend;
17
18pub struct PredictiveLocalBackend {
19    predictor: NextAppPredictor,
20}
21
22const POLICY_CONFIDENCE_FLOOR: f32 = 0.30;
23
24impl PredictiveLocalBackend {
25    pub fn new(artifact: NextAppModelArtifact) -> Result<Self, String> {
26        Ok(Self {
27            predictor: NextAppPredictor::new(artifact)?,
28        })
29    }
30
31    pub fn from_path(path: impl AsRef<std::path::Path>) -> Result<Self, String> {
32        Ok(Self {
33            predictor: NextAppPredictor::from_path(path)?,
34        })
35    }
36}
37
38impl DecisionBackend for PredictiveLocalBackend {
39    fn evaluate(&self, context: &StructuredContext) -> DecisionBackendResult {
40        let input = ModelInput::current_only(context.clone());
41        self.evaluate_model_input(&input)
42    }
43
44    fn evaluate_model_input(&self, input: &ModelInput) -> DecisionBackendResult {
45        let start = Instant::now();
46        let features = features_from_model_input(input);
47        let known = known_packages(&input.current_context);
48        let predictions =
49            self.predictor
50                .rank(&features, NextAppAlgorithm::Ensemble, MAX_BACKEND_INTENTS);
51
52        let mut intents: Vec<Intent> = predictions
53            .into_iter()
54            .map(|prediction| prediction_to_intent(&prediction, &known))
55            .collect();
56
57        if intents.is_empty() {
58            intents.push(Intent {
59                intent_id: crate::new_id(),
60                intent_type: IntentType::Idle,
61                confidence: 0.50,
62                risk_level: RiskLevel::Low,
63                suggested_actions: vec![SuggestedAction {
64                    action_type: ActionType::NoOp,
65                    target: None,
66                    urgency: ActionUrgency::IdleTime,
67                }],
68                rationale_tags: vec!["predictive:idle_no_prediction".into()],
69            });
70        }
71
72        let intent_batch = IntentBatch {
73            window_id: input.current_context.window_id.clone(),
74            intents,
75            generated_at_ms: input.current_context.window_end_ms,
76            model: MODEL_NAME.into(),
77        };
78        let rationale_tags = intent_batch
79            .intents
80            .iter()
81            .flat_map(|intent| intent.rationale_tags.iter().cloned())
82            .collect();
83
84        DecisionBackendResult {
85            route: DecisionRoute::LocalEvaluator,
86            intent_batch,
87            rationale_tags,
88            latency_us: start.elapsed().as_micros() as u64,
89            error: None,
90        }
91    }
92}
93
94pub(crate) fn features_from_model_input(input: &ModelInput) -> PredictionFeatures {
95    let context = &input.current_context;
96    let current_app =
97        latest_foreground_app(context).or_else(|| context.summary.foreground_apps.last().cloned());
98    let mut history: Vec<String> = input
99        .recent_feedback
100        .iter()
101        .rev()
102        .flat_map(|record| record.foreground_apps.iter().rev().cloned())
103        .take(5)
104        .collect();
105    history.reverse();
106    let event_type = context.events.last().map(|event| {
107        match &event.event_type {
108            SanitizedEventType::AppTransition { .. } => "app_transition",
109            SanitizedEventType::Notification { .. } => "notification",
110            SanitizedEventType::FileActivity { .. } => "file_activity",
111            SanitizedEventType::Screen { .. } => "screen",
112            SanitizedEventType::SystemStatus { .. } => "system_status",
113            SanitizedEventType::ProcessResource { .. } => "process_resource",
114            SanitizedEventType::InterAppInteraction { .. } => "inter_app",
115        }
116        .to_string()
117    });
118    PredictionFeatures {
119        user_id: input.behavior_profile.user_id.clone(),
120        current_app,
121        history,
122        hour_bucket: Some(hour_bucket(context.window_end_ms)),
123        weekday: Some(weekday(context.window_end_ms)),
124        event_type,
125    }
126}
127
128fn latest_foreground_app(context: &StructuredContext) -> Option<String> {
129    context
130        .events
131        .iter()
132        .rev()
133        .find_map(|event| match &event.event_type {
134            SanitizedEventType::AppTransition {
135                package_name,
136                transition: AppTransition::Foreground,
137                ..
138            } => Some(package_name.clone()),
139            _ => None,
140        })
141}
142
143fn known_packages(context: &StructuredContext) -> BTreeSet<String> {
144    let mut packages = BTreeSet::new();
145    packages.extend(context.summary.foreground_apps.iter().cloned());
146    packages.extend(context.summary.notified_apps.iter().cloned());
147    for event in &context.events {
148        if let Some(pkg) = &event.app_package {
149            packages.insert(pkg.clone());
150        }
151        match &event.event_type {
152            SanitizedEventType::AppTransition { package_name, .. } => {
153                packages.insert(package_name.clone());
154            },
155            SanitizedEventType::Notification { source_package, .. } => {
156                packages.insert(source_package.clone());
157            },
158            SanitizedEventType::ProcessResource {
159                package_name: Some(package),
160                ..
161            } => {
162                packages.insert(package.clone());
163            },
164            _ => {},
165        }
166    }
167    packages
168}
169
170/// Map a scored prediction to a policy-safe intent.
171///
172/// - If the target app is currently in context (foreground/notified/process),
173///   we emit `SwitchToApp` with a `PreWarmProcess` action and `Low` risk.
174/// - If the target is not currently observed, we emit `OpenApp` with a
175///   conservative `KeepAlive` heartbeat action and `Low` risk. The
176///   `OpenApp` intent type honestly reflects "we may want to open this app"
177///   while the `KeepAlive` action prevents the executor from launching
178///   something that is not on the device.
179fn prediction_to_intent(prediction: &super::AppScore, known: &BTreeSet<String>) -> Intent {
180    let in_context = known.contains(&prediction.app);
181    let (intent_type, action_type, target, risk_level) = if in_context {
182        (
183            IntentType::SwitchToApp(prediction.app.clone()),
184            ActionType::PreWarmProcess,
185            Some(format!("pkg:{}", prediction.app)),
186            RiskLevel::Low,
187        )
188    } else {
189        (
190            IntentType::OpenApp(prediction.app.clone()),
191            ActionType::KeepAlive,
192            Some("work:collector_heartbeat".to_string()),
193            RiskLevel::Low,
194        )
195    };
196    Intent {
197        intent_id: crate::new_id(),
198        intent_type,
199        confidence: prediction.score.clamp(POLICY_CONFIDENCE_FLOOR, 0.99),
200        risk_level,
201        suggested_actions: vec![SuggestedAction {
202            action_type,
203            target,
204            urgency: ActionUrgency::Immediate,
205        }],
206        rationale_tags: vec![
207            "predictive:next_app".into(),
208            if in_context {
209                "predictive:target_in_context".into()
210            } else {
211                "predictive:target_not_in_context_safe_keepalive".into()
212            },
213        ],
214    }
215}