Skip to main content

aidaemon_work/
stores.rs

1//! The store traits for goals, mandates, tasks, work and notifications.
2
3use aidaemon_tools::services::SettingsStore;
4use async_trait::async_trait;
5
6/// Goal lifecycle and confirmation-flow persistence. Task, schedule, budget,
7/// scheduled-run, dispatch, and notification concerns live in the sibling
8/// traits: [`TaskStore`], [`GoalScheduleStore`], [`GoalBudgetStore`],
9/// [`ScheduledRunStore`], [`TaskDispatchStore`], and [`GoalNotificationStore`].
10#[async_trait]
11pub trait GoalStore: Send + Sync {
12    /// Create a new goal.
13    async fn create_goal(&self, _goal: &crate::traits::Goal) -> anyhow::Result<()> {
14        Ok(())
15    }
16
17    /// Get a goal by ID.
18    async fn get_goal(&self, _id: &str) -> anyhow::Result<Option<crate::traits::Goal>> {
19        Ok(None)
20    }
21
22    /// Update a goal (full replacement).
23    async fn update_goal(&self, _goal: &crate::traits::Goal) -> anyhow::Result<()> {
24        Ok(())
25    }
26
27    /// Get all active orchestration goals (status = "active" or "pending").
28    async fn get_active_goals(&self) -> anyhow::Result<Vec<crate::traits::Goal>> {
29        Ok(vec![])
30    }
31
32    /// Get active personal goals (tracked, never dispatched).
33    async fn get_active_personal_goals(
34        &self,
35        _limit: i64,
36    ) -> anyhow::Result<Vec<crate::traits::Goal>> {
37        Ok(vec![])
38    }
39
40    /// Update a personal goal's status and/or append a progress note.
41    async fn update_personal_goal(
42        &self,
43        _goal_id: &str,
44        _status: Option<&str>,
45        _progress_note: Option<&str>,
46    ) -> anyhow::Result<()> {
47        Ok(())
48    }
49
50    /// Get orchestration goals for a specific session.
51    async fn get_goals_for_session(
52        &self,
53        _session_id: &str,
54    ) -> anyhow::Result<Vec<crate::traits::Goal>> {
55        Ok(vec![])
56    }
57
58    /// Get scheduled goals awaiting confirmation in a session.
59    async fn get_pending_confirmation_goals(
60        &self,
61        _session_id: &str,
62    ) -> anyhow::Result<Vec<crate::traits::Goal>> {
63        Ok(vec![])
64    }
65
66    /// Activate a pending-confirmation goal.
67    /// Returns true when the status transition was applied.
68    async fn activate_goal(&self, _goal_id: &str) -> anyhow::Result<bool> {
69        Ok(false)
70    }
71}
72
73/// Owner mandates, agent deliberation cycles, and intentions.
74#[async_trait]
75pub trait MandateStore: Send + Sync {
76    /// Atomically create the continuous controller goal and its mandate.
77    /// Adaptive review timing lives on the mandate, not in `goal_schedules`.
78    async fn create_mandate_controller(
79        &self,
80        _goal: &crate::traits::Goal,
81        _mandate: &crate::traits::Mandate,
82    ) -> anyhow::Result<()> {
83        anyhow::bail!("mandate controllers are not supported by this store")
84    }
85
86    async fn get_mandate(&self, _id: &str) -> anyhow::Result<Option<crate::traits::Mandate>> {
87        Ok(None)
88    }
89
90    async fn get_mandate_for_goal(
91        &self,
92        _goal_id: &str,
93    ) -> anyhow::Result<Option<crate::traits::Mandate>> {
94        Ok(None)
95    }
96
97    async fn list_mandates(
98        &self,
99        _session_id: Option<&str>,
100        _include_terminal: bool,
101    ) -> anyhow::Result<Vec<crate::traits::Mandate>> {
102        Ok(Vec::new())
103    }
104
105    /// Authorize one exact presentation session through the mandate's stable
106    /// principal mapping. Session-string similarity is never sufficient.
107    async fn is_mandate_session_authorized(
108        &self,
109        _mandate_id: &str,
110        _session_id: &str,
111    ) -> anyhow::Result<bool> {
112        Ok(false)
113    }
114
115    /// Append one receipt-backed metric observation for the exact current
116    /// mandate run and policy version.
117    async fn record_mandate_objective_measurement(
118        &self,
119        _measurement: &crate::traits::MandateObjectiveMeasurement,
120    ) -> anyhow::Result<()> {
121        anyhow::bail!("mandate objective measurements are not supported by this store")
122    }
123
124    async fn list_mandate_objective_measurements(
125        &self,
126        _mandate_id: &str,
127        _limit: i64,
128    ) -> anyhow::Result<Vec<crate::traits::MandateObjectiveMeasurement>> {
129        Ok(Vec::new())
130    }
131
132    /// Optimistic owner-policy update. `mandate.version` must be exactly one
133    /// greater than the currently stored version.
134    async fn update_mandate(&self, _mandate: &crate::traits::Mandate) -> anyhow::Result<()> {
135        anyhow::bail!("mandates are not supported by this store")
136    }
137
138    /// Atomically consume an explicit owner confirmation and activate both the
139    /// mandate and its continuous controller. This is the only path that may
140    /// turn an unconfirmed mandate into active authority.
141    async fn confirm_mandate(
142        &self,
143        _mandate_id: &str,
144        _expected_version: i64,
145        _activation_duration_secs: Option<i64>,
146    ) -> anyhow::Result<bool> {
147        Ok(false)
148    }
149
150    /// Atomic lifecycle/authority-epoch transition. Implementations must
151    /// invalidate open decision runs and stale ACT authority before returning.
152    async fn transition_mandate_status(
153        &self,
154        _mandate_id: &str,
155        _from_status: crate::traits::MandateStatus,
156        _to_status: crate::traits::MandateStatus,
157    ) -> anyhow::Result<bool> {
158        Ok(false)
159    }
160
161    /// Resume a paused/awaiting-input mandate and update its controller
162    /// context in the same expected-version transaction. This prevents owner
163    /// guidance from overwriting a concurrent cancel/pause lifecycle state.
164    async fn resume_mandate_with_context(
165        &self,
166        _mandate_id: &str,
167        _from_status: crate::traits::MandateStatus,
168        _expected_version: i64,
169        _controller_context: Option<&str>,
170    ) -> anyhow::Result<bool> {
171        Ok(false)
172    }
173
174    /// Record a late owner answer on an active mandate by replacing its
175    /// controller context, fenced on the mandate still being active at the
176    /// expected version for this owner. Authority is never touched.
177    async fn record_active_mandate_owner_guidance(
178        &self,
179        _mandate_id: &str,
180        _expected_version: i64,
181        _owner_session: &str,
182        _controller_context: &str,
183    ) -> anyhow::Result<bool> {
184        Ok(false)
185    }
186
187    /// Atomically create one mandate review run and its root task under the
188    /// caller's current review lease. A failed root insert must
189    /// leave no open run behind.
190    async fn create_mandate_review_run(
191        &self,
192        _mandate_id: &str,
193        _review_lease_token: &str,
194        _goal_run_id: &str,
195        _root_task: &crate::traits::Task,
196    ) -> anyhow::Result<crate::traits::GoalRun> {
197        anyhow::bail!("mandate review runs are not supported by this store")
198    }
199
200    /// Repair controller runtime state only while the exact mandate authority
201    /// epoch is still active. The state check and goal update must be one
202    /// atomic database statement so a racing owner pause/cancel wins.
203    async fn keep_mandate_controller_active(
204        &self,
205        _mandate_id: &str,
206        _expected_version: i64,
207    ) -> anyhow::Result<bool> {
208        Ok(false)
209    }
210
211    /// Claim due reviews with a durable lease. Concurrent callers must never
212    /// receive the same mandate before the lease expires.
213    async fn claim_due_mandates(
214        &self,
215        _limit: i64,
216        _lease_owner: &str,
217        _lease_secs: i64,
218    ) -> anyhow::Result<Vec<crate::traits::Mandate>> {
219        Ok(Vec::new())
220    }
221
222    async fn release_mandate_review_lease(
223        &self,
224        _mandate_id: &str,
225        _lease_token: &str,
226        _retry_at: &str,
227    ) -> anyhow::Result<bool> {
228        Ok(false)
229    }
230
231    /// Insert one non-root action task into an exact mandate run while the
232    /// dispatcher-owned root attempt remains current. Implementations must
233    /// validate the mandate/run/attempt fence and task cap atomically and must
234    /// never create or rebind a goal run by goal id.
235    async fn create_mandate_task_from_attempt(
236        &self,
237        _task: &crate::traits::Task,
238        _mandate_id: &str,
239        _mandate_version: i64,
240        _goal_run_id: &str,
241        _root_task_attempt_id: &str,
242        _max_non_root_tasks: i64,
243    ) -> anyhow::Result<bool> {
244        Ok(false)
245    }
246
247    /// Claim one pending non-root task inside an exact running mandate cycle.
248    /// The root task-attempt remains the control-plane lease; the returned
249    /// child attempt deliberately carries no worker-profile/workspace binding.
250    /// The independently fenced identifiers remain explicit because wrapping
251    /// them would churn the stable store API without reducing validation work.
252    #[allow(clippy::too_many_arguments)]
253    async fn claim_mandate_task_from_attempt(
254        &self,
255        _task_id: &str,
256        _worker_instance_id: &str,
257        _mandate_id: &str,
258        _mandate_version: i64,
259        _goal_run_id: &str,
260        _root_task_attempt_id: &str,
261        _lease_secs: i64,
262    ) -> anyhow::Result<Option<crate::traits::TaskAttempt>> {
263        Ok(None)
264    }
265
266    /// Insert exactly one deliberation result for a goal run, plus its ACT
267    /// intention when present. Implementations must commit both atomically.
268    async fn record_mandate_decision(
269        &self,
270        _decision: &crate::traits::MandateDecisionCycle,
271        _intention: Option<&crate::traits::Intention>,
272        _task_attempt_id: Option<&str>,
273    ) -> anyhow::Result<()> {
274        anyhow::bail!("mandate decisions are not supported by this store")
275    }
276
277    async fn record_mandate_decision_with_updates(
278        &self,
279        decision: &crate::traits::MandateDecisionCycle,
280        intention: Option<&crate::traits::Intention>,
281        operating_updates: Option<&crate::traits::MandateOperatingUpdates>,
282        task_attempt_id: Option<&str>,
283    ) -> anyhow::Result<()> {
284        anyhow::ensure!(
285            operating_updates.is_none_or(
286                |updates| updates.learning_note.is_none() && updates.action_outcomes.is_empty()
287            ),
288            "adaptive mandate operating updates are not supported by this store"
289        );
290        self.record_mandate_decision(decision, intention, task_attempt_id)
291            .await
292    }
293
294    async fn get_mandate_decision_for_run(
295        &self,
296        _goal_run_id: &str,
297    ) -> anyhow::Result<Option<crate::traits::MandateDecisionCycle>> {
298        Ok(None)
299    }
300
301    /// Tool-call ids of the run's successful structured receipts that may
302    /// back a decision or measurement (newest first, at most `limit`): the
303    /// same receipts `evidence_receipt_ids` accepts, minus the mandate
304    /// protocol's own control tools.
305    async fn current_run_evidence_receipt_ids(
306        &self,
307        _goal_run_id: &str,
308        _limit: usize,
309    ) -> anyhow::Result<Vec<String>> {
310        Ok(Vec::new())
311    }
312
313    async fn list_mandate_decisions(
314        &self,
315        _mandate_id: &str,
316        _limit: i64,
317    ) -> anyhow::Result<Vec<crate::traits::MandateDecisionCycle>> {
318        Ok(Vec::new())
319    }
320
321    async fn list_intentions(
322        &self,
323        _mandate_id: &str,
324        _limit: i64,
325    ) -> anyhow::Result<Vec<crate::traits::Intention>> {
326        Ok(Vec::new())
327    }
328
329    /// Persist one bounded, advisory learning note only after all cited
330    /// receipts are proven to belong to this mandate.
331    async fn record_mandate_learning_note(
332        &self,
333        _note: &crate::traits::MandateLearningNote,
334    ) -> anyhow::Result<()> {
335        anyhow::bail!("mandate learning is not supported by this store")
336    }
337
338    async fn list_mandate_learning_notes(
339        &self,
340        _mandate_id: &str,
341        _limit: i64,
342    ) -> anyhow::Result<Vec<crate::traits::MandateLearningNote>> {
343        Ok(Vec::new())
344    }
345
346    /// The most recent per-action outcomes of a mandate, newest first.
347    async fn list_mandate_action_outcomes(
348        &self,
349        _mandate_id: &str,
350        _limit: i64,
351    ) -> anyhow::Result<Vec<crate::traits::MandateActionOutcome>> {
352        Ok(Vec::new())
353    }
354
355    /// Deduplicate and route one content-free external signal to matching
356    /// Autopilot mandates. Matching is structural and cannot widen authority.
357    async fn wake_mandates_for_signal(
358        &self,
359        _signal: &crate::traits::MandateWakeSignal,
360    ) -> anyhow::Result<Vec<String>> {
361        Ok(Vec::new())
362    }
363
364    /// Resolve an awaiting-input state with a typed owner action. Question
365    /// answers and external-effect reconciliation are intentionally distinct.
366    #[allow(clippy::too_many_arguments)]
367    async fn resolve_mandate_suspension(
368        &self,
369        _mandate_id: &str,
370        _expected_version: i64,
371        _expected_kind: crate::traits::MandateSuspensionKind,
372        _controller_context: Option<&str>,
373        _reconciliation_resolution: Option<crate::traits::MandateReconciliationResolution>,
374        _owner_guidance: &str,
375        _owner_session: &str,
376    ) -> anyhow::Result<bool> {
377        Ok(false)
378    }
379
380    /// Atomically reserve the exact next mutation attempt under the current
381    /// cycle, rolling-24h, cooldown, mandate, run, intention, task, and lease
382    /// fences. Implementations must insert the durable ledger row and advance
383    /// the cycle counter in one transaction.
384    async fn reserve_mandate_action_attempt(
385        &self,
386        _reservation: &crate::traits::MandateMutationReservation,
387    ) -> anyhow::Result<Option<crate::traits::MandateMutationAttempt>> {
388        Ok(None)
389    }
390
391    /// Atomically claim one exact reserved mutation at the last common
392    /// dispatcher. A claim is one-use and must fail if any authority, run,
393    /// task-attempt, tool-call, digest, or reservation field is stale.
394    async fn claim_mandate_mutation_dispatch(
395        &self,
396        _claim: &crate::traits::MandateMutationDispatchClaim,
397    ) -> anyhow::Result<bool> {
398        Ok(false)
399    }
400
401    /// Read the typed, cross-cycle mutation quota projection at one instant.
402    /// This is advisory for deliberation; reservation remains authoritative.
403    async fn get_mandate_mutation_quota_state(
404        &self,
405        _mandate_id: &str,
406        _as_of: &str,
407    ) -> anyhow::Result<Option<crate::traits::MandateMutationQuotaState>> {
408        Ok(None)
409    }
410
411    async fn list_mandate_mutation_attempts_for_run(
412        &self,
413        _goal_run_id: &str,
414    ) -> anyhow::Result<Vec<crate::traits::MandateMutationAttempt>> {
415        Ok(Vec::new())
416    }
417
418    /// Atomically prove and close a mandate run. Satisfied outcomes close the
419    /// goal run (and ACT intention) inside the proof transaction; reconciliation
420    /// results leave lifecycle state untouched for the caller's explicit path.
421    async fn finalize_mandate_run_from_proof(
422        &self,
423        _request: &crate::traits::MandateRunFinalizationRequest,
424    ) -> anyhow::Result<crate::traits::MandateRunFinalizationResult> {
425        Ok(crate::traits::MandateRunFinalizationResult::Rejected {
426            reason: crate::traits::MandateFinalizationRejectReason::InvalidRequest,
427        })
428    }
429}
430
431/// Task persistence and task activity logs.
432#[async_trait]
433pub trait TaskStore: Send + Sync {
434    /// Create a new task within a goal.
435    async fn create_task(&self, _task: &crate::traits::Task) -> anyhow::Result<()> {
436        Ok(())
437    }
438
439    /// Get a task by ID.
440    async fn get_task(&self, _id: &str) -> anyhow::Result<Option<crate::traits::Task>> {
441        Ok(None)
442    }
443
444    /// Update a task (full replacement).
445    async fn update_task(&self, _task: &crate::traits::Task) -> anyhow::Result<()> {
446        Ok(())
447    }
448
449    /// Get all tasks for a goal.
450    async fn get_tasks_for_goal(&self, _goal_id: &str) -> anyhow::Result<Vec<crate::traits::Task>> {
451        Ok(vec![])
452    }
453
454    /// Count completed/skipped tasks for a goal (used by progress-based circuit breaker).
455    async fn count_completed_tasks_for_goal(&self, _goal_id: &str) -> anyhow::Result<i64> {
456        Ok(0)
457    }
458
459    /// Atomically claim a pending task for an executor.
460    async fn claim_task(&self, _task_id: &str, _agent_id: &str) -> anyhow::Result<bool> {
461        Ok(false)
462    }
463
464    /// Log an activity entry for a task.
465    async fn log_task_activity(
466        &self,
467        _activity: &crate::traits::TaskActivity,
468    ) -> anyhow::Result<()> {
469        Ok(())
470    }
471
472    /// Get activity log for a task.
473    async fn get_task_activities(
474        &self,
475        _task_id: &str,
476    ) -> anyhow::Result<Vec<crate::traits::TaskActivity>> {
477        Ok(vec![])
478    }
479}
480
481/// Goal schedule and scheduled-run persistence.
482#[async_trait]
483pub trait GoalScheduleStore: Send + Sync {
484    /// Create a new schedule for a goal.
485    async fn create_goal_schedule(
486        &self,
487        _schedule: &crate::traits::GoalSchedule,
488    ) -> anyhow::Result<()> {
489        Ok(())
490    }
491
492    /// Get a schedule by ID.
493    async fn get_goal_schedule(
494        &self,
495        _schedule_id: &str,
496    ) -> anyhow::Result<Option<crate::traits::GoalSchedule>> {
497        Ok(None)
498    }
499
500    /// List schedules for a goal.
501    async fn get_schedules_for_goal(
502        &self,
503        _goal_id: &str,
504    ) -> anyhow::Result<Vec<crate::traits::GoalSchedule>> {
505        Ok(vec![])
506    }
507
508    /// Get due schedules for active orchestration goals.
509    async fn get_due_goal_schedules(
510        &self,
511        _limit: i64,
512    ) -> anyhow::Result<Vec<crate::traits::GoalSchedule>> {
513        Ok(vec![])
514    }
515
516    /// Update a schedule (full replacement).
517    async fn update_goal_schedule(
518        &self,
519        _schedule: &crate::traits::GoalSchedule,
520    ) -> anyhow::Result<()> {
521        Ok(())
522    }
523
524    /// Delete a schedule by ID. Returns true if a row was deleted.
525    async fn delete_goal_schedule(&self, _schedule_id: &str) -> anyhow::Result<bool> {
526        Ok(false)
527    }
528
529    /// Cancel pending-confirmation goals older than max_age_secs.
530    async fn cancel_stale_pending_confirmation_goals(
531        &self,
532        _max_age_secs: i64,
533    ) -> anyhow::Result<u64> {
534        Ok(0)
535    }
536
537    /// Get all orchestration goals that have schedules or are awaiting confirmation.
538    async fn get_scheduled_goals(&self) -> anyhow::Result<Vec<crate::traits::Goal>> {
539        Ok(vec![])
540    }
541
542    /// Active continuous orchestration goals with no schedule and no mandate
543    /// behind them: nothing will ever run them. Listed so they can be seen
544    /// and cancelled.
545    async fn get_unscheduled_active_goals(&self) -> anyhow::Result<Vec<crate::traits::Goal>> {
546        Ok(vec![])
547    }
548}
549
550/// Goal token budget persistence and accounting.
551#[async_trait]
552pub trait GoalBudgetStore: Send + Sync {
553    /// Reset tokens_used_today only for active goals whose usage belongs to a
554    /// prior UTC day. Safe to call repeatedly or at process startup.
555    async fn reset_daily_token_budgets(&self) -> anyhow::Result<u64> {
556        Ok(0)
557    }
558
559    /// Update budget columns only. `None` = keep current value (COALESCE), NOT "clear to NULL".
560    /// This is a targeted UPDATE that avoids the race with `add_goal_tokens_and_get_budget_status()`
561    /// which atomically increments `tokens_used_today` — a full `update_goal()` would clobber that.
562    async fn set_goal_budgets(
563        &self,
564        _goal_id: &str,
565        _budget_per_check: Option<i64>,
566        _budget_daily: Option<i64>,
567    ) -> anyhow::Result<()> {
568        Ok(())
569    }
570
571    /// Atomically add tokens to a goal's daily usage counter and return budget status.
572    ///
573    /// Use `delta_tokens = 0` to read the latest counters without modifying them.
574    async fn add_goal_tokens_and_get_budget_status(
575        &self,
576        _goal_id: &str,
577        _delta_tokens: i64,
578    ) -> anyhow::Result<Option<crate::traits::GoalTokenBudgetStatus>> {
579        Ok(None)
580    }
581}
582
583/// Scheduled run runtime-state persistence.
584#[async_trait]
585pub trait ScheduledRunStore: Send + Sync {
586    /// Persist runtime state for an active scheduled run.
587    async fn upsert_scheduled_run_state(
588        &self,
589        _state: &crate::traits::ScheduledRunState,
590    ) -> anyhow::Result<()> {
591        Ok(())
592    }
593
594    /// Load persisted runtime state for an active scheduled run.
595    async fn get_scheduled_run_state(
596        &self,
597        _goal_id: &str,
598    ) -> anyhow::Result<Option<crate::traits::ScheduledRunState>> {
599        Ok(None)
600    }
601
602    async fn get_scheduled_recovery_state(
603        &self,
604        _goal_id: &str,
605    ) -> anyhow::Result<Option<crate::traits::ScheduledRecoveryState>> {
606        Ok(None)
607    }
608
609    /// Escalated scheduled objectives that the recovery machine itself paused,
610    /// whose cool-down has elapsed and whose automatic recovery attempts are
611    /// still under the cap.
612    async fn list_escalated_recovery_candidates(
613        &self,
614        _cooldown_secs: i64,
615        _max_attempts: u16,
616    ) -> anyhow::Result<Vec<crate::traits::ScheduledRecoveryState>> {
617        Ok(Vec::new())
618    }
619
620    /// Record that an automatic recovery run was launched for the goal.
621    async fn record_scheduled_recovery_attempt(&self, _goal_id: &str) -> anyhow::Result<()> {
622        Ok(())
623    }
624
625    /// Delete persisted runtime state for an active scheduled run.
626    async fn delete_scheduled_run_state(&self, _goal_id: &str) -> anyhow::Result<bool> {
627        Ok(false)
628    }
629}
630
631/// Task dispatch bookkeeping for executor scheduling and recovery.
632#[async_trait]
633pub trait TaskDispatchStore: Send + Sync {
634    /// Get pending tasks ordered by priority, filtering out those with unmet dependencies.
635    async fn get_pending_tasks_by_priority(
636        &self,
637        _limit: i64,
638    ) -> anyhow::Result<Vec<crate::traits::Task>> {
639        Ok(vec![])
640    }
641
642    /// Get tasks stuck in running/claimed state longer than timeout_secs.
643    async fn get_stuck_tasks(
644        &self,
645        _timeout_secs: i64,
646    ) -> anyhow::Result<Vec<crate::traits::Task>> {
647        Ok(vec![])
648    }
649
650    /// Get tasks completed after a given timestamp.
651    async fn get_recently_completed_tasks(
652        &self,
653        _since: &str,
654    ) -> anyhow::Result<Vec<crate::traits::Task>> {
655        Ok(vec![])
656    }
657
658    /// Mark a running/claimed task as interrupted (e.g., after crash or timeout).
659    async fn mark_task_interrupted(&self, _task_id: &str) -> anyhow::Result<bool> {
660        Ok(false)
661    }
662}
663
664/// Durable coordination for goal runs, fenced task attempts, collaboration
665/// records, named worker policies, project scope, and attempt workspaces.
666#[async_trait]
667pub trait WorkCoordinationStore: Send + Sync {
668    async fn create_work_project(
669        &self,
670        _name: &str,
671        _description: Option<&str>,
672    ) -> anyhow::Result<crate::traits::WorkProject> {
673        anyhow::bail!("work projects are not supported by this store")
674    }
675
676    async fn list_work_projects(&self) -> anyhow::Result<Vec<crate::traits::WorkProject>> {
677        Ok(vec![])
678    }
679
680    async fn get_session_work_project(&self, _session_id: &str) -> anyhow::Result<String> {
681        Ok(crate::traits::DEFAULT_PROJECT_ID.to_string())
682    }
683
684    /// Rename a project or change its folder (`Some(None)` clears it).
685    /// `None` when there is no such project.
686    async fn update_work_project(
687        &self,
688        _id: &str,
689        _name: Option<&str>,
690        _path: Option<Option<&str>>,
691    ) -> anyhow::Result<Option<crate::traits::WorkProject>> {
692        anyhow::bail!("work projects are not supported by this store")
693    }
694
695    /// Delete a project: its sessions, goals, runs and journal move to the
696    /// default project, its bots to none, and its worker profiles go with
697    /// it. `false` when there is no such project; the default one cannot
698    /// be deleted.
699    async fn delete_work_project(&self, _id: &str) -> anyhow::Result<bool> {
700        anyhow::bail!("work projects are not supported by this store")
701    }
702
703    /// Every session placed in a project other than the default one, with
704    /// its project id.
705    async fn session_work_projects(&self) -> anyhow::Result<Vec<(String, String)>> {
706        Ok(vec![])
707    }
708
709    async fn set_session_work_project(
710        &self,
711        _session_id: &str,
712        _project_id: &str,
713    ) -> anyhow::Result<bool> {
714        Ok(false)
715    }
716
717    /// Every chat bot sending its direct-message chats to a project: (bot
718    /// channel, project id).
719    async fn channel_work_projects(&self) -> anyhow::Result<Vec<(String, String)>> {
720        Ok(vec![])
721    }
722
723    /// Send bot `channel`'s direct-message chats to `project_id`, or to no
724    /// project (`None`). `false` when there is no such project.
725    async fn set_channel_work_project(
726        &self,
727        _channel: &str,
728        _project_id: Option<&str>,
729    ) -> anyhow::Result<bool> {
730        Ok(false)
731    }
732
733    /// Place a direct-message chat of bot `channel` in that bot's project,
734    /// when the chat was never placed (taking a chat out of its project
735    /// places it in the default one, so that stays). Returns whether it
736    /// was placed now.
737    async fn place_chat_by_channel(
738        &self,
739        _session_id: &str,
740        _channel: &str,
741    ) -> anyhow::Result<bool> {
742        Ok(false)
743    }
744
745    async fn start_goal_run(
746        &self,
747        _goal_id: &str,
748        _trigger_type: &str,
749        _schedule_id: Option<&str>,
750        _root_task_id: Option<&str>,
751    ) -> anyhow::Result<crate::traits::GoalRun> {
752        anyhow::bail!("goal runs are not supported by this store")
753    }
754
755    /// Record an occurrence the scheduler skipped (the daemon was not
756    /// running and it is past its catch-up window) as a closed run with
757    /// status `missed`, started at the time it was due. It is part of the
758    /// automation's history, but never goes through [`Self::finish_goal_run`]:
759    /// a miss is not a failure and leaves the failure budget as it was.
760    async fn record_missed_goal_run(
761        &self,
762        _goal_id: &str,
763        _schedule_id: Option<&str>,
764        _due_at: &str,
765        _summary: &str,
766    ) -> anyhow::Result<crate::traits::GoalRun> {
767        anyhow::bail!("goal runs are not supported by this store")
768    }
769
770    async fn get_current_goal_run(
771        &self,
772        _goal_id: &str,
773    ) -> anyhow::Result<Option<crate::traits::GoalRun>> {
774        Ok(None)
775    }
776
777    async fn get_goal_runs(&self, _goal_id: &str) -> anyhow::Result<Vec<crate::traits::GoalRun>> {
778        Ok(vec![])
779    }
780
781    /// Typed lifecycle owner for a task. Callers must use this relationship,
782    /// never infer run provenance from the task description.
783    async fn get_goal_run_for_task(
784        &self,
785        _task_id: &str,
786    ) -> anyhow::Result<Option<crate::traits::GoalRun>> {
787        Ok(None)
788    }
789
790    async fn get_tasks_for_goal_run(
791        &self,
792        _run_id: &str,
793    ) -> anyhow::Result<Vec<crate::traits::Task>> {
794        Ok(vec![])
795    }
796
797    async fn finish_goal_run(
798        &self,
799        _run_id: &str,
800        _status: &str,
801        _summary: Option<&str>,
802    ) -> anyhow::Result<bool> {
803        Ok(false)
804    }
805
806    async fn claim_task_with_lease(
807        &self,
808        _task_id: &str,
809        _worker_instance_id: &str,
810        _worker_profile_id: Option<&str>,
811        _lease_secs: i64,
812    ) -> anyhow::Result<Option<crate::traits::TaskAttempt>> {
813        Ok(None)
814    }
815
816    async fn get_current_task_attempt(
817        &self,
818        _task_id: &str,
819    ) -> anyhow::Result<Option<crate::traits::TaskAttempt>> {
820        Ok(None)
821    }
822
823    async fn bind_task_attempt_worker(
824        &self,
825        _attempt_id: &str,
826        _lease_token: &str,
827        _worker_instance_id: &str,
828        _worker_profile_id: Option<&str>,
829    ) -> anyhow::Result<bool> {
830        Ok(false)
831    }
832
833    async fn heartbeat_task_attempt(
834        &self,
835        _attempt_id: &str,
836        _lease_token: &str,
837        _lease_secs: i64,
838    ) -> anyhow::Result<bool> {
839        Ok(false)
840    }
841
842    async fn patch_task_from_attempt(
843        &self,
844        _attempt_id: &str,
845        _lease_token: &str,
846        _patch: &crate::traits::TaskAttemptPatch,
847    ) -> anyhow::Result<bool> {
848        Ok(false)
849    }
850
851    /// Expire elapsed leases and return the affected task IDs. Idempotent tasks
852    /// with retry budget are re-queued; ambiguous writes require verification.
853    async fn recover_expired_task_attempts(&self) -> anyhow::Result<Vec<String>> {
854        Ok(vec![])
855    }
856
857    /// Whether any worker still holds an unexpired execution lease on an
858    /// attempt belonging to this goal run. While one does, that worker owns
859    /// the run's outcome; lifecycle reconciliation must not race it.
860    async fn goal_run_has_live_attempt(&self, _run_id: &str) -> anyhow::Result<bool> {
861        Ok(false)
862    }
863
864    async fn append_task_journal(
865        &self,
866        _entry: &crate::traits::TaskJournalEntry,
867    ) -> anyhow::Result<()> {
868        Ok(())
869    }
870
871    async fn get_task_journal(
872        &self,
873        _task_id: &str,
874        _limit: i64,
875    ) -> anyhow::Result<Vec<crate::traits::TaskJournalEntry>> {
876        Ok(vec![])
877    }
878
879    async fn unblock_task(
880        &self,
881        _task_id: &str,
882        _resolution: &str,
883        _actor_id: &str,
884        _source_channel: Option<&str>,
885    ) -> anyhow::Result<bool> {
886        Ok(false)
887    }
888
889    async fn retry_work_task(
890        &self,
891        _task_id: &str,
892        _actor_id: &str,
893        _source_channel: Option<&str>,
894    ) -> anyhow::Result<bool> {
895        Ok(false)
896    }
897
898    async fn cancel_work_task(
899        &self,
900        _task_id: &str,
901        _actor_id: &str,
902        _source_channel: Option<&str>,
903    ) -> anyhow::Result<bool> {
904        Ok(false)
905    }
906
907    async fn upsert_worker_profile(
908        &self,
909        _profile: &crate::traits::WorkerProfile,
910    ) -> anyhow::Result<()> {
911        Ok(())
912    }
913
914    async fn get_worker_profile(
915        &self,
916        _profile_id: &str,
917    ) -> anyhow::Result<Option<crate::traits::WorkerProfile>> {
918        Ok(None)
919    }
920
921    async fn list_worker_profiles(
922        &self,
923        _project_id: Option<&str>,
924    ) -> anyhow::Result<Vec<crate::traits::WorkerProfile>> {
925        Ok(vec![])
926    }
927
928    async fn assign_task_worker_profile(
929        &self,
930        _task_id: &str,
931        _profile_id: &str,
932        _actor_id: &str,
933        _source_channel: Option<&str>,
934    ) -> anyhow::Result<bool> {
935        Ok(false)
936    }
937
938    async fn set_task_workspace_policy(
939        &self,
940        _task_id: &str,
941        _policy: &str,
942    ) -> anyhow::Result<bool> {
943        Ok(false)
944    }
945
946    async fn get_task_workspace_policy(&self, _task_id: &str) -> anyhow::Result<String> {
947        Ok("shared".to_string())
948    }
949
950    /// Whether the task's workspace policy was set on the task itself
951    /// (`set_task_workspace_policy`), rather than defaulted or inherited
952    /// from its worker profile.
953    async fn task_workspace_policy_is_explicit(&self, _task_id: &str) -> anyhow::Result<bool> {
954        Ok(false)
955    }
956
957    async fn create_task_workspace(
958        &self,
959        _workspace: &crate::traits::TaskWorkspace,
960    ) -> anyhow::Result<()> {
961        Ok(())
962    }
963
964    async fn update_task_workspace(
965        &self,
966        _workspace: &crate::traits::TaskWorkspace,
967    ) -> anyhow::Result<()> {
968        Ok(())
969    }
970
971    async fn get_task_workspace(
972        &self,
973        _task_id: &str,
974    ) -> anyhow::Result<Option<crate::traits::TaskWorkspace>> {
975        Ok(None)
976    }
977
978    async fn get_latest_task_handoff(
979        &self,
980        _task_id: &str,
981    ) -> anyhow::Result<Option<crate::traits::TaskHandoff>> {
982        Ok(None)
983    }
984
985    async fn list_work_goals(
986        &self,
987        _project_id: &str,
988        _include_terminal: bool,
989        _limit: i64,
990    ) -> anyhow::Result<Vec<crate::traits::WorkGoalSummary>> {
991        Ok(vec![])
992    }
993
994    async fn list_work_tasks(
995        &self,
996        _project_id: &str,
997        _lane: Option<&str>,
998        _limit: i64,
999    ) -> anyhow::Result<Vec<crate::traits::WorkTaskSummary>> {
1000        Ok(vec![])
1001    }
1002}
1003
1004/// Goal lifecycle cleanup and user notification bookkeeping.
1005#[async_trait]
1006pub trait GoalNotificationStore: Send + Sync {
1007    /// Count active evergreen (continuous) goals.
1008    async fn count_active_evergreen_goals(&self) -> anyhow::Result<i64> {
1009        Ok(0)
1010    }
1011
1012    /// Get goals that completed/failed but haven't been notified to the user yet.
1013    async fn get_goals_needing_notification(&self) -> anyhow::Result<Vec<crate::traits::Goal>> {
1014        Ok(vec![])
1015    }
1016
1017    /// Mark a goal as notified (set notified_at timestamp).
1018    async fn mark_goal_notified(&self, _goal_id: &str) -> anyhow::Result<()> {
1019        Ok(())
1020    }
1021
1022    /// Mark stale active goals as abandoned/failed.
1023    ///
1024    /// - Finite orchestration goals: active goals with no update in `stale_hours` → failed
1025    /// - Continuous orchestration goals: skipped (they have their own idle detection)
1026    /// - Personal goals: skipped
1027    ///
1028    /// Returns the number of goals cleaned up.
1029    async fn cleanup_stale_goals(&self, _stale_hours: i64) -> anyhow::Result<u64> {
1030        Ok(0)
1031    }
1032}
1033
1034/// Notification delivery queue persistence.
1035#[async_trait]
1036pub trait NotificationStore: Send + Sync {
1037    /// Record a background sub-agent that has started.
1038    async fn record_background_spawn(
1039        &self,
1040        _spawn: &crate::traits::BackgroundSpawn,
1041    ) -> anyhow::Result<()> {
1042        Ok(())
1043    }
1044
1045    /// Forget a background sub-agent that has ended.
1046    async fn finish_background_spawn(&self, _id: &str) -> anyhow::Result<()> {
1047        Ok(())
1048    }
1049
1050    /// The background sub-agents running for a session.
1051    async fn background_spawns_for_session(
1052        &self,
1053        _session_id: &str,
1054    ) -> anyhow::Result<Vec<crate::traits::BackgroundSpawn>> {
1055        Ok(Vec::new())
1056    }
1057
1058    /// Remove and return every recorded background sub-agent.
1059    async fn take_background_spawns(&self) -> anyhow::Result<Vec<crate::traits::BackgroundSpawn>> {
1060        Ok(Vec::new())
1061    }
1062
1063    /// Enqueue a notification for delivery.
1064    async fn enqueue_notification(
1065        &self,
1066        _entry: &crate::traits::NotificationEntry,
1067    ) -> anyhow::Result<()> {
1068        Ok(())
1069    }
1070
1071    /// Atomically claim a goal's notification slot and enqueue its notification.
1072    ///
1073    /// Returns `false` when another writer has already claimed the goal. Stores
1074    /// that do not support transactions may fall back to enqueueing only.
1075    async fn enqueue_goal_notification(
1076        &self,
1077        entry: &crate::traits::NotificationEntry,
1078    ) -> anyhow::Result<bool> {
1079        self.enqueue_notification(entry).await?;
1080        Ok(true)
1081    }
1082
1083    /// Get pending notifications ordered by priority (critical first), then creation time.
1084    async fn get_pending_notifications(
1085        &self,
1086        _limit: i64,
1087    ) -> anyhow::Result<Vec<crate::traits::NotificationEntry>> {
1088        Ok(vec![])
1089    }
1090
1091    /// Mark a notification as delivered.
1092    async fn mark_notification_delivered(&self, _notification_id: &str) -> anyhow::Result<()> {
1093        Ok(())
1094    }
1095
1096    /// Increment the attempt counter for a notification.
1097    async fn increment_notification_attempt(&self, _notification_id: &str) -> anyhow::Result<()> {
1098        Ok(())
1099    }
1100
1101    /// Delete expired status_update notifications (past their expires_at).
1102    async fn cleanup_expired_notifications(&self) -> anyhow::Result<i64> {
1103        Ok(0)
1104    }
1105
1106    /// Notices delivered to `session_id` at or after `since`, oldest first:
1107    /// what the owner was already told while a turn ran, so its reply can
1108    /// agree with them ([`crate::goals::notices_turn_context`]).
1109    async fn notices_delivered_since(
1110        &self,
1111        _session_id: &str,
1112        _since: chrono::DateTime<chrono::Utc>,
1113    ) -> anyhow::Result<Vec<crate::traits::DeliveredNotice>> {
1114        Ok(Vec::new())
1115    }
1116}
1117
1118/// Focused persistence contract used by mandate management. Includes the
1119/// schedule and scheduled-run lifecycle so the mandate surface can project
1120/// its controller goal's authoritative objective status.
1121pub trait MandateToolStore:
1122    MandateStore
1123    + GoalStore
1124    + WorkCoordinationStore
1125    + aidaemon_channels::hub::SessionChannelStore
1126    + GoalBudgetStore
1127    + GoalScheduleStore
1128    + ScheduledRunStore
1129{
1130}
1131
1132impl<T> MandateToolStore for T where
1133    T: MandateStore
1134        + GoalStore
1135        + WorkCoordinationStore
1136        + aidaemon_channels::hub::SessionChannelStore
1137        + GoalBudgetStore
1138        + GoalScheduleStore
1139        + ScheduledRunStore
1140{
1141}
1142
1143/// Focused persistence contract used by goal-trace tooling.
1144pub trait GoalTraceStore:
1145    GoalStore + GoalScheduleStore + MandateStore + TaskStore + WorkCoordinationStore + ScheduledRunStore
1146{
1147}
1148
1149impl<T> GoalTraceStore for T where
1150    T: GoalStore
1151        + GoalScheduleStore
1152        + MandateStore
1153        + TaskStore
1154        + WorkCoordinationStore
1155        + ScheduledRunStore
1156{
1157}
1158
1159/// Focused persistence contract used by goal task management.
1160pub trait ManageGoalTasksStore:
1161    GoalStore + TaskStore + MandateStore + WorkCoordinationStore + NotificationStore
1162{
1163}
1164
1165impl<T> ManageGoalTasksStore for T where
1166    T: GoalStore + TaskStore + MandateStore + WorkCoordinationStore + NotificationStore
1167{
1168}
1169
1170/// Focused persistence contract used by the automation surfaces (scheduled
1171/// goals, reminders and mandates): everything their two engines' tools take.
1172pub trait AutomationStore:
1173    MandateToolStore + ScheduledGoalRunsStore + GoalNotificationStore
1174{
1175}
1176
1177impl<T> AutomationStore for T where
1178    T: MandateToolStore + ScheduledGoalRunsStore + GoalNotificationStore
1179{
1180}
1181
1182/// Focused persistence contract used by blocker reporting.
1183pub trait ReportBlockerStore:
1184    TaskStore + GoalStore + NotificationStore + WorkCoordinationStore
1185{
1186}
1187
1188impl<T> ReportBlockerStore for T where
1189    T: TaskStore + GoalStore + NotificationStore + WorkCoordinationStore
1190{
1191}
1192
1193/// Focused persistence contract used by scheduled-goal tooling.
1194pub trait ScheduledGoalRunsStore:
1195    GoalStore
1196    + GoalScheduleStore
1197    + ScheduledRunStore
1198    + GoalBudgetStore
1199    + TaskStore
1200    + WorkCoordinationStore
1201    + SettingsStore
1202    + MandateStore
1203{
1204}
1205
1206impl<T> ScheduledGoalRunsStore for T where
1207    T: GoalStore
1208        + GoalScheduleStore
1209        + ScheduledRunStore
1210        + GoalBudgetStore
1211        + TaskStore
1212        + WorkCoordinationStore
1213        + SettingsStore
1214        + MandateStore
1215{
1216}
1217
1218/// Database health check: verifies the connection is alive. The scheduler's
1219/// [`DbHealthGate`](crate::heartbeat::DbHealthGate) skips a tick while it fails.
1220#[async_trait]
1221pub trait HealthCheckStore: Send + Sync {
1222    async fn health_check(&self) -> anyhow::Result<()> {
1223        Ok(())
1224    }
1225}