use serde::{Deserialize, Serialize};
pub const DEFAULT_PROJECT_ID: &str = "default";
#[derive(Debug, Clone)]
pub struct GoalTokenBudgetStatus {
#[allow(dead_code)] pub budget_per_check: Option<i64>,
pub budget_daily: Option<i64>,
pub tokens_used_today: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct ScheduledRunHealth {
pub evidence_gain_count: usize,
pub total_successful_tool_calls: usize,
#[serde(default)]
pub completion_requires_mutation: bool,
#[serde(default)]
pub required_mutation_progress: bool,
#[serde(default)]
pub completion_requires_observation: bool,
#[serde(default)]
pub verification_progress: bool,
pub stall_count: usize,
pub consecutive_same_tool_count: usize,
pub consecutive_same_tool_unique_args: usize,
pub unrecovered_error_count: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ScheduledRunState {
pub goal_id: String,
pub root_task_id: String,
pub effective_budget_per_check: i64,
pub tokens_used: i64,
pub budget_extensions_count: usize,
#[serde(default)]
pub health: ScheduledRunHealth,
pub created_at: String,
pub updated_at: String,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ScheduledFailureKind {
RetryableTool,
PermanentTool,
AuthorizationBlocked,
TaskFailed,
OutcomeUnproven,
}
impl ScheduledFailureKind {
pub const fn as_str(self) -> &'static str {
match self {
Self::RetryableTool => "retryable_tool",
Self::PermanentTool => "permanent_tool",
Self::AuthorizationBlocked => "authorization_blocked",
Self::TaskFailed => "task_failed",
Self::OutcomeUnproven => "outcome_unproven",
}
}
pub fn parse(value: &str) -> Option<Self> {
match value {
"retryable_tool" => Some(Self::RetryableTool),
"permanent_tool" => Some(Self::PermanentTool),
"authorization_blocked" => Some(Self::AuthorizationBlocked),
"task_failed" => Some(Self::TaskFailed),
"outcome_unproven" => Some(Self::OutcomeUnproven),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ScheduledRecoveryDisposition {
Healthy,
Recovering,
Escalated,
}
impl ScheduledRecoveryDisposition {
pub const fn as_str(self) -> &'static str {
match self {
Self::Healthy => "healthy",
Self::Recovering => "recovering",
Self::Escalated => "escalated",
}
}
pub fn parse(value: &str) -> Option<Self> {
match value {
"healthy" => Some(Self::Healthy),
"recovering" => Some(Self::Recovering),
"escalated" => Some(Self::Escalated),
_ => None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ScheduledRecoveryState {
pub goal_id: String,
pub consecutive_failures: u16,
pub failure_budget: u16,
pub disposition: ScheduledRecoveryDisposition,
pub latest_failure_kind: Option<ScheduledFailureKind>,
pub last_failed_run_id: Option<String>,
pub last_recovery_run_id: Option<String>,
#[serde(default)]
pub recovery_attempts: u16,
#[serde(default)]
pub last_recovery_attempt_at: Option<String>,
pub updated_at: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Goal {
pub id: String,
pub description: String,
pub domain: String,
pub goal_type: String,
pub status: String,
pub priority: String,
pub conditions: Option<String>,
pub context: Option<String>,
pub resources: Option<String>,
pub budget_per_check: Option<i64>,
pub budget_daily: Option<i64>,
pub tokens_used_today: i64,
pub tokens_used_day: String,
pub last_useful_action: Option<String>,
pub created_at: String,
pub updated_at: String,
pub completed_at: Option<String>,
pub parent_goal_id: Option<String>,
pub session_id: String,
pub notified_at: Option<String>,
#[serde(default)]
pub notification_attempts: i32,
#[serde(default)]
pub dispatch_failures: i32,
#[serde(skip_serializing_if = "Option::is_none")]
pub progress_notes: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub source_episode_id: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub legacy_int_id: Option<i64>,
}
impl Goal {
pub fn new_finite(description: &str, session_id: &str) -> Self {
let now = chrono::Utc::now().to_rfc3339();
let day = chrono::Utc::now().date_naive().to_string();
Self {
id: uuid::Uuid::new_v4().to_string(),
description: description.to_string(),
domain: "orchestration".to_string(),
goal_type: "finite".to_string(),
status: "active".to_string(),
priority: "medium".to_string(),
conditions: None,
context: None,
resources: None,
budget_per_check: Some(100_000),
budget_daily: Some(1_000_000),
tokens_used_today: 0,
tokens_used_day: day,
last_useful_action: None,
created_at: now.clone(),
updated_at: now,
completed_at: None,
parent_goal_id: None,
session_id: session_id.to_string(),
notified_at: None,
notification_attempts: 0,
dispatch_failures: 0,
progress_notes: None,
source_episode_id: None,
legacy_int_id: None,
}
}
pub fn new_personal(description: &str, session_id: &str) -> Self {
let now = chrono::Utc::now().to_rfc3339();
let day = chrono::Utc::now().date_naive().to_string();
Self {
id: uuid::Uuid::new_v4().to_string(),
description: description.to_string(),
domain: "personal".to_string(),
goal_type: "finite".to_string(),
status: "active".to_string(),
priority: "medium".to_string(),
conditions: None,
context: None,
resources: None,
budget_per_check: None,
budget_daily: None,
tokens_used_today: 0,
tokens_used_day: day,
last_useful_action: None,
created_at: now.clone(),
updated_at: now,
completed_at: None,
parent_goal_id: None,
session_id: session_id.to_string(),
notified_at: None,
notification_attempts: 0,
dispatch_failures: 0,
progress_notes: Some(Vec::new()),
source_episode_id: None,
legacy_int_id: None,
}
}
pub fn new_deferred_finite(description: &str, session_id: &str) -> Self {
let mut goal = Self::new_finite(description, session_id);
goal.status = "pending_confirmation".to_string();
goal
}
pub fn new_continuous(
description: &str,
session_id: &str,
budget_per_check: Option<i64>,
budget_daily: Option<i64>,
) -> Self {
let now = chrono::Utc::now().to_rfc3339();
let day = chrono::Utc::now().date_naive().to_string();
Self {
id: uuid::Uuid::new_v4().to_string(),
description: description.to_string(),
domain: "orchestration".to_string(),
goal_type: "continuous".to_string(),
status: "active".to_string(),
priority: "low".to_string(),
conditions: None,
context: None,
resources: None,
budget_per_check: budget_per_check.or(Some(400_000)),
budget_daily: budget_daily.or(Some(1_000_000)),
tokens_used_today: 0,
tokens_used_day: day,
last_useful_action: None,
created_at: now.clone(),
updated_at: now,
completed_at: None,
parent_goal_id: None,
session_id: session_id.to_string(),
notified_at: None,
notification_attempts: 0,
dispatch_failures: 0,
progress_notes: None,
source_episode_id: None,
legacy_int_id: None,
}
}
pub fn new_continuous_pending(
description: &str,
session_id: &str,
budget_per_check: Option<i64>,
budget_daily: Option<i64>,
) -> Self {
let mut goal =
Self::new_continuous(description, session_id, budget_per_check, budget_daily);
goal.status = "pending_confirmation".to_string();
goal
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GoalSchedule {
pub id: String,
pub goal_id: String,
pub cron_expr: String,
pub tz: String,
pub original_schedule: Option<String>,
pub fire_policy: String,
pub is_one_shot: bool,
pub is_paused: bool,
pub last_run_at: Option<String>,
pub next_run_at: String,
pub created_at: String,
pub updated_at: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(dead_code)] pub struct Task {
pub id: String,
pub goal_id: String,
pub description: String,
pub status: String,
pub priority: String,
pub task_order: i32,
pub parallel_group: Option<String>,
pub depends_on: Option<String>,
pub agent_id: Option<String>,
pub context: Option<String>,
pub result: Option<String>,
pub error: Option<String>,
pub blocker: Option<String>,
pub idempotent: bool,
pub retry_count: i32,
pub max_retries: i32,
pub created_at: String,
pub started_at: Option<String>,
pub completed_at: Option<String>,
}
impl Task {
pub fn dependency_ids(&self) -> Result<Vec<String>, String> {
let Some(raw) = self.depends_on.as_deref() else {
return Ok(Vec::new());
};
let ids = serde_json::from_str::<Vec<String>>(raw).map_err(|error| {
format!("task {} has invalid dependency metadata: {error}", self.id)
})?;
let mut unique = std::collections::BTreeSet::new();
for id in &ids {
if id.trim().is_empty() {
return Err(format!("task {} has an empty dependency ID", self.id));
}
if id == &self.id {
return Err(format!("task {} cannot depend on itself", self.id));
}
if !unique.insert(id.clone()) {
return Err(format!(
"task {} lists dependency {} more than once",
self.id, id
));
}
}
Ok(ids)
}
pub fn has_error(&self) -> bool {
self.error
.as_deref()
.is_some_and(|error| !error.trim().is_empty())
}
pub fn has_blocker(&self) -> bool {
self.blocker
.as_deref()
.is_some_and(|blocker| !blocker.trim().is_empty())
}
pub fn completed_successfully(&self) -> bool {
self.status == "completed" && !self.has_error() && !self.has_blocker()
}
pub fn satisfies_run_completion(&self) -> bool {
self.completed_successfully() || matches!(self.status.as_str(), "skipped" | "superseded")
}
}
pub fn task_execution_graph(
tasks: &[Task],
) -> Result<aidaemon_events::execution_graph::ExecutionGraph, String> {
let nodes = tasks
.iter()
.map(|task| {
Ok(aidaemon_events::execution_graph::ExecutionTaskNode {
id: task.id.clone(),
status: task.status.clone(),
dependency_ids: task.dependency_ids()?,
})
})
.collect::<Result<Vec<_>, String>>()?;
aidaemon_events::execution_graph::ExecutionGraph::from_task_nodes(&nodes)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExpiredAttemptRecovery {
Requeue,
RequireVerification,
}
impl ExpiredAttemptRecovery {
pub fn classify(idempotent: bool, retry_count: i32, max_retries: i32) -> Self {
if idempotent && retry_count < max_retries {
Self::Requeue
} else {
Self::RequireVerification
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct WorkProject {
pub id: String,
pub name: String,
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
pub created_at: String,
pub updated_at: String,
}
pub const GOAL_RUN_MISSED: &str = "missed";
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct GoalRun {
pub id: String,
pub project_id: String,
pub goal_id: String,
pub trigger_type: String,
pub schedule_id: Option<String>,
pub root_task_id: Option<String>,
pub status: String,
pub outcome_summary: Option<String>,
pub started_at: String,
pub completed_at: Option<String>,
pub created_at: String,
pub updated_at: String,
}
impl GoalRun {
pub fn new(goal_id: &str, project_id: &str, trigger_type: &str) -> Self {
let now = chrono::Utc::now().to_rfc3339();
Self {
id: uuid::Uuid::new_v4().to_string(),
project_id: project_id.to_string(),
goal_id: goal_id.to_string(),
trigger_type: trigger_type.to_string(),
schedule_id: None,
root_task_id: None,
status: "pending".to_string(),
outcome_summary: None,
started_at: now.clone(),
completed_at: None,
created_at: now.clone(),
updated_at: now,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct WorkerProfile {
pub id: String,
pub project_id: Option<String>,
pub name: String,
pub specialist: String,
pub model: Option<String>,
pub tools_json: Option<String>,
pub max_iterations: Option<i64>,
pub tool_budget: Option<i64>,
pub timeout_secs: Option<i64>,
pub max_concurrency: i64,
pub workspace_policy: String,
pub memory_scope: String,
pub version: i64,
pub enabled: bool,
pub created_at: String,
pub updated_at: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TaskAttempt {
pub id: String,
pub task_id: String,
pub goal_run_id: String,
pub worker_profile_id: Option<String>,
pub worker_instance_id: String,
#[serde(skip_serializing)]
pub lease_token: String,
pub status: String,
pub lease_expires_at: String,
pub last_heartbeat_at: String,
pub workspace_id: Option<String>,
pub started_at: String,
pub completed_at: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct HandoffArtifact {
pub kind: String,
pub reference: String,
pub digest: Option<String>,
pub metadata: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TaskHandoff {
pub id: String,
pub task_id: String,
pub attempt_id: String,
pub summary: String,
pub artifacts: Vec<HandoffArtifact>,
pub verification: Vec<String>,
pub remaining_risk: Option<String>,
pub next_step: Option<String>,
pub created_at: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TaskJournalEntry {
pub id: String,
pub project_id: String,
pub goal_id: String,
pub goal_run_id: String,
pub task_id: Option<String>,
pub attempt_id: Option<String>,
pub entry_type: String,
pub actor_type: String,
pub actor_id: String,
pub source_channel: Option<String>,
pub body: String,
pub payload: Option<String>,
pub created_at: String,
}
impl TaskJournalEntry {
pub fn new(
project_id: &str,
goal_id: &str,
goal_run_id: &str,
entry_type: &str,
actor_type: &str,
actor_id: &str,
body: &str,
) -> Self {
Self {
id: uuid::Uuid::new_v4().to_string(),
project_id: project_id.to_string(),
goal_id: goal_id.to_string(),
goal_run_id: goal_run_id.to_string(),
task_id: None,
attempt_id: None,
entry_type: entry_type.to_string(),
actor_type: actor_type.to_string(),
actor_id: actor_id.to_string(),
source_channel: None,
body: body.to_string(),
payload: None,
created_at: chrono::Utc::now().to_rfc3339(),
}
}
pub fn with_task(mut self, task_id: Option<&str>, attempt_id: Option<&str>) -> Self {
self.task_id = task_id.map(ToOwned::to_owned);
self.attempt_id = attempt_id.map(ToOwned::to_owned);
self
}
pub fn with_source_channel(mut self, source_channel: Option<&str>) -> Self {
self.source_channel = source_channel.map(ToOwned::to_owned);
self
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TaskWorkspace {
pub id: String,
pub task_id: String,
pub attempt_id: String,
pub backend_id: String,
pub policy: String,
pub root_path: String,
pub branch_name: Option<String>,
pub base_ref: Option<String>,
pub head_ref: Option<String>,
pub status: String,
pub created_at: String,
pub released_at: Option<String>,
}
#[derive(Debug, Clone, Default)]
pub struct TaskAttemptPatch {
pub status: String,
pub result: Option<String>,
pub error: Option<String>,
pub blocker: Option<String>,
pub context: Option<String>,
pub handoff: Option<TaskHandoff>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct WorkGoalSummary {
pub project_id: String,
pub goal_id: String,
pub description: String,
pub goal_status: String,
pub run_id: Option<String>,
pub run_status: Option<String>,
pub waiting: i64,
pub ready: i64,
pub in_progress: i64,
pub blocked: i64,
pub needs_attention: i64,
pub done: i64,
pub updated_at: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct WorkTaskSummary {
pub project_id: String,
pub goal_id: String,
pub goal_description: String,
pub goal_run_id: String,
pub task_id: String,
pub description: String,
pub status: String,
pub lane: String,
pub priority: String,
pub worker_profile: Option<String>,
pub worker_instance_id: Option<String>,
pub lease_expires_at: Option<String>,
pub blocker: Option<String>,
pub updated_at: String,
}
pub const REMOTE_CHANGE_ACTIVITY: &str = "remote_change";
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(dead_code)] pub struct TaskActivity {
pub id: i64,
pub task_id: String,
pub activity_type: String,
pub tool_name: Option<String>,
pub tool_args: Option<String>,
pub result: Option<String>,
pub success: Option<bool>,
pub tokens_used: Option<i64>,
pub created_at: String,
}
#[derive(Debug, Clone, PartialEq)]
pub struct BackgroundSpawn {
pub id: String,
pub session_id: String,
pub mission: String,
pub started_at: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NotificationEntry {
pub id: String,
pub goal_id: String,
pub session_id: String,
pub notification_type: String,
pub priority: String,
pub message: String,
pub created_at: String,
pub delivered_at: Option<String>,
pub attempts: i32,
pub expires_at: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub task_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub action_token: Option<String>,
#[serde(default)]
pub untrusted: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DeliveredNotice {
pub id: String,
pub notification_type: String,
pub message: String,
pub delivered_at: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mandate_id: Option<String>,
}
pub fn notices_turn_context(notices: &[DeliveredNotice]) -> Option<String> {
if notices.is_empty() {
return None;
}
let mut context = String::from(
"[NOTICES SENT DURING THIS TURN] While you worked, the owner already received these \
messages. Your reply must agree with them; do not repeat them in full, and do not \
say something has not happened when a notice says it has.",
);
for notice in notices {
let at = crate::schedule::owner_time_rfc3339(¬ice.delivered_at)
.unwrap_or_else(|| notice.delivered_at.clone());
context.push_str(&format!("\n- at {at} ({}", notice.notification_type));
if let Some(mandate_id) = notice.mandate_id.as_deref() {
context.push_str(&format!(", mandate_id {mandate_id}"));
}
context.push_str(&format!("): {}", notice.message.trim()));
}
Some(context)
}
impl NotificationEntry {
pub const DEFAULT_QUIET_HOURS_START: u32 = 22;
pub const DEFAULT_QUIET_HOURS_END: u32 = 7;
pub fn new(goal_id: &str, session_id: &str, notification_type: &str, message: &str) -> Self {
let now = chrono::Utc::now();
let priority = match notification_type {
"completed"
| "failed"
| "escalation"
| "evergreen_alert"
| "token_alert"
| "mandate_action"
| "mandate_ask"
| "mandate_alert"
| "mandate_ask_timeout"
| "mandate_stopped"
| "mandate_review_failed"
| "mandate_reconciliation"
| "mandate_reconciliation_required"
| "node_monitor_alert" => "critical",
_ => "status_update",
};
let expires_at = if priority == "status_update" {
Some((now + chrono::Duration::hours(24)).to_rfc3339())
} else {
None };
Self {
id: uuid::Uuid::new_v4().to_string(),
goal_id: goal_id.to_string(),
session_id: session_id.to_string(),
notification_type: notification_type.to_string(),
priority: priority.to_string(),
message: message.to_string(),
created_at: now.to_rfc3339(),
delivered_at: None,
attempts: 0,
expires_at,
task_id: None,
action_token: None,
untrusted: false,
}
}
pub fn with_untrusted(mut self, untrusted: bool) -> Self {
self.untrusted = untrusted;
self
}
pub fn with_task(mut self, task_id: &str) -> Self {
self.task_id = Some(task_id.to_string());
self.action_token = Some(uuid::Uuid::new_v4().to_string());
self
}
pub fn interrupts_quiet_hours(&self) -> bool {
matches!(
self.notification_type.as_str(),
"mandate_ask"
| "mandate_alert"
| "mandate_reconciliation_required"
| "escalation"
| "node_monitor_alert"
)
}
pub fn should_deliver_at_local_hour(&self, hour: u32) -> bool {
Self::routine_delivery_allowed_at_local_hour(hour) || self.interrupts_quiet_hours()
}
pub fn routine_delivery_allowed_at_local_hour(hour: u32) -> bool {
(Self::DEFAULT_QUIET_HOURS_END..Self::DEFAULT_QUIET_HOURS_START).contains(&hour)
}
}
pub fn is_terminal_task_status(status: &str) -> bool {
matches!(
status,
"completed"
| "skipped"
| "superseded"
| "failed"
| "blocked"
| "interrupted"
| "cancelled"
| "abandoned"
)
}
pub fn tasks_satisfy_goal_completion(tasks: &[Task]) -> bool {
!tasks.is_empty() && tasks.iter().all(Task::satisfies_run_completion)
}
#[cfg(test)]
mod notification_attention_tests {
use super::NotificationEntry;
#[test]
fn recoverable_failures_wait_during_quiet_hours() {
let failed = NotificationEntry::new("goal", "session", "failed", "retry exhausted");
assert!(!failed.should_deliver_at_local_hour(2));
assert!(failed.should_deliver_at_local_hour(9));
}
#[test]
fn owner_action_requests_interrupt_quiet_hours() {
for kind in [
"mandate_ask",
"mandate_reconciliation_required",
"escalation",
] {
let entry = NotificationEntry::new("goal", "session", kind, "owner action needed");
assert!(entry.should_deliver_at_local_hour(2));
}
}
#[test]
fn token_pressure_is_recoverable_not_an_owner_interrupt() {
let entry = NotificationEntry::new("goal", "session", "token_alert", "adapt budget");
assert!(!entry.should_deliver_at_local_hour(2));
}
}