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/// One execution of a goal. Finite goals normally have one run; each scheduled
496/// firing gets a distinct run.
497#[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    /// "finite", "scheduled", "manual", "mandate", or "legacy"
503    pub trigger_type: String,
504    pub schedule_id: Option<String>,
505    pub root_task_id: Option<String>,
506    /// "pending", "running", "completed", "failed", "blocked", "cancelled",
507    /// or [`GOAL_RUN_MISSED`]
508    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            // A run exists before any worker owns its root task. It becomes
527            // `running` atomically with the first successful task claim.
528            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/// Durable execution policy. The profile is stable configuration; a task
539/// attempt and its worker instance remain distinct identities.
540#[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    /// "shared", "isolated", or "worktree"
553    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/// One fenced claim of a task by one worker instance.
562#[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    /// Local fencing token. It is never included in user-facing output.
570    #[serde(skip_serializing)]
571    pub lease_token: String,
572    /// "claimed", "running", "completed", "failed", "blocked", "expired",
573    /// "needs_verification", or "cancelled"
574    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    /// "path", "commit", "url", "message", or another explicit artifact kind.
585    pub kind: String,
586    pub reference: String,
587    pub digest: Option<String>,
588    pub metadata: Option<String>,
589}
590
591/// Low-volume, structured output from one attempt for the next worker or human.
592#[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/// Append-only collaboration and audit record. Tool/LLM telemetry remains in
606/// `TaskActivity`; this journal is for durable decisions and human interaction.
607#[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    /// "comment", "blocked", "unblocked", "assigned", "handoff",
616    /// "lease_lost", "workspace", or "transition"
617    pub entry_type: String,
618    /// "human", "agent", or "system"
619    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/// Realized workspace for one attempt. Workspaces are preserved after execution
667/// until explicitly released so downstream integration can consume them.
668#[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    /// "active", "preserved", "released", or "failed"
680    pub status: String,
681    pub created_at: String,
682    pub released_at: Option<String>,
683}
684
685/// Attempt-scoped mutation applied only while the supplied lease is current.
686#[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/// Goal-level work projection used by chat and dashboard views.
697#[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/// Task-level work projection. `lane` is derived from scheduler state and is
715/// never persisted as a second status.
716#[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
734/// `TaskActivity::activity_type` of a call that changed something outside
735/// the machine (a post, a remote write, a deploy), recorded from its typed
736/// effects. The heartbeat reads it so a goal run never repeats one.
737pub const REMOTE_CHANGE_ACTIVITY: &str = "remote_change";
738
739/// A task activity log entry — records tool calls and results within a task.
740#[derive(Debug, Clone, Serialize, Deserialize)]
741pub struct TaskActivity {
742    pub id: i64,
743    pub task_id: String,
744    /// "tool_call", "tool_result", "llm_call", "status_change"
745    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/// A queued notification awaiting delivery to the user.
755///
756/// Notifications are queued in SQLite when the originating channel is unavailable.
757/// Retention depends on priority: status updates expire after 24 hours,
758/// critical notifications persist indefinitely until delivered.
759/// A background sub-agent still running, recorded so a restart can say it
760/// was lost and a cancel can find it.
761#[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    /// "completed", "failed", "escalation", "progress", "stalled", "evergreen_alert", "token_alert"
775    pub notification_type: String,
776    /// "critical" (persist indefinitely) or "status_update" (expire after 24h)
777    pub priority: String,
778    pub message: String,
779    pub created_at: String,
780    pub delivered_at: Option<String>,
781    pub attempts: i32,
782    /// When this notification expires (None = never, for critical notifications)
783    pub expires_at: Option<String>,
784    /// Optional durable work item associated with this notification.
785    #[serde(default, skip_serializing_if = "Option::is_none")]
786    pub task_id: Option<String>,
787    /// Opaque token reserved for channel-native actions.
788    #[serde(default, skip_serializing_if = "Option::is_none")]
789    pub action_token: Option<String>,
790    /// The message carries content someone other than the owner wrote (a
791    /// tainted child's result): delivering it into the session taints the
792    /// turn that records it.
793    #[serde(default)]
794    pub untrusted: bool,
795}
796
797/// A notice already delivered to the owner, as a running turn sees it.
798#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
799pub struct DeliveredNotice {
800    pub id: String,
801    /// The notification type ("mandate_review_failed", "mandate_ask", ...).
802    pub notification_type: String,
803    /// The text the owner read.
804    pub message: String,
805    /// When it was delivered (RFC 3339, UTC).
806    pub delivered_at: String,
807    /// The mandate it is about, when it is about one.
808    #[serde(default, skip_serializing_if = "Option::is_none")]
809    pub mandate_id: Option<String>,
810}
811
812/// The context a turn's reply needs about notices the owner received while
813/// the turn ran: they were sent a minute before the reply arrives, so the
814/// reply must not contradict them ("I haven't seen the first review run"
815/// right after "a review failed"). `None` when there were none.
816///
817/// The host adds it to the turn before the final reply, from
818/// [`crate::traits::NotificationStore::notices_delivered_since`] with the
819/// turn's start time.
820pub 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(&notice.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    /// Create a new notification entry.
846    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 // critical notifications never expire
869        };
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    /// Mark the message as carrying untrusted content.
888    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    /// Whether this notification represents a condition that genuinely needs
900    /// immediate owner attention instead of routine autonomous handling.
901    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
921/// A task status is "terminal" when it will never advance to `completed` on its
922/// own — either it already succeeded (`completed`/`skipped`), was explicitly
923/// replaced (`superseded`), or it is dead
924/// (`failed`/`blocked`/`interrupted`/`cancelled`/`abandoned`). Terminal tasks
925/// are useful when deciding whether a scheduler can make further progress.
926/// Terminal does not imply successful: strict finite/current-run completion
927/// separately requires [`Task::satisfies_run_completion`].
928pub 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
942/// Whether every task of a run completed it (and there is at least one).
943pub 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}