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