1use std::collections::HashMap;
10use std::time::Instant;
11
12use aios_spec::{
13 ActionType, ActionUrgency, AppTransition, DecisionBackendResult, DecisionRoute,
14 ExtensionCategory, FeedbackCorrectness, Intent, IntentBatch, IntentType, ModelInput,
15 NetworkType, RecentDecisionRecord, RiskLevel, SanitizedEventType, ScreenState, SemanticHint,
16 StructuredContext, SuggestedAction, UserBehaviorProfile,
17};
18
19use super::prefetch_target::default_prefetch_target;
20use crate::{new_id, DecisionBackend};
21
22pub struct LocalEvaluatorBackend;
23
24const MAX_INTENTS_PER_WINDOW: usize = 5;
25const LOW_BATTERY_THRESHOLD: u8 = 20;
26const STRONG_CORRELATION_WINDOW_MS: i64 = 10_000;
27
28const FILE_BASE_CONFIDENCE: f32 = 0.72;
29const HOT_FILE_BASE_CONFIDENCE: f32 = 0.80;
30const ONGOING_NOTIFICATION_CONFIDENCE: f32 = 0.66;
31const ATTACHMENT_NOTIFICATION_CONFIDENCE: f32 = 0.74;
32const FOREGROUND_TRANSITION_CONFIDENCE: f32 = 0.78;
33const INTER_APP_CONFIDENCE: f32 = 0.80;
34const LOW_BATTERY_CONFIDENCE: f32 = 0.84;
35const IDLE_CONFIDENCE: f32 = 0.60;
36
37const BOOST_HOT_FILE: f32 = 0.06;
38const BOOST_FOREGROUND_NOTIFICATION_APP: f32 = 0.08;
39const BOOST_LINK_ATTACHMENT: f32 = 0.03;
40const BOOST_FOREGROUND_TRANSITION: f32 = 0.04;
41const BOOST_REPEATED_PACKAGE: f32 = 0.04;
42const BOOST_FREQUENT_PACKAGE: f32 = 0.03;
43const BOOST_FILE_NOTIFICATION_STRONG: f32 = 0.06;
44const BOOST_FILE_NOTIFICATION_WEAK: f32 = 0.03;
45const BOOST_RECENT_FOREGROUND: f32 = 0.03;
46
47const PACKAGE_BOOST_CAP: f32 = 0.08;
48const BEHAVIOR_BOOST_CAP: f32 = 0.05;
49const CORRELATION_BOOST_CAP: f32 = 0.08;
50
51const PENALTY_LOW_BATTERY: f32 = -0.18;
52const PENALTY_CELLULAR: f32 = -0.06;
53const PENALTY_OFFLINE: f32 = -0.20;
54const PENALTY_SCREEN_NONINTERACTIVE: f32 = -0.12;
55const PENALTY_RECENT_POLICY_REJECTED: f32 = -0.12;
56const PENALTY_RECENT_EXECUTION_FAILED: f32 = -0.08;
57
58impl LocalEvaluatorBackend {
59 fn evaluate_intents(&self, input: EvaluationInput<'_>) -> Vec<Intent> {
60 let context = input.context;
61 let signals = WindowSignals::from_context(context);
62 let aggregation =
63 WindowAggregation::from_context(context, input.behavior_profile, input.recent_feedback);
64 let mut candidates = Vec::new();
65
66 for event in &context.events {
67 match &event.event_type {
68 SanitizedEventType::FileActivity {
69 package_name,
70 extension_category,
71 is_hot_file,
72 ..
73 } => {
74 let mut score = Score::new(if *is_hot_file {
75 HOT_FILE_BASE_CONFIDENCE
76 } else {
77 FILE_BASE_CONFIDENCE
78 });
79 if *is_hot_file {
80 score.add(BOOST_HOT_FILE, "local:boost:hot_file");
81 }
82 aggregation.apply_package_boost(package_name.as_deref(), &mut score);
83 aggregation.apply_file_notification_boost(
84 package_name.as_deref(),
85 event.timestamp_ms,
86 &mut score,
87 );
88 score.apply_window(&signals, false);
89 let actions = vec![SuggestedAction {
90 action_type: ActionType::PrefetchFile,
91 target: Some(default_prefetch_target(
92 extension_category,
93 package_name.as_deref(),
94 )),
95 urgency: ActionUrgency::IdleTime,
96 }];
97 aggregation.apply_action_feedback(&actions, &mut score);
98
99 candidates.push(IntentCandidate::new(
100 IntentType::HandleFile(extension_category.clone()),
101 score,
102 actions,
103 vec![
104 "local:file_activity".into(),
105 format!("local:extension:{extension_category:?}"),
106 ],
107 ));
108 },
109 SanitizedEventType::Notification {
110 source_package,
111 semantic_hints,
112 is_ongoing,
113 ..
114 } if semantic_hints.contains(&SemanticHint::FileMention)
115 || semantic_hints.contains(&SemanticHint::ImageMention)
116 || semantic_hints.contains(&SemanticHint::LinkAttachment) =>
117 {
118 let mut score = Score::new(if *is_ongoing {
119 ONGOING_NOTIFICATION_CONFIDENCE
120 } else {
121 ATTACHMENT_NOTIFICATION_CONFIDENCE
122 });
123 if signals.foreground_apps.contains(source_package) {
124 score.add(
125 BOOST_FOREGROUND_NOTIFICATION_APP,
126 "local:boost:foreground_notification_app",
127 );
128 }
129 if semantic_hints.contains(&SemanticHint::LinkAttachment) {
130 score.add(BOOST_LINK_ATTACHMENT, "local:boost:link_attachment");
131 }
132 aggregation.apply_package_boost(Some(source_package), &mut score);
133 aggregation.apply_notification_file_boost(
134 source_package,
135 event.timestamp_ms,
136 &mut score,
137 );
138 score.apply_window(&signals, true);
139 let actions = vec![SuggestedAction {
140 action_type: ActionType::PreWarmProcess,
141 target: Some(format!("pkg:{source_package}")),
142 urgency: ActionUrgency::Immediate,
143 }];
144 aggregation.apply_action_feedback(&actions, &mut score);
145
146 candidates.push(IntentCandidate::new(
147 IntentType::OpenApp(source_package.clone()),
148 score,
149 actions,
150 vec!["local:attachment_notification".into()],
151 ));
152 },
153 SanitizedEventType::AppTransition {
154 package_name,
155 transition: AppTransition::Foreground,
156 ..
157 } => {
158 let mut score = Score::new(FOREGROUND_TRANSITION_CONFIDENCE);
159 score.add(BOOST_FOREGROUND_TRANSITION, "local:boost:foreground");
160 aggregation.apply_package_boost(Some(package_name), &mut score);
161 if aggregation.is_recent_foreground(package_name) {
162 score.add_grouped(
163 BoostGroup::Package,
164 BOOST_RECENT_FOREGROUND,
165 "local:boost:recent_foreground",
166 );
167 }
168 score.apply_window(&signals, true);
169 let actions = vec![
170 SuggestedAction {
171 action_type: ActionType::PreWarmProcess,
172 target: Some(format!("pkg:{package_name}")),
173 urgency: ActionUrgency::Immediate,
174 },
175 SuggestedAction {
176 action_type: ActionType::KeepAlive,
177 target: Some("work:collector_heartbeat".into()),
178 urgency: ActionUrgency::Immediate,
179 },
180 ];
181 aggregation.apply_action_feedback(&actions, &mut score);
182
183 candidates.push(IntentCandidate::new(
184 IntentType::SwitchToApp(package_name.clone()),
185 score,
186 actions,
187 vec!["local:foreground_transition".into()],
188 ));
189 },
190 SanitizedEventType::InterAppInteraction {
191 interaction_type:
192 aios_spec::InteractionType::ActivityLaunch
193 | aios_spec::InteractionType::ShareIntent,
194 ..
195 } => {
196 let mut score = Score::new(INTER_APP_CONFIDENCE);
197 score.apply_window(&signals, false);
198 let actions = vec![SuggestedAction {
199 action_type: ActionType::PreWarmProcess,
200 target: Some("own:resources".into()),
201 urgency: ActionUrgency::Immediate,
202 }];
203 aggregation.apply_action_feedback(&actions, &mut score);
204
205 candidates.push(IntentCandidate::new(
206 IntentType::EnterContext("inter_app_interaction".into()),
207 score,
208 actions,
209 vec!["local:inter_app_interaction".into()],
210 ));
211 },
212 _ => {},
213 }
214 }
215
216 if signals.low_battery && !signals.charging {
217 let actions = vec![SuggestedAction {
218 action_type: ActionType::ReleaseMemory,
219 target: Some("cache:prefetch".into()),
220 urgency: ActionUrgency::Immediate,
221 }];
222 let mut score = Score::with_tags(
223 LOW_BATTERY_CONFIDENCE,
224 vec!["local:signal:low_battery".into()],
225 );
226 aggregation.apply_action_feedback(&actions, &mut score);
227 candidates.push(IntentCandidate::new(
228 IntentType::Idle,
229 score,
230 actions,
231 vec!["local:low_battery".into()],
232 ));
233 }
234
235 let mut intents = finalize_candidates(candidates, &signals, MAX_INTENTS_PER_WINDOW);
236
237 if intents.is_empty() {
238 intents.push(Intent {
239 intent_id: new_id(),
240 intent_type: IntentType::Idle,
241 confidence: IDLE_CONFIDENCE,
242 risk_level: RiskLevel::Low,
243 suggested_actions: vec![SuggestedAction {
244 action_type: ActionType::NoOp,
245 target: None,
246 urgency: ActionUrgency::IdleTime,
247 }],
248 rationale_tags: vec!["local:idle_window".into()],
249 });
250 }
251
252 intents
253 }
254}
255
256struct EvaluationInput<'a> {
257 context: &'a StructuredContext,
258 behavior_profile: Option<&'a UserBehaviorProfile>,
259 recent_feedback: &'a [RecentDecisionRecord],
260}
261
262#[derive(Debug, Default)]
263struct WindowAggregation {
264 package_counts: HashMap<String, u32>,
265 notification_counts: HashMap<String, u32>,
266 file_package_counts: HashMap<String, u32>,
267 notification_timestamps: HashMap<String, Vec<i64>>,
268 file_timestamps: HashMap<String, Vec<i64>>,
269 recent_foreground_app: Option<String>,
270 frequent_foreground_apps: HashMap<String, u32>,
271 frequent_notifying_apps: HashMap<String, u32>,
272 recent_policy_rejections: HashMap<String, u32>,
273 recent_execution_failures: HashMap<String, u32>,
274}
275
276impl WindowAggregation {
277 fn from_context(
278 context: &StructuredContext,
279 behavior_profile: Option<&UserBehaviorProfile>,
280 recent_feedback: &[RecentDecisionRecord],
281 ) -> Self {
282 let mut aggregation = Self::default();
283 let mut recent_foreground: Option<(i64, String)> = None;
284
285 for event in &context.events {
286 match &event.event_type {
287 SanitizedEventType::AppTransition {
288 package_name,
289 transition: AppTransition::Foreground,
290 ..
291 } => {
292 increment_count(&mut aggregation.package_counts, package_name);
293 if recent_foreground
294 .as_ref()
295 .is_none_or(|(timestamp_ms, _)| event.timestamp_ms >= *timestamp_ms)
296 {
297 recent_foreground = Some((event.timestamp_ms, package_name.clone()));
298 }
299 },
300 SanitizedEventType::ProcessResource { .. } => {},
301 SanitizedEventType::Notification { source_package, .. } => {
302 increment_count(&mut aggregation.package_counts, source_package);
303 increment_count(&mut aggregation.notification_counts, source_package);
304 push_timestamp(
305 &mut aggregation.notification_timestamps,
306 source_package,
307 event.timestamp_ms,
308 );
309 },
310 SanitizedEventType::FileActivity {
311 package_name: Some(pkg),
312 ..
313 } => {
314 increment_count(&mut aggregation.package_counts, pkg);
315 increment_count(&mut aggregation.file_package_counts, pkg);
316 push_timestamp(&mut aggregation.file_timestamps, pkg, event.timestamp_ms);
317 },
318 SanitizedEventType::InterAppInteraction {
319 source_package: Some(pkg),
320 ..
321 } => {
322 increment_count(&mut aggregation.package_counts, pkg);
323 },
324 _ => {},
325 }
326 }
327
328 aggregation.recent_foreground_app = recent_foreground.map(|(_, package)| package);
329
330 if let Some(profile) = behavior_profile {
331 for (package, count) in &profile.frequent_foreground_apps {
332 aggregation
333 .frequent_foreground_apps
334 .insert(package.clone(), *count);
335 }
336 for (package, count) in &profile.frequent_notifying_apps {
337 aggregation
338 .frequent_notifying_apps
339 .insert(package.clone(), *count);
340 }
341 }
342
343 for record in recent_feedback {
344 for action in &record.action_outcomes {
345 let key = feedback_action_key(&action.action_type, action.target.as_deref());
346 if matches!(action.correctness, FeedbackCorrectness::PolicyRejected)
347 || action.terminal.contains("Denied")
348 || action.denial_reason.is_some()
349 {
350 increment_count(&mut aggregation.recent_policy_rejections, &key);
351 }
352 if matches!(action.correctness, FeedbackCorrectness::ExecutionFailed)
353 || action.terminal.contains("Failed")
354 || action.error.is_some()
355 {
356 increment_count(&mut aggregation.recent_execution_failures, &key);
357 }
358 }
359 }
360
361 aggregation
362 }
363
364 fn apply_package_boost(&self, package: Option<&str>, score: &mut Score) {
365 let Some(package) = package else {
366 return;
367 };
368
369 if self.package_counts.get(package).copied().unwrap_or(0) >= 2 {
370 score.add_grouped(
371 BoostGroup::Package,
372 BOOST_REPEATED_PACKAGE,
373 "local:boost:repeated_package_in_window",
374 );
375 }
376 if self.frequent_foreground_apps.contains_key(package) {
377 score.add_grouped(
378 BoostGroup::Behavior,
379 BOOST_FREQUENT_PACKAGE,
380 "local:boost:frequent_foreground_app",
381 );
382 }
383 if self.frequent_notifying_apps.contains_key(package) {
384 score.add_grouped(
385 BoostGroup::Behavior,
386 BOOST_FREQUENT_PACKAGE,
387 "local:boost:frequent_notifying_app",
388 );
389 }
390 }
391
392 fn apply_file_notification_boost(
393 &self,
394 package: Option<&str>,
395 file_timestamp_ms: i64,
396 score: &mut Score,
397 ) {
398 let Some(package) = package else {
399 return;
400 };
401
402 match nearest_delta_ms(
403 self.notification_timestamps.get(package).map(Vec::as_slice),
404 file_timestamp_ms,
405 ) {
406 Some(delta) if delta <= STRONG_CORRELATION_WINDOW_MS => score.add_grouped(
407 BoostGroup::Correlation,
408 BOOST_FILE_NOTIFICATION_STRONG,
409 "local:boost:file_notification_same_package_strong",
410 ),
411 Some(_) => score.add_grouped(
412 BoostGroup::Correlation,
413 BOOST_FILE_NOTIFICATION_WEAK,
414 "local:boost:file_notification_same_package_weak",
415 ),
416 None => {},
417 }
418 }
419
420 fn apply_notification_file_boost(
421 &self,
422 package: &str,
423 notification_timestamp_ms: i64,
424 score: &mut Score,
425 ) {
426 match nearest_delta_ms(
427 self.file_timestamps.get(package).map(Vec::as_slice),
428 notification_timestamp_ms,
429 ) {
430 Some(delta) if delta <= STRONG_CORRELATION_WINDOW_MS => score.add_grouped(
431 BoostGroup::Correlation,
432 BOOST_FILE_NOTIFICATION_STRONG,
433 "local:boost:notification_file_activity_link_strong",
434 ),
435 Some(_) => score.add_grouped(
436 BoostGroup::Correlation,
437 BOOST_FILE_NOTIFICATION_WEAK,
438 "local:boost:notification_file_activity_link_weak",
439 ),
440 None => {},
441 }
442 }
443
444 fn is_recent_foreground(&self, package: &str) -> bool {
445 self.recent_foreground_app.as_deref() == Some(package)
446 }
447
448 fn apply_action_feedback(&self, actions: &[SuggestedAction], score: &mut Score) {
449 for action in actions {
450 let key = feedback_action_key(
451 action_type_name(&action.action_type),
452 action.target.as_deref(),
453 );
454 if self.recent_policy_rejections.contains_key(&key) {
455 score.add(
456 PENALTY_RECENT_POLICY_REJECTED,
457 "local:penalty:recent_policy_rejected",
458 );
459 }
460 if self.recent_execution_failures.contains_key(&key) {
461 score.add(
462 PENALTY_RECENT_EXECUTION_FAILED,
463 "local:penalty:recent_execution_failed",
464 );
465 }
466 }
467 }
468}
469
470fn increment_count(counts: &mut HashMap<String, u32>, key: &str) {
471 *counts.entry(key.to_string()).or_insert(0) += 1;
472}
473
474fn push_timestamp(timestamps: &mut HashMap<String, Vec<i64>>, key: &str, timestamp_ms: i64) {
475 timestamps
476 .entry(key.to_string())
477 .or_default()
478 .push(timestamp_ms);
479}
480
481fn nearest_delta_ms(timestamps: Option<&[i64]>, timestamp_ms: i64) -> Option<i64> {
482 timestamps?
483 .iter()
484 .map(|other| timestamp_ms.saturating_sub(*other).abs())
485 .min()
486}
487
488fn feedback_action_key(action_type: &str, target: Option<&str>) -> String {
489 format!("{}:{}", action_type, target.unwrap_or(""))
490}
491
492fn action_type_name(action_type: &ActionType) -> &'static str {
493 match action_type {
494 ActionType::PrefetchFile => "PrefetchFile",
495 ActionType::PreWarmProcess => "PreWarmProcess",
496 ActionType::KeepAlive => "KeepAlive",
497 ActionType::ReleaseMemory => "ReleaseMemory",
498 ActionType::NoOp => "NoOp",
499 }
500}
501
502#[derive(Debug, Default)]
503struct WindowSignals {
504 foreground_apps: Vec<String>,
505 low_battery: bool,
506 charging: bool,
507 cellular: bool,
508 offline: bool,
509 screen_noninteractive: bool,
510}
511
512impl WindowSignals {
513 fn from_context(context: &StructuredContext) -> Self {
514 let mut signals = Self {
515 foreground_apps: context.summary.foreground_apps.clone(),
516 ..Self::default()
517 };
518
519 if let Some(status) = &context.summary.latest_system_status {
520 signals.low_battery = status
521 .battery_pct
522 .is_some_and(|pct| pct < LOW_BATTERY_THRESHOLD);
523 signals.charging = status.is_charging;
524 signals.cellular = matches!(status.network, NetworkType::Cellular);
525 signals.offline = matches!(status.network, NetworkType::Offline);
526 }
527
528 for event in &context.events {
529 match &event.event_type {
530 SanitizedEventType::SystemStatus {
531 battery_pct,
532 is_charging,
533 network,
534 ..
535 } => {
536 signals.low_battery |=
537 battery_pct.is_some_and(|pct| pct < LOW_BATTERY_THRESHOLD);
538 signals.charging |= *is_charging;
539 signals.cellular |= matches!(network, NetworkType::Cellular);
540 signals.offline |= matches!(network, NetworkType::Offline);
541 },
542 SanitizedEventType::Screen {
543 state:
544 ScreenState::NonInteractive
545 | ScreenState::KeyguardShown
546 | ScreenState::KeyguardHidden,
547 } => {
548 signals.screen_noninteractive = true;
549 },
550 _ => {},
551 }
552 }
553
554 signals
555 }
556}
557
558struct Score {
559 value: f32,
560 tags: Vec<String>,
561 package_boost: f32,
562 behavior_boost: f32,
563 correlation_boost: f32,
564}
565
566impl Score {
567 fn new(value: f32) -> Self {
568 Self {
569 value,
570 tags: Vec::new(),
571 package_boost: 0.0,
572 behavior_boost: 0.0,
573 correlation_boost: 0.0,
574 }
575 }
576
577 fn with_tags(value: f32, tags: Vec<String>) -> Self {
578 Self {
579 value,
580 tags,
581 package_boost: 0.0,
582 behavior_boost: 0.0,
583 correlation_boost: 0.0,
584 }
585 }
586
587 fn add(&mut self, delta: f32, tag: &str) {
588 self.value += delta;
589 self.tags.push(tag.into());
590 }
591
592 fn add_grouped(&mut self, group: BoostGroup, delta: f32, tag: &str) {
593 let remaining = match group {
594 BoostGroup::Package => PACKAGE_BOOST_CAP - self.package_boost,
595 BoostGroup::Behavior => BEHAVIOR_BOOST_CAP - self.behavior_boost,
596 BoostGroup::Correlation => CORRELATION_BOOST_CAP - self.correlation_boost,
597 };
598 let applied = delta.min(remaining.max(0.0));
599 if applied <= 0.0 {
600 self.tags.push(format!("{tag}:capped"));
601 return;
602 }
603
604 self.value += applied;
605 match group {
606 BoostGroup::Package => self.package_boost += applied,
607 BoostGroup::Behavior => self.behavior_boost += applied,
608 BoostGroup::Correlation => self.correlation_boost += applied,
609 }
610 self.tags.push(tag.into());
611 }
612
613 fn apply_window(&mut self, signals: &WindowSignals, user_visible_hint: bool) {
614 if signals.low_battery && !signals.charging {
615 self.add(PENALTY_LOW_BATTERY, "local:penalty:low_battery");
616 }
617 if signals.cellular {
618 self.add(PENALTY_CELLULAR, "local:penalty:cellular_network");
619 }
620 if signals.offline {
621 self.add(PENALTY_OFFLINE, "local:penalty:offline");
622 }
623 if signals.screen_noninteractive && user_visible_hint {
624 self.add(
625 PENALTY_SCREEN_NONINTERACTIVE,
626 "local:penalty:screen_noninteractive",
627 );
628 }
629 self.value = self.value.clamp(0.0, 0.99);
630 }
631}
632
633#[derive(Clone, Copy)]
634enum BoostGroup {
635 Package,
636 Behavior,
637 Correlation,
638}
639
640struct IntentCandidate {
641 intent_type: IntentType,
642 confidence: f32,
643 actions: Vec<SuggestedAction>,
644 tags: Vec<String>,
645}
646
647impl IntentCandidate {
648 fn new(
649 intent_type: IntentType,
650 score: Score,
651 actions: Vec<SuggestedAction>,
652 mut tags: Vec<String>,
653 ) -> Self {
654 tags.extend(score.tags);
655 Self {
656 intent_type,
657 confidence: score.value,
658 actions,
659 tags,
660 }
661 }
662}
663
664fn finalize_candidates(
665 mut candidates: Vec<IntentCandidate>,
666 signals: &WindowSignals,
667 max_intents: usize,
668) -> Vec<Intent> {
669 for candidate in &mut candidates {
670 let original_len = candidate.actions.len();
671 candidate
672 .actions
673 .retain(|action| is_policy_aware_action(action, signals));
674 if candidate.actions.len() < original_len {
675 candidate
676 .tags
677 .push("local:suppress:policy_aware_filter".into());
678 }
679 }
680
681 candidates.retain(|candidate| !candidate.actions.is_empty());
682
683 let mut deduped: HashMap<String, IntentCandidate> = HashMap::new();
684 for candidate in candidates {
685 let key = candidate_key(&candidate);
686 match deduped.get_mut(&key) {
687 Some(existing) if existing.confidence >= candidate.confidence => {
688 merge_tags(&mut existing.tags, candidate.tags);
689 },
690 Some(existing) => {
691 let mut replacement = candidate;
692 merge_tags(&mut replacement.tags, existing.tags.clone());
693 *existing = replacement;
694 },
695 None => {
696 deduped.insert(key, candidate);
697 },
698 }
699 }
700
701 let mut candidates: Vec<_> = deduped.into_values().collect();
702 candidates.sort_by(|a, b| {
703 b.confidence
704 .partial_cmp(&a.confidence)
705 .unwrap_or(std::cmp::Ordering::Equal)
706 .then_with(|| candidate_key(a).cmp(&candidate_key(b)))
707 });
708
709 candidates
710 .into_iter()
711 .take(max_intents)
712 .map(|candidate| Intent {
713 intent_id: new_id(),
714 intent_type: candidate.intent_type,
715 confidence: candidate.confidence,
716 risk_level: RiskLevel::Low,
717 suggested_actions: candidate.actions,
718 rationale_tags: candidate.tags,
719 })
720 .collect()
721}
722
723fn is_policy_aware_action(action: &SuggestedAction, signals: &WindowSignals) -> bool {
724 match action.action_type {
725 ActionType::PrefetchFile => {
726 (!signals.low_battery || signals.charging)
727 && !signals.offline
728 && action
729 .target
730 .as_deref()
731 .is_some_and(is_safe_prefetch_target)
732 },
733 ActionType::PreWarmProcess => action
734 .target
735 .as_deref()
736 .is_some_and(|target| is_safe_prewarm_target(target, signals)),
737 ActionType::KeepAlive => action
738 .target
739 .as_deref()
740 .is_none_or(|target| target.starts_with("work:")),
741 ActionType::ReleaseMemory => action
742 .target
743 .as_deref()
744 .is_none_or(|target| matches!(target, "cache:prefetch" | "cache:all")),
745 ActionType::NoOp => action.target.is_none(),
746 }
747}
748
749fn is_safe_prefetch_target(target: &str) -> bool {
750 target.starts_with("url:https://") || target.starts_with("uri:content://")
751}
752
753fn is_safe_prewarm_target(target: &str, signals: &WindowSignals) -> bool {
754 if signals.screen_noninteractive && (target.starts_with("pkg:") || target.starts_with("notif:"))
755 {
756 return false;
757 }
758
759 target.starts_with("own:")
760 || target.starts_with("notif:")
761 || target
762 .strip_prefix("pkg:")
763 .is_some_and(super::prefetch_target::looks_like_package_name)
764}
765
766fn candidate_key(candidate: &IntentCandidate) -> String {
767 let mut parts = vec![intent_key(&candidate.intent_type)];
768 for action in &candidate.actions {
769 let action_type = &action.action_type;
770 let target = action.target.as_deref().unwrap_or("");
771 parts.push(format!("{action_type:?}:{target}"));
772 }
773 parts.join("|")
774}
775
776fn intent_key(intent_type: &IntentType) -> String {
777 match intent_type {
778 IntentType::OpenApp(pkg) => format!("open:{pkg}"),
779 IntentType::SwitchToApp(pkg) => format!("switch:{pkg}"),
780 IntentType::CheckNotification(pkg) => format!("notify:{pkg}"),
781 IntentType::HandleFile(ext) => format!("file:{}", extension_key(ext)),
782 IntentType::EnterContext(ctx) => format!("context:{ctx}"),
783 IntentType::Idle => "idle".into(),
784 }
785}
786
787fn extension_key(ext: &ExtensionCategory) -> &'static str {
788 match ext {
789 ExtensionCategory::Document => "document",
790 ExtensionCategory::Image => "image",
791 ExtensionCategory::Video => "video",
792 ExtensionCategory::Audio => "audio",
793 ExtensionCategory::Archive => "archive",
794 ExtensionCategory::Code => "code",
795 ExtensionCategory::Other => "other",
796 ExtensionCategory::Unknown => "unknown",
797 }
798}
799
800fn merge_tags(target: &mut Vec<String>, source: Vec<String>) {
801 for tag in source {
802 if !target.contains(&tag) {
803 target.push(tag);
804 }
805 }
806}
807
808impl DecisionBackend for LocalEvaluatorBackend {
809 fn evaluate(&self, context: &StructuredContext) -> DecisionBackendResult {
810 self.evaluate_input(EvaluationInput {
811 context,
812 behavior_profile: None,
813 recent_feedback: &[],
814 })
815 }
816
817 fn evaluate_model_input(&self, input: &ModelInput) -> DecisionBackendResult {
818 self.evaluate_input(EvaluationInput {
819 context: &input.current_context,
820 behavior_profile: Some(&input.behavior_profile),
821 recent_feedback: &input.recent_feedback,
822 })
823 }
824}
825
826impl LocalEvaluatorBackend {
827 fn evaluate_input(&self, input: EvaluationInput<'_>) -> DecisionBackendResult {
828 let start = Instant::now();
829 let context = input.context;
830 let intents = self.evaluate_intents(input);
831 let intent_batch = IntentBatch {
832 window_id: context.window_id.clone(),
833 intents,
834 generated_at_ms: context.window_end_ms,
835 model: "local-evaluator-v0.1".into(),
836 };
837 let rationale_tags = intent_batch
838 .intents
839 .iter()
840 .flat_map(|intent| intent.rationale_tags.iter().cloned())
841 .collect();
842
843 DecisionBackendResult {
844 route: DecisionRoute::LocalEvaluator,
845 intent_batch,
846 rationale_tags,
847 latency_us: start.elapsed().as_micros() as u64,
848 error: None,
849 }
850 }
851}