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
495pub const GOAL_RUN_INTERRUPTED: &str = "interrupted";
500
501#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
504pub struct GoalRun {
505 pub id: String,
506 pub project_id: String,
507 pub goal_id: String,
508 pub trigger_type: String,
510 pub schedule_id: Option<String>,
511 pub root_task_id: Option<String>,
512 pub status: String,
515 pub outcome_summary: Option<String>,
516 pub started_at: String,
517 pub completed_at: Option<String>,
518 pub created_at: String,
519 pub updated_at: String,
520}
521
522impl GoalRun {
523 pub fn new(goal_id: &str, project_id: &str, trigger_type: &str) -> Self {
524 let now = chrono::Utc::now().to_rfc3339();
525 Self {
526 id: uuid::Uuid::new_v4().to_string(),
527 project_id: project_id.to_string(),
528 goal_id: goal_id.to_string(),
529 trigger_type: trigger_type.to_string(),
530 schedule_id: None,
531 root_task_id: None,
532 status: "pending".to_string(),
535 outcome_summary: None,
536 started_at: now.clone(),
537 completed_at: None,
538 created_at: now.clone(),
539 updated_at: now,
540 }
541 }
542}
543
544#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
547pub struct WorkerProfile {
548 pub id: String,
549 pub project_id: Option<String>,
550 pub name: String,
551 pub specialist: String,
552 pub model: Option<String>,
553 pub tools_json: Option<String>,
554 pub max_iterations: Option<i64>,
555 pub tool_budget: Option<i64>,
556 pub timeout_secs: Option<i64>,
557 pub max_concurrency: i64,
558 pub workspace_policy: String,
560 pub memory_scope: String,
561 pub version: i64,
562 pub enabled: bool,
563 pub created_at: String,
564 pub updated_at: String,
565}
566
567#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
569pub struct TaskAttempt {
570 pub id: String,
571 pub task_id: String,
572 pub goal_run_id: String,
573 pub worker_profile_id: Option<String>,
574 pub worker_instance_id: String,
575 #[serde(skip_serializing)]
577 pub lease_token: String,
578 pub status: String,
581 pub lease_expires_at: String,
582 pub last_heartbeat_at: String,
583 pub workspace_id: Option<String>,
584 pub started_at: String,
585 pub completed_at: Option<String>,
586}
587
588#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
589pub struct HandoffArtifact {
590 pub kind: String,
592 pub reference: String,
593 pub digest: Option<String>,
594 pub metadata: Option<String>,
595}
596
597#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
599pub struct TaskHandoff {
600 pub id: String,
601 pub task_id: String,
602 pub attempt_id: String,
603 pub summary: String,
604 pub artifacts: Vec<HandoffArtifact>,
605 pub verification: Vec<String>,
606 pub remaining_risk: Option<String>,
607 pub next_step: Option<String>,
608 pub created_at: String,
609}
610
611pub const JOURNAL_SCHEDULED_RESTART_REPLAY: &str = "scheduled_restart_replay";
613
614pub const JOURNAL_PREVIOUS_INSTANCE_STOPPED: &str = "previous_instance_stopped";
617
618pub const JOURNAL_STOPPED_ON_REQUEST: &str = "stopped_on_request";
622
623pub const JOURNAL_RESTART_RESUME: &str = "restart_resume";
628
629#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
632pub struct TaskJournalEntry {
633 pub id: String,
634 pub project_id: String,
635 pub goal_id: String,
636 pub goal_run_id: String,
637 pub task_id: Option<String>,
638 pub attempt_id: Option<String>,
639 pub entry_type: String,
643 pub actor_type: String,
645 pub actor_id: String,
646 pub source_channel: Option<String>,
647 pub body: String,
648 pub payload: Option<String>,
649 pub created_at: String,
650}
651
652impl TaskJournalEntry {
653 pub fn new(
654 project_id: &str,
655 goal_id: &str,
656 goal_run_id: &str,
657 entry_type: &str,
658 actor_type: &str,
659 actor_id: &str,
660 body: &str,
661 ) -> Self {
662 Self {
663 id: uuid::Uuid::new_v4().to_string(),
664 project_id: project_id.to_string(),
665 goal_id: goal_id.to_string(),
666 goal_run_id: goal_run_id.to_string(),
667 task_id: None,
668 attempt_id: None,
669 entry_type: entry_type.to_string(),
670 actor_type: actor_type.to_string(),
671 actor_id: actor_id.to_string(),
672 source_channel: None,
673 body: body.to_string(),
674 payload: None,
675 created_at: chrono::Utc::now().to_rfc3339(),
676 }
677 }
678
679 pub fn with_task(mut self, task_id: Option<&str>, attempt_id: Option<&str>) -> Self {
680 self.task_id = task_id.map(ToOwned::to_owned);
681 self.attempt_id = attempt_id.map(ToOwned::to_owned);
682 self
683 }
684
685 pub fn with_source_channel(mut self, source_channel: Option<&str>) -> Self {
686 self.source_channel = source_channel.map(ToOwned::to_owned);
687 self
688 }
689}
690
691#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
694pub struct TaskWorkspace {
695 pub id: String,
696 pub task_id: String,
697 pub attempt_id: String,
698 pub backend_id: String,
699 pub policy: String,
700 pub root_path: String,
701 pub branch_name: Option<String>,
702 pub base_ref: Option<String>,
703 pub head_ref: Option<String>,
704 pub status: String,
706 pub created_at: String,
707 pub released_at: Option<String>,
708}
709
710#[derive(Debug, Clone, Default)]
712pub struct TaskAttemptPatch {
713 pub status: String,
714 pub result: Option<String>,
715 pub error: Option<String>,
716 pub blocker: Option<String>,
717 pub context: Option<String>,
718 pub handoff: Option<TaskHandoff>,
719}
720
721#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
723pub struct WorkGoalSummary {
724 pub project_id: String,
725 pub goal_id: String,
726 pub description: String,
727 pub goal_status: String,
728 pub run_id: Option<String>,
729 pub run_status: Option<String>,
730 pub waiting: i64,
731 pub ready: i64,
732 pub in_progress: i64,
733 pub blocked: i64,
734 pub needs_attention: i64,
735 pub done: i64,
736 pub updated_at: String,
737}
738
739#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
742pub struct WorkTaskSummary {
743 pub project_id: String,
744 pub goal_id: String,
745 pub goal_description: String,
746 pub goal_run_id: String,
747 pub task_id: String,
748 pub description: String,
749 pub status: String,
750 pub lane: String,
751 pub priority: String,
752 pub worker_profile: Option<String>,
753 pub worker_instance_id: Option<String>,
754 pub lease_expires_at: Option<String>,
755 pub blocker: Option<String>,
756 pub updated_at: String,
757}
758
759pub const REMOTE_CHANGE_ACTIVITY: &str = "remote_change";
763
764#[derive(Debug, Clone, Serialize, Deserialize)]
766pub struct TaskActivity {
767 pub id: i64,
768 pub task_id: String,
769 pub activity_type: String,
771 pub tool_name: Option<String>,
772 pub tool_args: Option<String>,
773 pub result: Option<String>,
774 pub success: Option<bool>,
775 pub tokens_used: Option<i64>,
776 pub created_at: String,
777}
778
779#[derive(Debug, Clone, PartialEq)]
787pub struct BackgroundSpawn {
788 pub id: String,
789 pub session_id: String,
790 pub mission: String,
791 pub started_at: String,
792}
793
794#[derive(Debug, Clone, Serialize, Deserialize)]
795pub struct NotificationEntry {
796 pub id: String,
797 pub goal_id: String,
798 pub session_id: String,
799 pub notification_type: String,
801 pub priority: String,
803 pub message: String,
804 pub created_at: String,
805 pub delivered_at: Option<String>,
806 pub attempts: i32,
807 pub expires_at: Option<String>,
809 #[serde(default, skip_serializing_if = "Option::is_none")]
811 pub task_id: Option<String>,
812 #[serde(default, skip_serializing_if = "Option::is_none")]
814 pub action_token: Option<String>,
815 #[serde(default)]
819 pub untrusted: bool,
820}
821
822#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
824pub struct DeliveredNotice {
825 pub id: String,
826 pub notification_type: String,
828 pub message: String,
830 pub delivered_at: String,
832 #[serde(default, skip_serializing_if = "Option::is_none")]
834 pub mandate_id: Option<String>,
835}
836
837pub fn notices_turn_context(notices: &[DeliveredNotice]) -> Option<String> {
846 if notices.is_empty() {
847 return None;
848 }
849 let mut context = String::from(
850 "[NOTICES SENT DURING THIS TURN] While you worked, the owner already received these \
851 messages. Your reply must agree with them; do not repeat them in full, and do not \
852 say something has not happened when a notice says it has.",
853 );
854 for notice in notices {
855 let at = crate::schedule::owner_time_rfc3339(¬ice.delivered_at)
856 .unwrap_or_else(|| notice.delivered_at.clone());
857 context.push_str(&format!("\n- at {at} ({}", notice.notification_type));
858 if let Some(mandate_id) = notice.mandate_id.as_deref() {
859 context.push_str(&format!(", mandate_id {mandate_id}"));
860 }
861 context.push_str(&format!("): {}", notice.message.trim()));
862 }
863 Some(context)
864}
865
866impl NotificationEntry {
867 pub const DEFAULT_QUIET_HOURS_START: u32 = 22;
868 pub const DEFAULT_QUIET_HOURS_END: u32 = 7;
869
870 pub fn new(goal_id: &str, session_id: &str, notification_type: &str, message: &str) -> Self {
872 let now = chrono::Utc::now();
873 let priority = match notification_type {
874 "completed"
875 | "failed"
876 | "escalation"
877 | "evergreen_alert"
878 | "token_alert"
879 | "mandate_action"
880 | "mandate_ask"
881 | "mandate_alert"
882 | "mandate_ask_timeout"
883 | "mandate_stopped"
884 | "mandate_review_failed"
885 | "mandate_reconciliation"
886 | "mandate_reconciliation_required"
887 | "node_monitor_alert" => "critical",
888 _ => "status_update",
889 };
890 let expires_at = if priority == "status_update" {
891 Some((now + chrono::Duration::hours(24)).to_rfc3339())
892 } else {
893 None };
895 Self {
896 id: uuid::Uuid::new_v4().to_string(),
897 goal_id: goal_id.to_string(),
898 session_id: session_id.to_string(),
899 notification_type: notification_type.to_string(),
900 priority: priority.to_string(),
901 message: message.to_string(),
902 created_at: now.to_rfc3339(),
903 delivered_at: None,
904 attempts: 0,
905 expires_at,
906 task_id: None,
907 action_token: None,
908 untrusted: false,
909 }
910 }
911
912 pub fn with_untrusted(mut self, untrusted: bool) -> Self {
914 self.untrusted = untrusted;
915 self
916 }
917
918 pub fn with_task(mut self, task_id: &str) -> Self {
919 self.task_id = Some(task_id.to_string());
920 self.action_token = Some(uuid::Uuid::new_v4().to_string());
921 self
922 }
923
924 pub fn interrupts_quiet_hours(&self) -> bool {
927 matches!(
928 self.notification_type.as_str(),
929 "mandate_ask"
930 | "mandate_alert"
931 | "mandate_reconciliation_required"
932 | "escalation"
933 | "node_monitor_alert"
934 )
935 }
936
937 pub fn should_deliver_at_local_hour(&self, hour: u32) -> bool {
938 Self::routine_delivery_allowed_at_local_hour(hour) || self.interrupts_quiet_hours()
939 }
940
941 pub fn routine_delivery_allowed_at_local_hour(hour: u32) -> bool {
942 (Self::DEFAULT_QUIET_HOURS_END..Self::DEFAULT_QUIET_HOURS_START).contains(&hour)
943 }
944}
945
946pub fn is_terminal_task_status(status: &str) -> bool {
954 matches!(
955 status,
956 "completed"
957 | "skipped"
958 | "superseded"
959 | "failed"
960 | "blocked"
961 | "interrupted"
962 | "cancelled"
963 | "abandoned"
964 )
965}
966
967pub fn tasks_satisfy_goal_completion(tasks: &[Task]) -> bool {
969 !tasks.is_empty() && tasks.iter().all(Task::satisfies_run_completion)
970}
971
972#[cfg(test)]
973mod notification_attention_tests {
974 use super::NotificationEntry;
975
976 #[test]
977 fn recoverable_failures_wait_during_quiet_hours() {
978 let failed = NotificationEntry::new("goal", "session", "failed", "retry exhausted");
979 assert!(!failed.should_deliver_at_local_hour(2));
980 assert!(failed.should_deliver_at_local_hour(9));
981 }
982
983 #[test]
984 fn owner_action_requests_interrupt_quiet_hours() {
985 for kind in [
986 "mandate_ask",
987 "mandate_reconciliation_required",
988 "escalation",
989 ] {
990 let entry = NotificationEntry::new("goal", "session", kind, "owner action needed");
991 assert!(entry.should_deliver_at_local_hour(2));
992 }
993 }
994
995 #[test]
996 fn token_pressure_is_recoverable_not_an_owner_interrupt() {
997 let entry = NotificationEntry::new("goal", "session", "token_alert", "adapt budget");
998 assert!(!entry.should_deliver_at_local_hour(2));
999 }
1000}