1use serde::{Deserialize, Serialize};
2
3pub const DEFAULT_PROJECT_ID: &str = "default";
4
5#[derive(Debug, Clone)]
7pub struct GoalTokenBudgetStatus {
8 #[allow(dead_code)] pub budget_per_check: Option<i64>,
10 pub budget_daily: Option<i64>,
11 pub tokens_used_today: i64,
12}
13
14#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
16pub struct ScheduledRunHealth {
17 pub evidence_gain_count: usize,
18 pub total_successful_tool_calls: usize,
19 #[serde(default)]
21 pub completion_requires_mutation: bool,
22 #[serde(default)]
24 pub required_mutation_progress: bool,
25 #[serde(default)]
27 pub completion_requires_observation: bool,
28 #[serde(default)]
30 pub verification_progress: bool,
31 pub stall_count: usize,
32 pub consecutive_same_tool_count: usize,
33 pub consecutive_same_tool_unique_args: usize,
34 pub unrecovered_error_count: usize,
35}
36
37#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
39pub struct ScheduledRunState {
40 pub goal_id: String,
41 pub root_task_id: String,
42 pub effective_budget_per_check: i64,
43 pub tokens_used: i64,
44 pub budget_extensions_count: usize,
45 #[serde(default)]
46 pub health: ScheduledRunHealth,
47 pub created_at: String,
48 pub updated_at: String,
49}
50
51#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
52#[serde(rename_all = "snake_case")]
53pub enum ScheduledFailureKind {
54 RetryableTool,
55 PermanentTool,
56 AuthorizationBlocked,
57 TaskFailed,
58 OutcomeUnproven,
59}
60
61impl ScheduledFailureKind {
62 pub const fn as_str(self) -> &'static str {
63 match self {
64 Self::RetryableTool => "retryable_tool",
65 Self::PermanentTool => "permanent_tool",
66 Self::AuthorizationBlocked => "authorization_blocked",
67 Self::TaskFailed => "task_failed",
68 Self::OutcomeUnproven => "outcome_unproven",
69 }
70 }
71
72 pub fn parse(value: &str) -> Option<Self> {
73 match value {
74 "retryable_tool" => Some(Self::RetryableTool),
75 "permanent_tool" => Some(Self::PermanentTool),
76 "authorization_blocked" => Some(Self::AuthorizationBlocked),
77 "task_failed" => Some(Self::TaskFailed),
78 "outcome_unproven" => Some(Self::OutcomeUnproven),
79 _ => None,
80 }
81 }
82}
83
84#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
85#[serde(rename_all = "snake_case")]
86pub enum ScheduledRecoveryDisposition {
87 Healthy,
88 Recovering,
89 Escalated,
90}
91
92impl ScheduledRecoveryDisposition {
93 pub const fn as_str(self) -> &'static str {
94 match self {
95 Self::Healthy => "healthy",
96 Self::Recovering => "recovering",
97 Self::Escalated => "escalated",
98 }
99 }
100
101 pub fn parse(value: &str) -> Option<Self> {
102 match value {
103 "healthy" => Some(Self::Healthy),
104 "recovering" => Some(Self::Recovering),
105 "escalated" => Some(Self::Escalated),
106 _ => None,
107 }
108 }
109}
110
111#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
114pub struct ScheduledRecoveryState {
115 pub goal_id: String,
116 pub consecutive_failures: u16,
117 pub failure_budget: u16,
118 pub disposition: ScheduledRecoveryDisposition,
119 pub latest_failure_kind: Option<ScheduledFailureKind>,
120 pub last_failed_run_id: Option<String>,
121 pub last_recovery_run_id: Option<String>,
122 #[serde(default)]
125 pub recovery_attempts: u16,
126 #[serde(default)]
127 pub last_recovery_attempt_at: Option<String>,
128 pub updated_at: String,
129}
130
131#[derive(Debug, Clone, Serialize, Deserialize)]
139pub struct Goal {
140 pub id: String,
141 pub description: String,
142 pub domain: String,
144 pub goal_type: String,
146 pub status: String,
148 pub priority: String,
150 pub conditions: Option<String>,
152 pub context: Option<String>,
154 pub resources: Option<String>,
156 pub budget_per_check: Option<i64>,
158 pub budget_daily: Option<i64>,
160 pub tokens_used_today: i64,
162 pub tokens_used_day: String,
164 pub last_useful_action: Option<String>,
166 pub created_at: String,
167 pub updated_at: String,
168 pub completed_at: Option<String>,
169 pub parent_goal_id: Option<String>,
171 pub session_id: String,
173 pub notified_at: Option<String>,
175 #[serde(default)]
177 pub notification_attempts: i32,
178 #[serde(default)]
180 pub dispatch_failures: i32,
181 #[serde(skip_serializing_if = "Option::is_none")]
183 pub progress_notes: Option<Vec<String>>,
184 #[serde(skip_serializing_if = "Option::is_none")]
186 pub source_episode_id: Option<i64>,
187 #[serde(skip_serializing_if = "Option::is_none")]
189 pub legacy_int_id: Option<i64>,
190}
191
192impl Goal {
193 pub fn new_finite(description: &str, session_id: &str) -> Self {
195 let now = chrono::Utc::now().to_rfc3339();
196 let day = chrono::Utc::now().date_naive().to_string();
197 Self {
198 id: uuid::Uuid::new_v4().to_string(),
199 description: description.to_string(),
200 domain: "orchestration".to_string(),
201 goal_type: "finite".to_string(),
202 status: "active".to_string(),
203 priority: "medium".to_string(),
204 conditions: None,
205 context: None,
206 resources: None,
207 budget_per_check: Some(100_000),
210 budget_daily: Some(1_000_000),
211 tokens_used_today: 0,
212 tokens_used_day: day,
213 last_useful_action: None,
214 created_at: now.clone(),
215 updated_at: now,
216 completed_at: None,
217 parent_goal_id: None,
218 session_id: session_id.to_string(),
219 notified_at: None,
220 notification_attempts: 0,
221 dispatch_failures: 0,
222 progress_notes: None,
223 source_episode_id: None,
224 legacy_int_id: None,
225 }
226 }
227
228 pub fn new_personal(description: &str, session_id: &str) -> Self {
233 let now = chrono::Utc::now().to_rfc3339();
234 let day = chrono::Utc::now().date_naive().to_string();
235 Self {
236 id: uuid::Uuid::new_v4().to_string(),
237 description: description.to_string(),
238 domain: "personal".to_string(),
239 goal_type: "finite".to_string(),
240 status: "active".to_string(),
241 priority: "medium".to_string(),
242 conditions: None,
243 context: None,
244 resources: None,
245 budget_per_check: None,
246 budget_daily: None,
247 tokens_used_today: 0,
248 tokens_used_day: day,
249 last_useful_action: None,
250 created_at: now.clone(),
251 updated_at: now,
252 completed_at: None,
253 parent_goal_id: None,
254 session_id: session_id.to_string(),
255 notified_at: None,
256 notification_attempts: 0,
257 dispatch_failures: 0,
258 progress_notes: Some(Vec::new()),
259 source_episode_id: None,
260 legacy_int_id: None,
261 }
262 }
263
264 pub fn new_deferred_finite(description: &str, session_id: &str) -> Self {
268 let mut goal = Self::new_finite(description, session_id);
269 goal.status = "pending_confirmation".to_string();
270 goal
271 }
272
273 pub fn new_continuous(
275 description: &str,
276 session_id: &str,
277 budget_per_check: Option<i64>,
278 budget_daily: Option<i64>,
279 ) -> Self {
280 let now = chrono::Utc::now().to_rfc3339();
281 let day = chrono::Utc::now().date_naive().to_string();
282 Self {
283 id: uuid::Uuid::new_v4().to_string(),
284 description: description.to_string(),
285 domain: "orchestration".to_string(),
286 goal_type: "continuous".to_string(),
287 status: "active".to_string(),
288 priority: "low".to_string(),
289 conditions: None,
290 context: None,
291 resources: None,
292 budget_per_check: budget_per_check.or(Some(400_000)),
297 budget_daily: budget_daily.or(Some(1_000_000)),
298 tokens_used_today: 0,
299 tokens_used_day: day,
300 last_useful_action: None,
301 created_at: now.clone(),
302 updated_at: now,
303 completed_at: None,
304 parent_goal_id: None,
305 session_id: session_id.to_string(),
306 notified_at: None,
307 notification_attempts: 0,
308 dispatch_failures: 0,
309 progress_notes: None,
310 source_episode_id: None,
311 legacy_int_id: None,
312 }
313 }
314
315 pub fn new_continuous_pending(
317 description: &str,
318 session_id: &str,
319 budget_per_check: Option<i64>,
320 budget_daily: Option<i64>,
321 ) -> Self {
322 let mut goal =
323 Self::new_continuous(description, session_id, budget_per_check, budget_daily);
324 goal.status = "pending_confirmation".to_string();
325 goal
326 }
327}
328
329#[derive(Debug, Clone, Serialize, Deserialize)]
331pub struct GoalSchedule {
332 pub id: String,
333 pub goal_id: String,
334 pub cron_expr: String,
336 pub tz: String,
339 pub original_schedule: Option<String>,
341 pub fire_policy: String,
343 pub is_one_shot: bool,
344 pub is_paused: bool,
345 pub last_run_at: Option<String>,
346 pub next_run_at: String,
347 pub created_at: String,
348 pub updated_at: String,
349}
350
351#[derive(Debug, Clone, Serialize, Deserialize)]
353#[allow(dead_code)] pub struct Task {
355 pub id: String,
356 pub goal_id: String,
357 pub description: String,
358 pub status: String,
361 pub priority: String,
363 pub task_order: i32,
365 pub parallel_group: Option<String>,
367 pub depends_on: Option<String>,
369 pub agent_id: Option<String>,
371 pub context: Option<String>,
373 pub result: Option<String>,
375 pub error: Option<String>,
377 pub blocker: Option<String>,
379 pub idempotent: bool,
381 pub retry_count: i32,
382 pub max_retries: i32,
383 pub created_at: String,
384 pub started_at: Option<String>,
385 pub completed_at: Option<String>,
386}
387
388impl Task {
389 pub fn dependency_ids(&self) -> Result<Vec<String>, String> {
393 let Some(raw) = self.depends_on.as_deref() else {
394 return Ok(Vec::new());
395 };
396 let ids = serde_json::from_str::<Vec<String>>(raw).map_err(|error| {
397 format!("task {} has invalid dependency metadata: {error}", self.id)
398 })?;
399 let mut unique = std::collections::BTreeSet::new();
400 for id in &ids {
401 if id.trim().is_empty() {
402 return Err(format!("task {} has an empty dependency ID", self.id));
403 }
404 if id == &self.id {
405 return Err(format!("task {} cannot depend on itself", self.id));
406 }
407 if !unique.insert(id.clone()) {
408 return Err(format!(
409 "task {} lists dependency {} more than once",
410 self.id, id
411 ));
412 }
413 }
414 Ok(ids)
415 }
416
417 pub fn has_error(&self) -> bool {
421 self.error
422 .as_deref()
423 .is_some_and(|error| !error.trim().is_empty())
424 }
425
426 pub fn has_blocker(&self) -> bool {
430 self.blocker
431 .as_deref()
432 .is_some_and(|blocker| !blocker.trim().is_empty())
433 }
434
435 pub fn completed_successfully(&self) -> bool {
436 self.status == "completed" && !self.has_error() && !self.has_blocker()
437 }
438
439 pub fn satisfies_run_completion(&self) -> bool {
443 self.completed_successfully() || matches!(self.status.as_str(), "skipped" | "superseded")
444 }
445}
446
447pub fn task_execution_graph(
448 tasks: &[Task],
449) -> Result<aidaemon_events::execution_graph::ExecutionGraph, String> {
450 let nodes = tasks
451 .iter()
452 .map(|task| {
453 Ok(aidaemon_events::execution_graph::ExecutionTaskNode {
454 id: task.id.clone(),
455 status: task.status.clone(),
456 dependency_ids: task.dependency_ids()?,
457 })
458 })
459 .collect::<Result<Vec<_>, String>>()?;
460 aidaemon_events::execution_graph::ExecutionGraph::from_task_nodes(&nodes)
461}
462
463#[derive(Debug, Clone, Copy, PartialEq, Eq)]
464pub enum ExpiredAttemptRecovery {
465 Requeue,
466 RequireVerification,
467}
468
469impl ExpiredAttemptRecovery {
470 pub fn classify(idempotent: bool, retry_count: i32, max_retries: i32) -> Self {
471 if idempotent && retry_count < max_retries {
472 Self::Requeue
473 } else {
474 Self::RequireVerification
475 }
476 }
477}
478
479#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
481pub struct WorkProject {
482 pub id: String,
483 pub name: String,
484 pub description: Option<String>,
485 #[serde(default, skip_serializing_if = "Option::is_none")]
487 pub path: Option<String>,
488 pub created_at: String,
489 pub updated_at: String,
490}
491
492pub const GOAL_RUN_MISSED: &str = "missed";
496
497#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
500pub struct GoalRun {
501 pub id: String,
502 pub project_id: String,
503 pub goal_id: String,
504 pub trigger_type: String,
506 pub schedule_id: Option<String>,
507 pub root_task_id: Option<String>,
508 pub status: String,
511 pub outcome_summary: Option<String>,
512 pub started_at: String,
513 pub completed_at: Option<String>,
514 pub created_at: String,
515 pub updated_at: String,
516}
517
518impl GoalRun {
519 pub fn new(goal_id: &str, project_id: &str, trigger_type: &str) -> Self {
520 let now = chrono::Utc::now().to_rfc3339();
521 Self {
522 id: uuid::Uuid::new_v4().to_string(),
523 project_id: project_id.to_string(),
524 goal_id: goal_id.to_string(),
525 trigger_type: trigger_type.to_string(),
526 schedule_id: None,
527 root_task_id: None,
528 status: "pending".to_string(),
531 outcome_summary: None,
532 started_at: now.clone(),
533 completed_at: None,
534 created_at: now.clone(),
535 updated_at: now,
536 }
537 }
538}
539
540#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
543pub struct WorkerProfile {
544 pub id: String,
545 pub project_id: Option<String>,
546 pub name: String,
547 pub specialist: String,
548 pub model: Option<String>,
549 pub tools_json: Option<String>,
550 pub max_iterations: Option<i64>,
551 pub tool_budget: Option<i64>,
552 pub timeout_secs: Option<i64>,
553 pub max_concurrency: i64,
554 pub workspace_policy: String,
556 pub memory_scope: String,
557 pub version: i64,
558 pub enabled: bool,
559 pub created_at: String,
560 pub updated_at: String,
561}
562
563#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
565pub struct TaskAttempt {
566 pub id: String,
567 pub task_id: String,
568 pub goal_run_id: String,
569 pub worker_profile_id: Option<String>,
570 pub worker_instance_id: String,
571 #[serde(skip_serializing)]
573 pub lease_token: String,
574 pub status: String,
577 pub lease_expires_at: String,
578 pub last_heartbeat_at: String,
579 pub workspace_id: Option<String>,
580 pub started_at: String,
581 pub completed_at: Option<String>,
582}
583
584#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
585pub struct HandoffArtifact {
586 pub kind: String,
588 pub reference: String,
589 pub digest: Option<String>,
590 pub metadata: Option<String>,
591}
592
593#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
595pub struct TaskHandoff {
596 pub id: String,
597 pub task_id: String,
598 pub attempt_id: String,
599 pub summary: String,
600 pub artifacts: Vec<HandoffArtifact>,
601 pub verification: Vec<String>,
602 pub remaining_risk: Option<String>,
603 pub next_step: Option<String>,
604 pub created_at: String,
605}
606
607#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
610pub struct TaskJournalEntry {
611 pub id: String,
612 pub project_id: String,
613 pub goal_id: String,
614 pub goal_run_id: String,
615 pub task_id: Option<String>,
616 pub attempt_id: Option<String>,
617 pub entry_type: String,
620 pub actor_type: String,
622 pub actor_id: String,
623 pub source_channel: Option<String>,
624 pub body: String,
625 pub payload: Option<String>,
626 pub created_at: String,
627}
628
629impl TaskJournalEntry {
630 pub fn new(
631 project_id: &str,
632 goal_id: &str,
633 goal_run_id: &str,
634 entry_type: &str,
635 actor_type: &str,
636 actor_id: &str,
637 body: &str,
638 ) -> Self {
639 Self {
640 id: uuid::Uuid::new_v4().to_string(),
641 project_id: project_id.to_string(),
642 goal_id: goal_id.to_string(),
643 goal_run_id: goal_run_id.to_string(),
644 task_id: None,
645 attempt_id: None,
646 entry_type: entry_type.to_string(),
647 actor_type: actor_type.to_string(),
648 actor_id: actor_id.to_string(),
649 source_channel: None,
650 body: body.to_string(),
651 payload: None,
652 created_at: chrono::Utc::now().to_rfc3339(),
653 }
654 }
655
656 pub fn with_task(mut self, task_id: Option<&str>, attempt_id: Option<&str>) -> Self {
657 self.task_id = task_id.map(ToOwned::to_owned);
658 self.attempt_id = attempt_id.map(ToOwned::to_owned);
659 self
660 }
661
662 pub fn with_source_channel(mut self, source_channel: Option<&str>) -> Self {
663 self.source_channel = source_channel.map(ToOwned::to_owned);
664 self
665 }
666}
667
668#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
671pub struct TaskWorkspace {
672 pub id: String,
673 pub task_id: String,
674 pub attempt_id: String,
675 pub backend_id: String,
676 pub policy: String,
677 pub root_path: String,
678 pub branch_name: Option<String>,
679 pub base_ref: Option<String>,
680 pub head_ref: Option<String>,
681 pub status: String,
683 pub created_at: String,
684 pub released_at: Option<String>,
685}
686
687#[derive(Debug, Clone, Default)]
689pub struct TaskAttemptPatch {
690 pub status: String,
691 pub result: Option<String>,
692 pub error: Option<String>,
693 pub blocker: Option<String>,
694 pub context: Option<String>,
695 pub handoff: Option<TaskHandoff>,
696}
697
698#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
700pub struct WorkGoalSummary {
701 pub project_id: String,
702 pub goal_id: String,
703 pub description: String,
704 pub goal_status: String,
705 pub run_id: Option<String>,
706 pub run_status: Option<String>,
707 pub waiting: i64,
708 pub ready: i64,
709 pub in_progress: i64,
710 pub blocked: i64,
711 pub needs_attention: i64,
712 pub done: i64,
713 pub updated_at: String,
714}
715
716#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
719pub struct WorkTaskSummary {
720 pub project_id: String,
721 pub goal_id: String,
722 pub goal_description: String,
723 pub goal_run_id: String,
724 pub task_id: String,
725 pub description: String,
726 pub status: String,
727 pub lane: String,
728 pub priority: String,
729 pub worker_profile: Option<String>,
730 pub worker_instance_id: Option<String>,
731 pub lease_expires_at: Option<String>,
732 pub blocker: Option<String>,
733 pub updated_at: String,
734}
735
736pub const REMOTE_CHANGE_ACTIVITY: &str = "remote_change";
740
741#[derive(Debug, Clone, Serialize, Deserialize)]
743#[allow(dead_code)] pub struct TaskActivity {
745 pub id: i64,
746 pub task_id: String,
747 pub activity_type: String,
749 pub tool_name: Option<String>,
750 pub tool_args: Option<String>,
751 pub result: Option<String>,
752 pub success: Option<bool>,
753 pub tokens_used: Option<i64>,
754 pub created_at: String,
755}
756
757#[derive(Debug, Clone, PartialEq)]
765pub struct BackgroundSpawn {
766 pub id: String,
767 pub session_id: String,
768 pub mission: String,
769 pub started_at: String,
770}
771
772#[derive(Debug, Clone, Serialize, Deserialize)]
773pub struct NotificationEntry {
774 pub id: String,
775 pub goal_id: String,
776 pub session_id: String,
777 pub notification_type: String,
779 pub priority: String,
781 pub message: String,
782 pub created_at: String,
783 pub delivered_at: Option<String>,
784 pub attempts: i32,
785 pub expires_at: Option<String>,
787 #[serde(default, skip_serializing_if = "Option::is_none")]
789 pub task_id: Option<String>,
790 #[serde(default, skip_serializing_if = "Option::is_none")]
792 pub action_token: Option<String>,
793 #[serde(default)]
797 pub untrusted: bool,
798}
799
800#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
802pub struct DeliveredNotice {
803 pub id: String,
804 pub notification_type: String,
806 pub message: String,
808 pub delivered_at: String,
810 #[serde(default, skip_serializing_if = "Option::is_none")]
812 pub mandate_id: Option<String>,
813}
814
815pub fn notices_turn_context(notices: &[DeliveredNotice]) -> Option<String> {
824 if notices.is_empty() {
825 return None;
826 }
827 let mut context = String::from(
828 "[NOTICES SENT DURING THIS TURN] While you worked, the owner already received these \
829 messages. Your reply must agree with them; do not repeat them in full, and do not \
830 say something has not happened when a notice says it has.",
831 );
832 for notice in notices {
833 let at = crate::schedule::owner_time_rfc3339(¬ice.delivered_at)
834 .unwrap_or_else(|| notice.delivered_at.clone());
835 context.push_str(&format!("\n- at {at} ({}", notice.notification_type));
836 if let Some(mandate_id) = notice.mandate_id.as_deref() {
837 context.push_str(&format!(", mandate_id {mandate_id}"));
838 }
839 context.push_str(&format!("): {}", notice.message.trim()));
840 }
841 Some(context)
842}
843
844impl NotificationEntry {
845 pub const DEFAULT_QUIET_HOURS_START: u32 = 22;
846 pub const DEFAULT_QUIET_HOURS_END: u32 = 7;
847
848 pub fn new(goal_id: &str, session_id: &str, notification_type: &str, message: &str) -> Self {
850 let now = chrono::Utc::now();
851 let priority = match notification_type {
852 "completed"
853 | "failed"
854 | "escalation"
855 | "evergreen_alert"
856 | "token_alert"
857 | "mandate_action"
858 | "mandate_ask"
859 | "mandate_alert"
860 | "mandate_ask_timeout"
861 | "mandate_stopped"
862 | "mandate_review_failed"
863 | "mandate_reconciliation"
864 | "mandate_reconciliation_required"
865 | "node_monitor_alert" => "critical",
866 _ => "status_update",
867 };
868 let expires_at = if priority == "status_update" {
869 Some((now + chrono::Duration::hours(24)).to_rfc3339())
870 } else {
871 None };
873 Self {
874 id: uuid::Uuid::new_v4().to_string(),
875 goal_id: goal_id.to_string(),
876 session_id: session_id.to_string(),
877 notification_type: notification_type.to_string(),
878 priority: priority.to_string(),
879 message: message.to_string(),
880 created_at: now.to_rfc3339(),
881 delivered_at: None,
882 attempts: 0,
883 expires_at,
884 task_id: None,
885 action_token: None,
886 untrusted: false,
887 }
888 }
889
890 pub fn with_untrusted(mut self, untrusted: bool) -> Self {
892 self.untrusted = untrusted;
893 self
894 }
895
896 pub fn with_task(mut self, task_id: &str) -> Self {
897 self.task_id = Some(task_id.to_string());
898 self.action_token = Some(uuid::Uuid::new_v4().to_string());
899 self
900 }
901
902 pub fn interrupts_quiet_hours(&self) -> bool {
905 matches!(
906 self.notification_type.as_str(),
907 "mandate_ask"
908 | "mandate_alert"
909 | "mandate_reconciliation_required"
910 | "escalation"
911 | "node_monitor_alert"
912 )
913 }
914
915 pub fn should_deliver_at_local_hour(&self, hour: u32) -> bool {
916 Self::routine_delivery_allowed_at_local_hour(hour) || self.interrupts_quiet_hours()
917 }
918
919 pub fn routine_delivery_allowed_at_local_hour(hour: u32) -> bool {
920 (Self::DEFAULT_QUIET_HOURS_END..Self::DEFAULT_QUIET_HOURS_START).contains(&hour)
921 }
922}
923
924pub fn is_terminal_task_status(status: &str) -> bool {
932 matches!(
933 status,
934 "completed"
935 | "skipped"
936 | "superseded"
937 | "failed"
938 | "blocked"
939 | "interrupted"
940 | "cancelled"
941 | "abandoned"
942 )
943}
944
945pub fn tasks_satisfy_goal_completion(tasks: &[Task]) -> bool {
947 !tasks.is_empty() && tasks.iter().all(Task::satisfies_run_completion)
948}
949
950#[cfg(test)]
951mod notification_attention_tests {
952 use super::NotificationEntry;
953
954 #[test]
955 fn recoverable_failures_wait_during_quiet_hours() {
956 let failed = NotificationEntry::new("goal", "session", "failed", "retry exhausted");
957 assert!(!failed.should_deliver_at_local_hour(2));
958 assert!(failed.should_deliver_at_local_hour(9));
959 }
960
961 #[test]
962 fn owner_action_requests_interrupt_quiet_hours() {
963 for kind in [
964 "mandate_ask",
965 "mandate_reconciliation_required",
966 "escalation",
967 ] {
968 let entry = NotificationEntry::new("goal", "session", kind, "owner action needed");
969 assert!(entry.should_deliver_at_local_hour(2));
970 }
971 }
972
973 #[test]
974 fn token_pressure_is_recoverable_not_an_owner_interrupt() {
975 let entry = NotificationEntry::new("goal", "session", "token_alert", "adapt budget");
976 assert!(!entry.should_deliver_at_local_hour(2));
977 }
978}