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    #[allow(dead_code)] // Reserved for future per-check budget enforcement.
9    pub budget_per_check: Option<i64>,
10    pub budget_daily: Option<i64>,
11    pub tokens_used_today: i64,
12}
13
14/// Persisted runtime state for an active scheduled run.
15#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
16pub struct ScheduledRunHealth {
17    pub evidence_gain_count: usize,
18    pub total_successful_tool_calls: usize,
19    /// The finalized completion contract requires at least one mutation.
20    #[serde(default)]
21    pub completion_requires_mutation: bool,
22    /// At least one successful mutation receipt matches a required effect.
23    #[serde(default)]
24    pub required_mutation_progress: bool,
25    /// The finalized completion contract requires result verification.
26    #[serde(default)]
27    pub completion_requires_observation: bool,
28    /// A verification receipt matched the task's target.
29    #[serde(default)]
30    pub verification_progress: bool,
31    pub stall_count: usize,
32    pub consecutive_same_tool_count: usize,
33    pub consecutive_same_tool_unique_args: usize,
34    pub unrecovered_error_count: usize,
35}
36
37/// Persisted runtime state for an active scheduled run.
38#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
39pub struct ScheduledRunState {
40    pub goal_id: String,
41    pub root_task_id: String,
42    pub effective_budget_per_check: i64,
43    pub tokens_used: i64,
44    pub budget_extensions_count: usize,
45    #[serde(default)]
46    pub health: ScheduledRunHealth,
47    pub created_at: String,
48    pub updated_at: String,
49}
50
51#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
52#[serde(rename_all = "snake_case")]
53pub enum ScheduledFailureKind {
54    RetryableTool,
55    PermanentTool,
56    AuthorizationBlocked,
57    TaskFailed,
58    OutcomeUnproven,
59}
60
61impl ScheduledFailureKind {
62    pub const fn as_str(self) -> &'static str {
63        match self {
64            Self::RetryableTool => "retryable_tool",
65            Self::PermanentTool => "permanent_tool",
66            Self::AuthorizationBlocked => "authorization_blocked",
67            Self::TaskFailed => "task_failed",
68            Self::OutcomeUnproven => "outcome_unproven",
69        }
70    }
71
72    pub fn parse(value: &str) -> Option<Self> {
73        match value {
74            "retryable_tool" => Some(Self::RetryableTool),
75            "permanent_tool" => Some(Self::PermanentTool),
76            "authorization_blocked" => Some(Self::AuthorizationBlocked),
77            "task_failed" => Some(Self::TaskFailed),
78            "outcome_unproven" => Some(Self::OutcomeUnproven),
79            _ => None,
80        }
81    }
82}
83
84#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
85#[serde(rename_all = "snake_case")]
86pub enum ScheduledRecoveryDisposition {
87    Healthy,
88    Recovering,
89    Escalated,
90}
91
92impl ScheduledRecoveryDisposition {
93    pub const fn as_str(self) -> &'static str {
94        match self {
95            Self::Healthy => "healthy",
96            Self::Recovering => "recovering",
97            Self::Escalated => "escalated",
98        }
99    }
100
101    pub fn parse(value: &str) -> Option<Self> {
102        match value {
103            "healthy" => Some(Self::Healthy),
104            "recovering" => Some(Self::Recovering),
105            "escalated" => Some(Self::Escalated),
106            _ => None,
107        }
108    }
109}
110
111/// Cross-run failure-budget state for one parent scheduled objective. Unlike
112/// `ScheduledRunState`, this survives individual run teardown.
113#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
114pub struct ScheduledRecoveryState {
115    pub goal_id: String,
116    pub consecutive_failures: u16,
117    pub failure_budget: u16,
118    pub disposition: ScheduledRecoveryDisposition,
119    pub latest_failure_kind: Option<ScheduledFailureKind>,
120    pub last_failed_run_id: Option<String>,
121    pub last_recovery_run_id: Option<String>,
122    /// Automatic recovery runs launched by the heartbeat after escalation.
123    /// Bounded so an unfixable objective cannot retry forever.
124    #[serde(default)]
125    pub recovery_attempts: u16,
126    #[serde(default)]
127    pub last_recovery_attempt_at: Option<String>,
128    pub updated_at: String,
129}
130
131// ==================== Goals + Tasks Data Model ====================
132
133/// A goal — a tracked, potentially long-running objective.
134///
135/// Goals are stored in a single `goals` table with a `domain` that gates behavior:
136/// - `orchestration`: can be scheduled/continuous, can have tasks, can be dispatched
137/// - `personal`: tracked/injected/listed, never dispatched, usually no tasks
138#[derive(Debug, Clone, Serialize, Deserialize)]
139pub struct Goal {
140    pub id: String,
141    pub description: String,
142    /// "orchestration" (default) or "personal"
143    pub domain: String,
144    /// "finite" (one-shot) or "continuous" (monitoring/recurring)
145    pub goal_type: String,
146    /// "pending", "pending_confirmation", "active", "paused", "completed", "failed", "cancelled", "abandoned"
147    pub status: String,
148    /// "low", "medium", "high", "critical"
149    pub priority: String,
150    /// Success/completion conditions (human-readable)
151    pub conditions: Option<String>,
152    /// JSON context blob (original request, constraints, etc.)
153    pub context: Option<String>,
154    /// JSON array of resource references (files, URLs, etc.)
155    pub resources: Option<String>,
156    /// Max tokens per check (for continuous goals)
157    pub budget_per_check: Option<i64>,
158    /// Max tokens per day for this goal
159    pub budget_daily: Option<i64>,
160    /// Tokens used for the UTC day in `tokens_used_day` (reset daily).
161    pub tokens_used_today: i64,
162    /// UTC day anchor for `tokens_used_today` (YYYY-MM-DD).
163    pub tokens_used_day: String,
164    /// Timestamp of last meaningful action
165    pub last_useful_action: Option<String>,
166    pub created_at: String,
167    pub updated_at: String,
168    pub completed_at: Option<String>,
169    /// Parent goal ID for hierarchical decomposition
170    pub parent_goal_id: Option<String>,
171    /// Session where this goal was created
172    pub session_id: String,
173    /// Timestamp when user was notified of completion/failure (None = not yet notified)
174    pub notified_at: Option<String>,
175    /// Number of notification delivery attempts (gives up after 3)
176    #[serde(default)]
177    pub notification_attempts: i32,
178    /// Consecutive dispatch cycles with no progress (circuit breaker: stalls at 3)
179    #[serde(default)]
180    pub dispatch_failures: i32,
181    /// Personal-goal progress notes (append-only) stored as JSON array.
182    #[serde(skip_serializing_if = "Option::is_none")]
183    pub progress_notes: Option<Vec<String>>,
184    /// Optional episodic-memory provenance (personal goals).
185    #[serde(skip_serializing_if = "Option::is_none")]
186    pub source_episode_id: Option<i64>,
187    /// Optional legacy integer ID (for migrated pre-unification personal goals).
188    #[serde(skip_serializing_if = "Option::is_none")]
189    pub legacy_int_id: Option<i64>,
190}
191
192impl Goal {
193    /// Create a new finite (one-shot) goal from a user request.
194    pub fn new_finite(description: &str, session_id: &str) -> Self {
195        let now = chrono::Utc::now().to_rfc3339();
196        let day = chrono::Utc::now().date_naive().to_string();
197        Self {
198            id: uuid::Uuid::new_v4().to_string(),
199            description: description.to_string(),
200            domain: "orchestration".to_string(),
201            goal_type: "finite".to_string(),
202            status: "active".to_string(),
203            priority: "medium".to_string(),
204            conditions: None,
205            context: None,
206            resources: None,
207            // Safety defaults: generous enough for normal usage (including
208            // sub-agent token overhead), but prevents runaway execution.
209            budget_per_check: Some(100_000),
210            budget_daily: Some(1_000_000),
211            tokens_used_today: 0,
212            tokens_used_day: day,
213            last_useful_action: None,
214            created_at: now.clone(),
215            updated_at: now,
216            completed_at: None,
217            parent_goal_id: None,
218            session_id: session_id.to_string(),
219            notified_at: None,
220            notification_attempts: 0,
221            dispatch_failures: 0,
222            progress_notes: None,
223            source_episode_id: None,
224            legacy_int_id: None,
225        }
226    }
227
228    /// Create a new personal goal.
229    ///
230    /// Personal goals are tracked and injected (DM-only) but never dispatched
231    /// as background work. Budgets are unset because they do not execute.
232    pub fn new_personal(description: &str, session_id: &str) -> Self {
233        let now = chrono::Utc::now().to_rfc3339();
234        let day = chrono::Utc::now().date_naive().to_string();
235        Self {
236            id: uuid::Uuid::new_v4().to_string(),
237            description: description.to_string(),
238            domain: "personal".to_string(),
239            goal_type: "finite".to_string(),
240            status: "active".to_string(),
241            priority: "medium".to_string(),
242            conditions: None,
243            context: None,
244            resources: None,
245            budget_per_check: None,
246            budget_daily: None,
247            tokens_used_today: 0,
248            tokens_used_day: day,
249            last_useful_action: None,
250            created_at: now.clone(),
251            updated_at: now,
252            completed_at: None,
253            parent_goal_id: None,
254            session_id: session_id.to_string(),
255            notified_at: None,
256            notification_attempts: 0,
257            dispatch_failures: 0,
258            progress_notes: Some(Vec::new()),
259            source_episode_id: None,
260            legacy_int_id: None,
261        }
262    }
263
264    /// Create a deferred one-shot finite goal pending user confirmation.
265    ///
266    /// Scheduling is managed via `GoalSchedule` rows, not a goal column.
267    pub fn new_deferred_finite(description: &str, session_id: &str) -> Self {
268        let mut goal = Self::new_finite(description, session_id);
269        goal.status = "pending_confirmation".to_string();
270        goal
271    }
272
273    /// Create a new continuous (evergreen) goal.
274    pub fn new_continuous(
275        description: &str,
276        session_id: &str,
277        budget_per_check: Option<i64>,
278        budget_daily: Option<i64>,
279    ) -> Self {
280        let now = chrono::Utc::now().to_rfc3339();
281        let day = chrono::Utc::now().date_naive().to_string();
282        Self {
283            id: uuid::Uuid::new_v4().to_string(),
284            description: description.to_string(),
285            domain: "orchestration".to_string(),
286            goal_type: "continuous".to_string(),
287            status: "active".to_string(),
288            priority: "low".to_string(),
289            conditions: None,
290            context: None,
291            resources: None,
292            // Scheduled work carries task-lead and executor context overhead in
293            // addition to the action itself. Observed write/build/deploy/verify
294            // cycles exceed 300k even when healthy. Keep the budget bounded,
295            // but leave headroom for one complete cycle and two daily attempts.
296            budget_per_check: budget_per_check.or(Some(400_000)),
297            budget_daily: budget_daily.or(Some(1_000_000)),
298            tokens_used_today: 0,
299            tokens_used_day: day,
300            last_useful_action: None,
301            created_at: now.clone(),
302            updated_at: now,
303            completed_at: None,
304            parent_goal_id: None,
305            session_id: session_id.to_string(),
306            notified_at: None,
307            notification_attempts: 0,
308            dispatch_failures: 0,
309            progress_notes: None,
310            source_episode_id: None,
311            legacy_int_id: None,
312        }
313    }
314
315    /// Create a continuous goal pending user confirmation.
316    pub fn new_continuous_pending(
317        description: &str,
318        session_id: &str,
319        budget_per_check: Option<i64>,
320        budget_daily: Option<i64>,
321    ) -> Self {
322        let mut goal =
323            Self::new_continuous(description, session_id, budget_per_check, budget_daily);
324        goal.status = "pending_confirmation".to_string();
325        goal
326    }
327}
328
329/// Goal schedule row — per-schedule state for a goal.
330#[derive(Debug, Clone, Serialize, Deserialize)]
331pub struct GoalSchedule {
332    pub id: String,
333    pub goal_id: String,
334    /// 5-field cron expression.
335    pub cron_expr: String,
336    /// The zone `cron_expr` is read in: `local` (the owner's zone), an IANA
337    /// name, or a fixed offset; see `schedule::ScheduleZone::stored`.
338    pub tz: String,
339    /// User-provided schedule string (optional; for display/audit).
340    pub original_schedule: Option<String>,
341    /// "coalesce" (default) or "always_fire"
342    pub fire_policy: String,
343    pub is_one_shot: bool,
344    pub is_paused: bool,
345    pub last_run_at: Option<String>,
346    pub next_run_at: String,
347    pub created_at: String,
348    pub updated_at: String,
349}
350
351/// A task — a discrete unit of work within a goal.
352#[derive(Debug, Clone, Serialize, Deserialize)]
353#[allow(dead_code)] // Used in Phase 2; StateStore methods and SQLite impl ready
354pub struct Task {
355    pub id: String,
356    pub goal_id: String,
357    pub description: String,
358    /// "pending", "claimed", "running", "completed", "failed", "blocked",
359    /// "skipped", or "superseded"
360    pub status: String,
361    /// "low", "medium", "high"
362    pub priority: String,
363    /// Execution order within the goal
364    pub task_order: i32,
365    /// Tasks in the same parallel group can run concurrently
366    pub parallel_group: Option<String>,
367    /// JSON array of task IDs this task depends on
368    pub depends_on: Option<String>,
369    /// Agent/executor ID that claimed this task
370    pub agent_id: Option<String>,
371    /// JSON context blob
372    pub context: Option<String>,
373    /// Result text on completion
374    pub result: Option<String>,
375    /// Error message on failure
376    pub error: Option<String>,
377    /// Blocker description if status is "blocked"
378    pub blocker: Option<String>,
379    /// Whether this task is safe to retry
380    pub idempotent: bool,
381    pub retry_count: i32,
382    pub max_retries: i32,
383    pub created_at: String,
384    pub started_at: Option<String>,
385    pub completed_at: Option<String>,
386}
387
388impl Task {
389    /// Parse the compatibility JSON projection into typed dependency IDs.
390    /// Durable scheduling also stores normalized edges; this method is the
391    /// shared validation boundary for callers and migration compatibility.
392    pub fn dependency_ids(&self) -> Result<Vec<String>, String> {
393        let Some(raw) = self.depends_on.as_deref() else {
394            return Ok(Vec::new());
395        };
396        let ids = serde_json::from_str::<Vec<String>>(raw).map_err(|error| {
397            format!("task {} has invalid dependency metadata: {error}", self.id)
398        })?;
399        let mut unique = std::collections::BTreeSet::new();
400        for id in &ids {
401            if id.trim().is_empty() {
402                return Err(format!("task {} has an empty dependency ID", self.id));
403            }
404            if id == &self.id {
405                return Err(format!("task {} cannot depend on itself", self.id));
406            }
407            if !unique.insert(id.clone()) {
408                return Err(format!(
409                    "task {} lists dependency {} more than once",
410                    self.id, id
411                ));
412            }
413        }
414        Ok(ids)
415    }
416
417    /// SQLite contains legacy task rows whose optional error field is an empty
418    /// string instead of NULL. Treat blank error text as absent everywhere task
419    /// success is evaluated.
420    pub fn has_error(&self) -> bool {
421        self.error
422            .as_deref()
423            .is_some_and(|error| !error.trim().is_empty())
424    }
425
426    /// A blocker is unresolved work even if a stale coordinator has written a
427    /// terminal-looking status. Treat legacy empty strings as absent, matching
428    /// the normalization used for errors.
429    pub fn has_blocker(&self) -> bool {
430        self.blocker
431            .as_deref()
432            .is_some_and(|blocker| !blocker.trim().is_empty())
433    }
434
435    pub fn completed_successfully(&self) -> bool {
436        self.status == "completed" && !self.has_error() && !self.has_blocker()
437    }
438
439    /// True when this task no longer represents required work for the current
440    /// run. A superseded task is not itself a success, but a successful
441    /// replacement means it must not poison the run's terminal outcome.
442    pub fn satisfies_run_completion(&self) -> bool {
443        self.completed_successfully() || matches!(self.status.as_str(), "skipped" | "superseded")
444    }
445}
446
447pub fn task_execution_graph(
448    tasks: &[Task],
449) -> Result<aidaemon_events::execution_graph::ExecutionGraph, String> {
450    let nodes = tasks
451        .iter()
452        .map(|task| {
453            Ok(aidaemon_events::execution_graph::ExecutionTaskNode {
454                id: task.id.clone(),
455                status: task.status.clone(),
456                dependency_ids: task.dependency_ids()?,
457            })
458        })
459        .collect::<Result<Vec<_>, String>>()?;
460    aidaemon_events::execution_graph::ExecutionGraph::from_task_nodes(&nodes)
461}
462
463#[derive(Debug, Clone, Copy, PartialEq, Eq)]
464pub enum ExpiredAttemptRecovery {
465    Requeue,
466    RequireVerification,
467}
468
469impl ExpiredAttemptRecovery {
470    pub fn classify(idempotent: bool, retry_count: i32, max_retries: i32) -> Self {
471        if idempotent && retry_count < max_retries {
472            Self::Requeue
473        } else {
474            Self::RequireVerification
475        }
476    }
477}
478
479/// A stable isolation boundary for goals, runs, worker policies, and channel views.
480#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
481pub struct WorkProject {
482    pub id: String,
483    pub name: String,
484    pub description: Option<String>,
485    /// The folder the project's conversations work in, as an absolute path.
486    #[serde(default, skip_serializing_if = "Option::is_none")]
487    pub path: Option<String>,
488    pub created_at: String,
489    pub updated_at: String,
490}
491
492/// The status of a scheduled occurrence that never ran: the daemon was not
493/// running when it was due, and it was past its catch-up window when the
494/// daemon came back. A closed run, but neither a success nor a failure.
495pub const GOAL_RUN_MISSED: &str = "missed";
496
497/// One execution of a goal. Finite goals normally have one run; each scheduled
498/// firing gets a distinct run.
499#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
500pub struct GoalRun {
501    pub id: String,
502    pub project_id: String,
503    pub goal_id: String,
504    /// "finite", "scheduled", "manual", "mandate", or "legacy"
505    pub trigger_type: String,
506    pub schedule_id: Option<String>,
507    pub root_task_id: Option<String>,
508    /// "pending", "running", "completed", "failed", "blocked", "cancelled",
509    /// or [`GOAL_RUN_MISSED`]
510    pub status: String,
511    pub outcome_summary: Option<String>,
512    pub started_at: String,
513    pub completed_at: Option<String>,
514    pub created_at: String,
515    pub updated_at: String,
516}
517
518impl GoalRun {
519    pub fn new(goal_id: &str, project_id: &str, trigger_type: &str) -> Self {
520        let now = chrono::Utc::now().to_rfc3339();
521        Self {
522            id: uuid::Uuid::new_v4().to_string(),
523            project_id: project_id.to_string(),
524            goal_id: goal_id.to_string(),
525            trigger_type: trigger_type.to_string(),
526            schedule_id: None,
527            root_task_id: None,
528            // A run exists before any worker owns its root task. It becomes
529            // `running` atomically with the first successful task claim.
530            status: "pending".to_string(),
531            outcome_summary: None,
532            started_at: now.clone(),
533            completed_at: None,
534            created_at: now.clone(),
535            updated_at: now,
536        }
537    }
538}
539
540/// Durable execution policy. The profile is stable configuration; a task
541/// attempt and its worker instance remain distinct identities.
542#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
543pub struct WorkerProfile {
544    pub id: String,
545    pub project_id: Option<String>,
546    pub name: String,
547    pub specialist: String,
548    pub model: Option<String>,
549    pub tools_json: Option<String>,
550    pub max_iterations: Option<i64>,
551    pub tool_budget: Option<i64>,
552    pub timeout_secs: Option<i64>,
553    pub max_concurrency: i64,
554    /// "shared", "isolated", or "worktree"
555    pub workspace_policy: String,
556    pub memory_scope: String,
557    pub version: i64,
558    pub enabled: bool,
559    pub created_at: String,
560    pub updated_at: String,
561}
562
563/// One fenced claim of a task by one worker instance.
564#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
565pub struct TaskAttempt {
566    pub id: String,
567    pub task_id: String,
568    pub goal_run_id: String,
569    pub worker_profile_id: Option<String>,
570    pub worker_instance_id: String,
571    /// Local fencing token. It is never included in user-facing output.
572    #[serde(skip_serializing)]
573    pub lease_token: String,
574    /// "claimed", "running", "completed", "failed", "blocked", "expired",
575    /// "needs_verification", or "cancelled"
576    pub status: String,
577    pub lease_expires_at: String,
578    pub last_heartbeat_at: String,
579    pub workspace_id: Option<String>,
580    pub started_at: String,
581    pub completed_at: Option<String>,
582}
583
584#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
585pub struct HandoffArtifact {
586    /// "path", "commit", "url", "message", or another explicit artifact kind.
587    pub kind: String,
588    pub reference: String,
589    pub digest: Option<String>,
590    pub metadata: Option<String>,
591}
592
593/// Low-volume, structured output from one attempt for the next worker or human.
594#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
595pub struct TaskHandoff {
596    pub id: String,
597    pub task_id: String,
598    pub attempt_id: String,
599    pub summary: String,
600    pub artifacts: Vec<HandoffArtifact>,
601    pub verification: Vec<String>,
602    pub remaining_risk: Option<String>,
603    pub next_step: Option<String>,
604    pub created_at: String,
605}
606
607/// Append-only collaboration and audit record. Tool/LLM telemetry remains in
608/// `TaskActivity`; this journal is for durable decisions and human interaction.
609#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
610pub struct TaskJournalEntry {
611    pub id: String,
612    pub project_id: String,
613    pub goal_id: String,
614    pub goal_run_id: String,
615    pub task_id: Option<String>,
616    pub attempt_id: Option<String>,
617    /// "comment", "blocked", "unblocked", "assigned", "handoff",
618    /// "lease_lost", "workspace", or "transition"
619    pub entry_type: String,
620    /// "human", "agent", or "system"
621    pub actor_type: String,
622    pub actor_id: String,
623    pub source_channel: Option<String>,
624    pub body: String,
625    pub payload: Option<String>,
626    pub created_at: String,
627}
628
629impl TaskJournalEntry {
630    pub fn new(
631        project_id: &str,
632        goal_id: &str,
633        goal_run_id: &str,
634        entry_type: &str,
635        actor_type: &str,
636        actor_id: &str,
637        body: &str,
638    ) -> Self {
639        Self {
640            id: uuid::Uuid::new_v4().to_string(),
641            project_id: project_id.to_string(),
642            goal_id: goal_id.to_string(),
643            goal_run_id: goal_run_id.to_string(),
644            task_id: None,
645            attempt_id: None,
646            entry_type: entry_type.to_string(),
647            actor_type: actor_type.to_string(),
648            actor_id: actor_id.to_string(),
649            source_channel: None,
650            body: body.to_string(),
651            payload: None,
652            created_at: chrono::Utc::now().to_rfc3339(),
653        }
654    }
655
656    pub fn with_task(mut self, task_id: Option<&str>, attempt_id: Option<&str>) -> Self {
657        self.task_id = task_id.map(ToOwned::to_owned);
658        self.attempt_id = attempt_id.map(ToOwned::to_owned);
659        self
660    }
661
662    pub fn with_source_channel(mut self, source_channel: Option<&str>) -> Self {
663        self.source_channel = source_channel.map(ToOwned::to_owned);
664        self
665    }
666}
667
668/// Realized workspace for one attempt. Workspaces are preserved after execution
669/// until explicitly released so downstream integration can consume them.
670#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
671pub struct TaskWorkspace {
672    pub id: String,
673    pub task_id: String,
674    pub attempt_id: String,
675    pub backend_id: String,
676    pub policy: String,
677    pub root_path: String,
678    pub branch_name: Option<String>,
679    pub base_ref: Option<String>,
680    pub head_ref: Option<String>,
681    /// "active", "preserved", "released", or "failed"
682    pub status: String,
683    pub created_at: String,
684    pub released_at: Option<String>,
685}
686
687/// Attempt-scoped mutation applied only while the supplied lease is current.
688#[derive(Debug, Clone, Default)]
689pub struct TaskAttemptPatch {
690    pub status: String,
691    pub result: Option<String>,
692    pub error: Option<String>,
693    pub blocker: Option<String>,
694    pub context: Option<String>,
695    pub handoff: Option<TaskHandoff>,
696}
697
698/// Goal-level work projection used by chat and dashboard views.
699#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
700pub struct WorkGoalSummary {
701    pub project_id: String,
702    pub goal_id: String,
703    pub description: String,
704    pub goal_status: String,
705    pub run_id: Option<String>,
706    pub run_status: Option<String>,
707    pub waiting: i64,
708    pub ready: i64,
709    pub in_progress: i64,
710    pub blocked: i64,
711    pub needs_attention: i64,
712    pub done: i64,
713    pub updated_at: String,
714}
715
716/// Task-level work projection. `lane` is derived from scheduler state and is
717/// never persisted as a second status.
718#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
719pub struct WorkTaskSummary {
720    pub project_id: String,
721    pub goal_id: String,
722    pub goal_description: String,
723    pub goal_run_id: String,
724    pub task_id: String,
725    pub description: String,
726    pub status: String,
727    pub lane: String,
728    pub priority: String,
729    pub worker_profile: Option<String>,
730    pub worker_instance_id: Option<String>,
731    pub lease_expires_at: Option<String>,
732    pub blocker: Option<String>,
733    pub updated_at: String,
734}
735
736/// `TaskActivity::activity_type` of a call that changed something outside
737/// the machine (a post, a remote write, a deploy), recorded from its typed
738/// effects. The heartbeat reads it so a goal run never repeats one.
739pub const REMOTE_CHANGE_ACTIVITY: &str = "remote_change";
740
741/// A task activity log entry — records tool calls and results within a task.
742#[derive(Debug, Clone, Serialize, Deserialize)]
743#[allow(dead_code)] // Used in Phase 2; StateStore methods and SQLite impl ready
744pub struct TaskActivity {
745    pub id: i64,
746    pub task_id: String,
747    /// "tool_call", "tool_result", "llm_call", "status_change"
748    pub activity_type: String,
749    pub tool_name: Option<String>,
750    pub tool_args: Option<String>,
751    pub result: Option<String>,
752    pub success: Option<bool>,
753    pub tokens_used: Option<i64>,
754    pub created_at: String,
755}
756
757/// A queued notification awaiting delivery to the user.
758///
759/// Notifications are queued in SQLite when the originating channel is unavailable.
760/// Retention depends on priority: status updates expire after 24 hours,
761/// critical notifications persist indefinitely until delivered.
762/// A background sub-agent still running, recorded so a restart can say it
763/// was lost and a cancel can find it.
764#[derive(Debug, Clone, PartialEq)]
765pub struct BackgroundSpawn {
766    pub id: String,
767    pub session_id: String,
768    pub mission: String,
769    pub started_at: String,
770}
771
772#[derive(Debug, Clone, Serialize, Deserialize)]
773pub struct NotificationEntry {
774    pub id: String,
775    pub goal_id: String,
776    pub session_id: String,
777    /// "completed", "failed", "escalation", "progress", "stalled", "evergreen_alert", "token_alert"
778    pub notification_type: String,
779    /// "critical" (persist indefinitely) or "status_update" (expire after 24h)
780    pub priority: String,
781    pub message: String,
782    pub created_at: String,
783    pub delivered_at: Option<String>,
784    pub attempts: i32,
785    /// When this notification expires (None = never, for critical notifications)
786    pub expires_at: Option<String>,
787    /// Optional durable work item associated with this notification.
788    #[serde(default, skip_serializing_if = "Option::is_none")]
789    pub task_id: Option<String>,
790    /// Opaque token reserved for channel-native actions.
791    #[serde(default, skip_serializing_if = "Option::is_none")]
792    pub action_token: Option<String>,
793    /// The message carries content someone other than the owner wrote (a
794    /// tainted child's result): delivering it into the session taints the
795    /// turn that records it.
796    #[serde(default)]
797    pub untrusted: bool,
798}
799
800/// A notice already delivered to the owner, as a running turn sees it.
801#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
802pub struct DeliveredNotice {
803    pub id: String,
804    /// The notification type ("mandate_review_failed", "mandate_ask", ...).
805    pub notification_type: String,
806    /// The text the owner read.
807    pub message: String,
808    /// When it was delivered (RFC 3339, UTC).
809    pub delivered_at: String,
810    /// The mandate it is about, when it is about one.
811    #[serde(default, skip_serializing_if = "Option::is_none")]
812    pub mandate_id: Option<String>,
813}
814
815/// The context a turn's reply needs about notices the owner received while
816/// the turn ran: they were sent a minute before the reply arrives, so the
817/// reply must not contradict them ("I haven't seen the first review run"
818/// right after "a review failed"). `None` when there were none.
819///
820/// The host adds it to the turn before the final reply, from
821/// [`crate::traits::NotificationStore::notices_delivered_since`] with the
822/// turn's start time.
823pub fn notices_turn_context(notices: &[DeliveredNotice]) -> Option<String> {
824    if notices.is_empty() {
825        return None;
826    }
827    let mut context = String::from(
828        "[NOTICES SENT DURING THIS TURN] While you worked, the owner already received these \
829         messages. Your reply must agree with them; do not repeat them in full, and do not \
830         say something has not happened when a notice says it has.",
831    );
832    for notice in notices {
833        let at = crate::schedule::owner_time_rfc3339(&notice.delivered_at)
834            .unwrap_or_else(|| notice.delivered_at.clone());
835        context.push_str(&format!("\n- at {at} ({}", notice.notification_type));
836        if let Some(mandate_id) = notice.mandate_id.as_deref() {
837            context.push_str(&format!(", mandate_id {mandate_id}"));
838        }
839        context.push_str(&format!("): {}", notice.message.trim()));
840    }
841    Some(context)
842}
843
844impl NotificationEntry {
845    pub const DEFAULT_QUIET_HOURS_START: u32 = 22;
846    pub const DEFAULT_QUIET_HOURS_END: u32 = 7;
847
848    /// Create a new notification entry.
849    pub fn new(goal_id: &str, session_id: &str, notification_type: &str, message: &str) -> Self {
850        let now = chrono::Utc::now();
851        let priority = match notification_type {
852            "completed"
853            | "failed"
854            | "escalation"
855            | "evergreen_alert"
856            | "token_alert"
857            | "mandate_action"
858            | "mandate_ask"
859            | "mandate_alert"
860            | "mandate_ask_timeout"
861            | "mandate_stopped"
862            | "mandate_review_failed"
863            | "mandate_reconciliation"
864            | "mandate_reconciliation_required"
865            | "node_monitor_alert" => "critical",
866            _ => "status_update",
867        };
868        let expires_at = if priority == "status_update" {
869            Some((now + chrono::Duration::hours(24)).to_rfc3339())
870        } else {
871            None // critical notifications never expire
872        };
873        Self {
874            id: uuid::Uuid::new_v4().to_string(),
875            goal_id: goal_id.to_string(),
876            session_id: session_id.to_string(),
877            notification_type: notification_type.to_string(),
878            priority: priority.to_string(),
879            message: message.to_string(),
880            created_at: now.to_rfc3339(),
881            delivered_at: None,
882            attempts: 0,
883            expires_at,
884            task_id: None,
885            action_token: None,
886            untrusted: false,
887        }
888    }
889
890    /// Mark the message as carrying untrusted content.
891    pub fn with_untrusted(mut self, untrusted: bool) -> Self {
892        self.untrusted = untrusted;
893        self
894    }
895
896    pub fn with_task(mut self, task_id: &str) -> Self {
897        self.task_id = Some(task_id.to_string());
898        self.action_token = Some(uuid::Uuid::new_v4().to_string());
899        self
900    }
901
902    /// Whether this notification represents a condition that genuinely needs
903    /// immediate owner attention instead of routine autonomous handling.
904    pub fn interrupts_quiet_hours(&self) -> bool {
905        matches!(
906            self.notification_type.as_str(),
907            "mandate_ask"
908                | "mandate_alert"
909                | "mandate_reconciliation_required"
910                | "escalation"
911                | "node_monitor_alert"
912        )
913    }
914
915    pub fn should_deliver_at_local_hour(&self, hour: u32) -> bool {
916        Self::routine_delivery_allowed_at_local_hour(hour) || self.interrupts_quiet_hours()
917    }
918
919    pub fn routine_delivery_allowed_at_local_hour(hour: u32) -> bool {
920        (Self::DEFAULT_QUIET_HOURS_END..Self::DEFAULT_QUIET_HOURS_START).contains(&hour)
921    }
922}
923
924/// A task status is "terminal" when it will never advance to `completed` on its
925/// own — either it already succeeded (`completed`/`skipped`), was explicitly
926/// replaced (`superseded`), or it is dead
927/// (`failed`/`blocked`/`interrupted`/`cancelled`/`abandoned`). Terminal tasks
928/// are useful when deciding whether a scheduler can make further progress.
929/// Terminal does not imply successful: strict finite/current-run completion
930/// separately requires [`Task::satisfies_run_completion`].
931pub fn is_terminal_task_status(status: &str) -> bool {
932    matches!(
933        status,
934        "completed"
935            | "skipped"
936            | "superseded"
937            | "failed"
938            | "blocked"
939            | "interrupted"
940            | "cancelled"
941            | "abandoned"
942    )
943}
944
945/// Whether every task of a run completed it (and there is at least one).
946pub fn tasks_satisfy_goal_completion(tasks: &[Task]) -> bool {
947    !tasks.is_empty() && tasks.iter().all(Task::satisfies_run_completion)
948}
949
950#[cfg(test)]
951mod notification_attention_tests {
952    use super::NotificationEntry;
953
954    #[test]
955    fn recoverable_failures_wait_during_quiet_hours() {
956        let failed = NotificationEntry::new("goal", "session", "failed", "retry exhausted");
957        assert!(!failed.should_deliver_at_local_hour(2));
958        assert!(failed.should_deliver_at_local_hour(9));
959    }
960
961    #[test]
962    fn owner_action_requests_interrupt_quiet_hours() {
963        for kind in [
964            "mandate_ask",
965            "mandate_reconciliation_required",
966            "escalation",
967        ] {
968            let entry = NotificationEntry::new("goal", "session", kind, "owner action needed");
969            assert!(entry.should_deliver_at_local_hour(2));
970        }
971    }
972
973    #[test]
974    fn token_pressure_is_recoverable_not_an_owner_interrupt() {
975        let entry = NotificationEntry::new("goal", "session", "token_alert", "adapt budget");
976        assert!(!entry.should_deliver_at_local_hour(2));
977    }
978}