Skip to main content

aidaemon_work/
goals.rs

1use serde::{Deserialize, Serialize};
2
3pub const DEFAULT_PROJECT_ID: &str = "default";
4
5/// Snapshot of a goal's token budget state.
6#[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/// Persisted runtime state for an active scheduled run.
14#[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    /// The finalized completion contract requires at least one mutation.
19    #[serde(default)]
20    pub completion_requires_mutation: bool,
21    /// At least one successful mutation receipt matches a required effect.
22    #[serde(default)]
23    pub required_mutation_progress: bool,
24    /// The finalized completion contract requires result verification.
25    #[serde(default)]
26    pub completion_requires_observation: bool,
27    /// A verification receipt matched the task's target.
28    #[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/// Persisted runtime state for an active scheduled run.
37#[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/// Cross-run failure-budget state for one parent scheduled objective. Unlike
111/// `ScheduledRunState`, this survives individual run teardown.
112#[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    /// Automatic recovery runs launched by the heartbeat after escalation.
122    /// Bounded so an unfixable objective cannot retry forever.
123    #[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// ==================== Goals + Tasks Data Model ====================
131
132/// A goal — a tracked, potentially long-running objective.
133///
134/// Goals are stored in a single `goals` table with a `domain` that gates behavior:
135/// - `orchestration`: can be scheduled/continuous, can have tasks, can be dispatched
136/// - `personal`: tracked/injected/listed, never dispatched, usually no tasks
137#[derive(Debug, Clone, Serialize, Deserialize)]
138pub struct Goal {
139    pub id: String,
140    pub description: String,
141    /// "orchestration" (default) or "personal"
142    pub domain: String,
143    /// "finite" (one-shot) or "continuous" (monitoring/recurring)
144    pub goal_type: String,
145    /// "pending", "pending_confirmation", "active", "paused", "completed", "failed", "cancelled", "abandoned"
146    pub status: String,
147    /// "low", "medium", "high", "critical"
148    pub priority: String,
149    /// Success/completion conditions (human-readable)
150    pub conditions: Option<String>,
151    /// JSON context blob (original request, constraints, etc.)
152    pub context: Option<String>,
153    /// JSON array of resource references (files, URLs, etc.)
154    pub resources: Option<String>,
155    /// Max tokens per check (for continuous goals)
156    pub budget_per_check: Option<i64>,
157    /// Max tokens per day for this goal
158    pub budget_daily: Option<i64>,
159    /// Tokens used for the UTC day in `tokens_used_day` (reset daily).
160    pub tokens_used_today: i64,
161    /// UTC day anchor for `tokens_used_today` (YYYY-MM-DD).
162    pub tokens_used_day: String,
163    /// Timestamp of last meaningful action
164    pub last_useful_action: Option<String>,
165    pub created_at: String,
166    pub updated_at: String,
167    pub completed_at: Option<String>,
168    /// Parent goal ID for hierarchical decomposition
169    pub parent_goal_id: Option<String>,
170    /// Session where this goal was created
171    pub session_id: String,
172    /// Timestamp when user was notified of completion/failure (None = not yet notified)
173    pub notified_at: Option<String>,
174    /// Number of notification delivery attempts (gives up after 3)
175    #[serde(default)]
176    pub notification_attempts: i32,
177    /// Consecutive dispatch cycles with no progress (circuit breaker: stalls at 3)
178    #[serde(default)]
179    pub dispatch_failures: i32,
180    /// Personal-goal progress notes (append-only) stored as JSON array.
181    #[serde(skip_serializing_if = "Option::is_none")]
182    pub progress_notes: Option<Vec<String>>,
183    /// Optional episodic-memory provenance (personal goals).
184    #[serde(skip_serializing_if = "Option::is_none")]
185    pub source_episode_id: Option<i64>,
186    /// Optional legacy integer ID (for migrated pre-unification personal goals).
187    #[serde(skip_serializing_if = "Option::is_none")]
188    pub legacy_int_id: Option<i64>,
189}
190
191impl Goal {
192    /// Create a new finite (one-shot) goal from a user request.
193    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            // Safety defaults: generous enough for normal usage (including
207            // sub-agent token overhead), but prevents runaway execution.
208            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    /// Create a new personal goal.
228    ///
229    /// Personal goals are tracked and injected (DM-only) but never dispatched
230    /// as background work. Budgets are unset because they do not execute.
231    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    /// Create a deferred one-shot finite goal pending user confirmation.
264    ///
265    /// Scheduling is managed via `GoalSchedule` rows, not a goal column.
266    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    /// Create a new continuous (evergreen) goal.
273    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            // Scheduled work carries task-lead and executor context overhead in
292            // addition to the action itself. Observed write/build/deploy/verify
293            // cycles exceed 300k even when healthy. Keep the budget bounded,
294            // but leave headroom for one complete cycle and two daily attempts.
295            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    /// Create a continuous goal pending user confirmation.
315    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/// Goal schedule row — per-schedule state for a goal.
329#[derive(Debug, Clone, Serialize, Deserialize)]
330pub struct GoalSchedule {
331    pub id: String,
332    pub goal_id: String,
333    /// 5-field cron expression.
334    pub cron_expr: String,
335    /// The zone `cron_expr` is read in: `local` (the owner's zone), an IANA
336    /// name, or a fixed offset; see `schedule::ScheduleZone::stored`.
337    pub tz: String,
338    /// User-provided schedule string (optional; for display/audit).
339    pub original_schedule: Option<String>,
340    /// "coalesce" (default) or "always_fire"
341    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/// A task — a discrete unit of work within a goal.
351#[derive(Debug, Clone, Serialize, Deserialize)]
352pub struct Task {
353    pub id: String,
354    pub goal_id: String,
355    pub description: String,
356    /// "pending", "claimed", "running", "completed", "failed", "blocked",
357    /// "skipped", or "superseded"
358    pub status: String,
359    /// "low", "medium", "high"
360    pub priority: String,
361    /// Execution order within the goal
362    pub task_order: i32,
363    /// Tasks in the same parallel group can run concurrently
364    pub parallel_group: Option<String>,
365    /// JSON array of task IDs this task depends on
366    pub depends_on: Option<String>,
367    /// Agent/executor ID that claimed this task
368    pub agent_id: Option<String>,
369    /// JSON context blob
370    pub context: Option<String>,
371    /// Result text on completion
372    pub result: Option<String>,
373    /// Error message on failure
374    pub error: Option<String>,
375    /// Blocker description if status is "blocked"
376    pub blocker: Option<String>,
377    /// Whether this task is safe to retry
378    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    /// Parse the compatibility JSON projection into typed dependency IDs.
388    /// Durable scheduling also stores normalized edges; this method is the
389    /// shared validation boundary for callers and migration compatibility.
390    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    /// SQLite contains legacy task rows whose optional error field is an empty
416    /// string instead of NULL. Treat blank error text as absent everywhere task
417    /// success is evaluated.
418    pub fn has_error(&self) -> bool {
419        self.error
420            .as_deref()
421            .is_some_and(|error| !error.trim().is_empty())
422    }
423
424    /// A blocker is unresolved work even if a stale coordinator has written a
425    /// terminal-looking status. Treat legacy empty strings as absent, matching
426    /// the normalization used for errors.
427    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    /// True when this task no longer represents required work for the current
438    /// run. A superseded task is not itself a success, but a successful
439    /// replacement means it must not poison the run's terminal outcome.
440    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/// A stable isolation boundary for goals, runs, worker policies, and channel views.
478#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
479pub struct WorkProject {
480    pub id: String,
481    pub name: String,
482    pub description: Option<String>,
483    /// The folder the project's conversations work in, as an absolute path.
484    #[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
490/// The status of a scheduled occurrence that never ran: the daemon was not
491/// running when it was due, and it was past its catch-up window when the
492/// daemon came back. A closed run, but neither a success nor a failure.
493pub const GOAL_RUN_MISSED: &str = "missed";
494
495/// The status of a run cut off before it did anything outside (most often
496/// by a daemon restart) and retried on its own: a closed run, neither a
497/// success nor a failure, and outside failure counts. Today only a
498/// watching automation's review that dispatched nothing ends this way.
499pub const GOAL_RUN_INTERRUPTED: &str = "interrupted";
500
501/// One execution of a goal. Finite goals normally have one run; each scheduled
502/// firing gets a distinct run.
503#[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    /// "finite", "scheduled", "manual", "mandate", or "legacy"
509    pub trigger_type: String,
510    pub schedule_id: Option<String>,
511    pub root_task_id: Option<String>,
512    /// "pending", "running", "completed", "failed", "blocked", "cancelled",
513    /// [`GOAL_RUN_MISSED`] or [`GOAL_RUN_INTERRUPTED`]
514    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            // A run exists before any worker owns its root task. It becomes
533            // `running` atomically with the first successful task claim.
534            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/// Durable execution policy. The profile is stable configuration; a task
545/// attempt and its worker instance remain distinct identities.
546#[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    /// "shared", "isolated", or "worktree"
559    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/// One fenced claim of a task by one worker instance.
568#[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    /// Local fencing token. It is never included in user-facing output.
576    #[serde(skip_serializing)]
577    pub lease_token: String,
578    /// "claimed", "running", "completed", "failed", "blocked", "expired",
579    /// "needs_verification", or "cancelled"
580    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    /// "path", "commit", "url", "message", or another explicit artifact kind.
591    pub kind: String,
592    pub reference: String,
593    pub digest: Option<String>,
594    pub metadata: Option<String>,
595}
596
597/// Low-volume, structured output from one attempt for the next worker or human.
598#[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
611/// The single automatic effect-free replay of a scheduled root after restart.
612pub const JOURNAL_SCHEDULED_RESTART_REPLAY: &str = "scheduled_restart_replay";
613
614/// Journal kind for an attempt whose daemon process stopped (crash or
615/// restart) while it held the lease; startup recovery released the lease.
616pub const JOURNAL_PREVIOUS_INSTANCE_STOPPED: &str = "previous_instance_stopped";
617
618/// Journal kind written at shutdown, before anything is cancelled, for each
619/// attempt that still held a live lease: the daemon was asked to stop (a
620/// shutdown signal), so a crash or kill never leaves this mark.
621pub const JOURNAL_STOPPED_ON_REQUEST: &str = "stopped_on_request";
622
623/// The single automatic resume of a scheduled root that a requested stop
624/// cut off after it changed something, every change settled. Its payload is
625/// the complete receipt summary of what the cut-off run changed, handed to
626/// the root's next task lead.
627pub const JOURNAL_RESTART_RESUME: &str = "restart_resume";
628
629/// Append-only collaboration and audit record. Tool/LLM telemetry remains in
630/// `TaskActivity`; this journal is for durable decisions and human interaction.
631#[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    /// "comment", "blocked", "unblocked", "assigned", "handoff",
640    /// "lease_lost", [`JOURNAL_PREVIOUS_INSTANCE_STOPPED`], "workspace", or
641    /// "transition"
642    pub entry_type: String,
643    /// "human", "agent", or "system"
644    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/// Realized workspace for one attempt. Workspaces are preserved after execution
692/// until explicitly released so downstream integration can consume them.
693#[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    /// "active", "preserved", "released", or "failed"
705    pub status: String,
706    pub created_at: String,
707    pub released_at: Option<String>,
708}
709
710/// Attempt-scoped mutation applied only while the supplied lease is current.
711#[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/// Goal-level work projection used by chat and dashboard views.
722#[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/// Task-level work projection. `lane` is derived from scheduler state and is
740/// never persisted as a second status.
741#[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
759/// `TaskActivity::activity_type` of a call that changed something outside
760/// the machine (a post, a remote write, a deploy), recorded from its typed
761/// effects. The heartbeat reads it so a goal run never repeats one.
762pub const REMOTE_CHANGE_ACTIVITY: &str = "remote_change";
763
764/// A task activity log entry — records tool calls and results within a task.
765#[derive(Debug, Clone, Serialize, Deserialize)]
766pub struct TaskActivity {
767    pub id: i64,
768    pub task_id: String,
769    /// "tool_call", "tool_result", "llm_call", "status_change"
770    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/// A queued notification awaiting delivery to the user.
780///
781/// Notifications are queued in SQLite when the originating channel is unavailable.
782/// Retention depends on priority: status updates expire after 24 hours,
783/// critical notifications persist indefinitely until delivered.
784/// A background sub-agent still running, recorded so a restart can say it
785/// was lost and a cancel can find it.
786#[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    /// "completed", "failed", "escalation", "progress", "stalled", "evergreen_alert", "token_alert"
800    pub notification_type: String,
801    /// "critical" (persist indefinitely) or "status_update" (expire after 24h)
802    pub priority: String,
803    pub message: String,
804    pub created_at: String,
805    pub delivered_at: Option<String>,
806    pub attempts: i32,
807    /// When this notification expires (None = never, for critical notifications)
808    pub expires_at: Option<String>,
809    /// Optional durable work item associated with this notification.
810    #[serde(default, skip_serializing_if = "Option::is_none")]
811    pub task_id: Option<String>,
812    /// Opaque token reserved for channel-native actions.
813    #[serde(default, skip_serializing_if = "Option::is_none")]
814    pub action_token: Option<String>,
815    /// The message carries content someone other than the owner wrote (a
816    /// tainted child's result): delivering it into the session taints the
817    /// turn that records it.
818    #[serde(default)]
819    pub untrusted: bool,
820}
821
822/// A notice already delivered to the owner, as a running turn sees it.
823#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
824pub struct DeliveredNotice {
825    pub id: String,
826    /// The notification type ("mandate_review_failed", "mandate_ask", ...).
827    pub notification_type: String,
828    /// The text the owner read.
829    pub message: String,
830    /// When it was delivered (RFC 3339, UTC).
831    pub delivered_at: String,
832    /// The mandate it is about, when it is about one.
833    #[serde(default, skip_serializing_if = "Option::is_none")]
834    pub mandate_id: Option<String>,
835}
836
837/// The context a turn's reply needs about notices the owner received while
838/// the turn ran: they were sent a minute before the reply arrives, so the
839/// reply must not contradict them ("I haven't seen the first review run"
840/// right after "a review failed"). `None` when there were none.
841///
842/// The host adds it to the turn before the final reply, from
843/// [`crate::traits::NotificationStore::notices_delivered_since`] with the
844/// turn's start time.
845pub 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(&notice.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    /// Create a new notification entry.
871    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 // critical notifications never expire
894        };
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    /// Mark the message as carrying untrusted content.
913    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    /// Whether this notification represents a condition that genuinely needs
925    /// immediate owner attention instead of routine autonomous handling.
926    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
946/// A task status is "terminal" when it will never advance to `completed` on its
947/// own — either it already succeeded (`completed`/`skipped`), was explicitly
948/// replaced (`superseded`), or it is dead
949/// (`failed`/`blocked`/`interrupted`/`cancelled`/`abandoned`). Terminal tasks
950/// are useful when deciding whether a scheduler can make further progress.
951/// Terminal does not imply successful: strict finite/current-run completion
952/// separately requires [`Task::satisfies_run_completion`].
953pub 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
967/// Whether every task of a run completed it (and there is at least one).
968pub 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}