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(|updates| updates.learning_note.is_none()),
286            "adaptive mandate operating updates are not supported by this store"
287        );
288        self.record_mandate_decision(decision, intention, task_attempt_id)
289            .await
290    }
291
292    async fn get_mandate_decision_for_run(
293        &self,
294        _goal_run_id: &str,
295    ) -> anyhow::Result<Option<crate::traits::MandateDecisionCycle>> {
296        Ok(None)
297    }
298
299    /// Tool-call ids of the run's successful structured receipts that may
300    /// back a decision or measurement (newest first, at most `limit`): the
301    /// same receipts `evidence_receipt_ids` accepts, minus the mandate
302    /// protocol's own control tools.
303    async fn current_run_evidence_receipt_ids(
304        &self,
305        _goal_run_id: &str,
306        _limit: usize,
307    ) -> anyhow::Result<Vec<String>> {
308        Ok(Vec::new())
309    }
310
311    async fn list_mandate_decisions(
312        &self,
313        _mandate_id: &str,
314        _limit: i64,
315    ) -> anyhow::Result<Vec<crate::traits::MandateDecisionCycle>> {
316        Ok(Vec::new())
317    }
318
319    async fn list_intentions(
320        &self,
321        _mandate_id: &str,
322        _limit: i64,
323    ) -> anyhow::Result<Vec<crate::traits::Intention>> {
324        Ok(Vec::new())
325    }
326
327    /// Persist one bounded, advisory learning note only after all cited
328    /// receipts are proven to belong to this mandate.
329    async fn record_mandate_learning_note(
330        &self,
331        _note: &crate::traits::MandateLearningNote,
332    ) -> anyhow::Result<()> {
333        anyhow::bail!("mandate learning is not supported by this store")
334    }
335
336    async fn list_mandate_learning_notes(
337        &self,
338        _mandate_id: &str,
339        _limit: i64,
340    ) -> anyhow::Result<Vec<crate::traits::MandateLearningNote>> {
341        Ok(Vec::new())
342    }
343
344    /// Deduplicate and route one content-free external signal to matching
345    /// Autopilot mandates. Matching is structural and cannot widen authority.
346    async fn wake_mandates_for_signal(
347        &self,
348        _signal: &crate::traits::MandateWakeSignal,
349    ) -> anyhow::Result<Vec<String>> {
350        Ok(Vec::new())
351    }
352
353    /// Resolve an awaiting-input state with a typed owner action. Question
354    /// answers and external-effect reconciliation are intentionally distinct.
355    #[allow(clippy::too_many_arguments)]
356    async fn resolve_mandate_suspension(
357        &self,
358        _mandate_id: &str,
359        _expected_version: i64,
360        _expected_kind: crate::traits::MandateSuspensionKind,
361        _controller_context: Option<&str>,
362        _reconciliation_resolution: Option<crate::traits::MandateReconciliationResolution>,
363        _owner_guidance: &str,
364        _owner_session: &str,
365    ) -> anyhow::Result<bool> {
366        Ok(false)
367    }
368
369    /// Atomically reserve the exact next mutation attempt under the current
370    /// cycle, rolling-24h, cooldown, mandate, run, intention, task, and lease
371    /// fences. Implementations must insert the durable ledger row and advance
372    /// the cycle counter in one transaction.
373    async fn reserve_mandate_action_attempt(
374        &self,
375        _reservation: &crate::traits::MandateMutationReservation,
376    ) -> anyhow::Result<Option<crate::traits::MandateMutationAttempt>> {
377        Ok(None)
378    }
379
380    /// Atomically claim one exact reserved mutation at the last common
381    /// dispatcher. A claim is one-use and must fail if any authority, run,
382    /// task-attempt, tool-call, digest, or reservation field is stale.
383    async fn claim_mandate_mutation_dispatch(
384        &self,
385        _claim: &crate::traits::MandateMutationDispatchClaim,
386    ) -> anyhow::Result<bool> {
387        Ok(false)
388    }
389
390    /// Read the typed, cross-cycle mutation quota projection at one instant.
391    /// This is advisory for deliberation; reservation remains authoritative.
392    async fn get_mandate_mutation_quota_state(
393        &self,
394        _mandate_id: &str,
395        _as_of: &str,
396    ) -> anyhow::Result<Option<crate::traits::MandateMutationQuotaState>> {
397        Ok(None)
398    }
399
400    async fn list_mandate_mutation_attempts_for_run(
401        &self,
402        _goal_run_id: &str,
403    ) -> anyhow::Result<Vec<crate::traits::MandateMutationAttempt>> {
404        Ok(Vec::new())
405    }
406
407    /// Atomically prove and close a mandate run. Satisfied outcomes close the
408    /// goal run (and ACT intention) inside the proof transaction; reconciliation
409    /// results leave lifecycle state untouched for the caller's explicit path.
410    async fn finalize_mandate_run_from_proof(
411        &self,
412        _request: &crate::traits::MandateRunFinalizationRequest,
413    ) -> anyhow::Result<crate::traits::MandateRunFinalizationResult> {
414        Ok(crate::traits::MandateRunFinalizationResult::Rejected {
415            reason: crate::traits::MandateFinalizationRejectReason::InvalidRequest,
416        })
417    }
418}
419
420/// Task persistence and task activity logs.
421#[async_trait]
422pub trait TaskStore: Send + Sync {
423    /// Create a new task within a goal.
424    async fn create_task(&self, _task: &crate::traits::Task) -> anyhow::Result<()> {
425        Ok(())
426    }
427
428    /// Get a task by ID.
429    async fn get_task(&self, _id: &str) -> anyhow::Result<Option<crate::traits::Task>> {
430        Ok(None)
431    }
432
433    /// Update a task (full replacement).
434    async fn update_task(&self, _task: &crate::traits::Task) -> anyhow::Result<()> {
435        Ok(())
436    }
437
438    /// Get all tasks for a goal.
439    async fn get_tasks_for_goal(&self, _goal_id: &str) -> anyhow::Result<Vec<crate::traits::Task>> {
440        Ok(vec![])
441    }
442
443    /// Count completed/skipped tasks for a goal (used by progress-based circuit breaker).
444    async fn count_completed_tasks_for_goal(&self, _goal_id: &str) -> anyhow::Result<i64> {
445        Ok(0)
446    }
447
448    /// Atomically claim a pending task for an executor.
449    async fn claim_task(&self, _task_id: &str, _agent_id: &str) -> anyhow::Result<bool> {
450        Ok(false)
451    }
452
453    /// Log an activity entry for a task.
454    async fn log_task_activity(
455        &self,
456        _activity: &crate::traits::TaskActivity,
457    ) -> anyhow::Result<()> {
458        Ok(())
459    }
460
461    /// Get activity log for a task.
462    async fn get_task_activities(
463        &self,
464        _task_id: &str,
465    ) -> anyhow::Result<Vec<crate::traits::TaskActivity>> {
466        Ok(vec![])
467    }
468}
469
470/// Goal schedule and scheduled-run persistence.
471#[async_trait]
472pub trait GoalScheduleStore: Send + Sync {
473    /// Create a new schedule for a goal.
474    async fn create_goal_schedule(
475        &self,
476        _schedule: &crate::traits::GoalSchedule,
477    ) -> anyhow::Result<()> {
478        Ok(())
479    }
480
481    /// Get a schedule by ID.
482    async fn get_goal_schedule(
483        &self,
484        _schedule_id: &str,
485    ) -> anyhow::Result<Option<crate::traits::GoalSchedule>> {
486        Ok(None)
487    }
488
489    /// List schedules for a goal.
490    async fn get_schedules_for_goal(
491        &self,
492        _goal_id: &str,
493    ) -> anyhow::Result<Vec<crate::traits::GoalSchedule>> {
494        Ok(vec![])
495    }
496
497    /// Get due schedules for active orchestration goals.
498    async fn get_due_goal_schedules(
499        &self,
500        _limit: i64,
501    ) -> anyhow::Result<Vec<crate::traits::GoalSchedule>> {
502        Ok(vec![])
503    }
504
505    /// Update a schedule (full replacement).
506    async fn update_goal_schedule(
507        &self,
508        _schedule: &crate::traits::GoalSchedule,
509    ) -> anyhow::Result<()> {
510        Ok(())
511    }
512
513    /// Delete a schedule by ID. Returns true if a row was deleted.
514    async fn delete_goal_schedule(&self, _schedule_id: &str) -> anyhow::Result<bool> {
515        Ok(false)
516    }
517
518    /// Cancel pending-confirmation goals older than max_age_secs.
519    async fn cancel_stale_pending_confirmation_goals(
520        &self,
521        _max_age_secs: i64,
522    ) -> anyhow::Result<u64> {
523        Ok(0)
524    }
525
526    /// Get all orchestration goals that have schedules or are awaiting confirmation.
527    async fn get_scheduled_goals(&self) -> anyhow::Result<Vec<crate::traits::Goal>> {
528        Ok(vec![])
529    }
530
531    /// Active continuous orchestration goals with no schedule and no mandate
532    /// behind them: nothing will ever run them. Listed so they can be seen
533    /// and cancelled.
534    async fn get_unscheduled_active_goals(&self) -> anyhow::Result<Vec<crate::traits::Goal>> {
535        Ok(vec![])
536    }
537}
538
539/// Goal token budget persistence and accounting.
540#[async_trait]
541pub trait GoalBudgetStore: Send + Sync {
542    /// Reset tokens_used_today only for active goals whose usage belongs to a
543    /// prior UTC day. Safe to call repeatedly or at process startup.
544    async fn reset_daily_token_budgets(&self) -> anyhow::Result<u64> {
545        Ok(0)
546    }
547
548    /// Update budget columns only. `None` = keep current value (COALESCE), NOT "clear to NULL".
549    /// This is a targeted UPDATE that avoids the race with `add_goal_tokens_and_get_budget_status()`
550    /// which atomically increments `tokens_used_today` — a full `update_goal()` would clobber that.
551    async fn set_goal_budgets(
552        &self,
553        _goal_id: &str,
554        _budget_per_check: Option<i64>,
555        _budget_daily: Option<i64>,
556    ) -> anyhow::Result<()> {
557        Ok(())
558    }
559
560    /// Atomically add tokens to a goal's daily usage counter and return budget status.
561    ///
562    /// Use `delta_tokens = 0` to read the latest counters without modifying them.
563    async fn add_goal_tokens_and_get_budget_status(
564        &self,
565        _goal_id: &str,
566        _delta_tokens: i64,
567    ) -> anyhow::Result<Option<crate::traits::GoalTokenBudgetStatus>> {
568        Ok(None)
569    }
570}
571
572/// Scheduled run runtime-state persistence.
573#[async_trait]
574pub trait ScheduledRunStore: Send + Sync {
575    /// Persist runtime state for an active scheduled run.
576    async fn upsert_scheduled_run_state(
577        &self,
578        _state: &crate::traits::ScheduledRunState,
579    ) -> anyhow::Result<()> {
580        Ok(())
581    }
582
583    /// Load persisted runtime state for an active scheduled run.
584    async fn get_scheduled_run_state(
585        &self,
586        _goal_id: &str,
587    ) -> anyhow::Result<Option<crate::traits::ScheduledRunState>> {
588        Ok(None)
589    }
590
591    async fn get_scheduled_recovery_state(
592        &self,
593        _goal_id: &str,
594    ) -> anyhow::Result<Option<crate::traits::ScheduledRecoveryState>> {
595        Ok(None)
596    }
597
598    /// Escalated scheduled objectives that the recovery machine itself paused,
599    /// whose cool-down has elapsed and whose automatic recovery attempts are
600    /// still under the cap.
601    async fn list_escalated_recovery_candidates(
602        &self,
603        _cooldown_secs: i64,
604        _max_attempts: u16,
605    ) -> anyhow::Result<Vec<crate::traits::ScheduledRecoveryState>> {
606        Ok(Vec::new())
607    }
608
609    /// Record that an automatic recovery run was launched for the goal.
610    async fn record_scheduled_recovery_attempt(&self, _goal_id: &str) -> anyhow::Result<()> {
611        Ok(())
612    }
613
614    /// Delete persisted runtime state for an active scheduled run.
615    async fn delete_scheduled_run_state(&self, _goal_id: &str) -> anyhow::Result<bool> {
616        Ok(false)
617    }
618}
619
620/// Task dispatch bookkeeping for executor scheduling and recovery.
621#[async_trait]
622pub trait TaskDispatchStore: Send + Sync {
623    /// Get pending tasks ordered by priority, filtering out those with unmet dependencies.
624    async fn get_pending_tasks_by_priority(
625        &self,
626        _limit: i64,
627    ) -> anyhow::Result<Vec<crate::traits::Task>> {
628        Ok(vec![])
629    }
630
631    /// Get tasks stuck in running/claimed state longer than timeout_secs.
632    async fn get_stuck_tasks(
633        &self,
634        _timeout_secs: i64,
635    ) -> anyhow::Result<Vec<crate::traits::Task>> {
636        Ok(vec![])
637    }
638
639    /// Get tasks completed after a given timestamp.
640    async fn get_recently_completed_tasks(
641        &self,
642        _since: &str,
643    ) -> anyhow::Result<Vec<crate::traits::Task>> {
644        Ok(vec![])
645    }
646
647    /// Mark a running/claimed task as interrupted (e.g., after crash or timeout).
648    async fn mark_task_interrupted(&self, _task_id: &str) -> anyhow::Result<bool> {
649        Ok(false)
650    }
651}
652
653/// Durable coordination for goal runs, fenced task attempts, collaboration
654/// records, named worker policies, project scope, and attempt workspaces.
655#[async_trait]
656pub trait WorkCoordinationStore: Send + Sync {
657    async fn create_work_project(
658        &self,
659        _name: &str,
660        _description: Option<&str>,
661    ) -> anyhow::Result<crate::traits::WorkProject> {
662        anyhow::bail!("work projects are not supported by this store")
663    }
664
665    async fn list_work_projects(&self) -> anyhow::Result<Vec<crate::traits::WorkProject>> {
666        Ok(vec![])
667    }
668
669    async fn get_session_work_project(&self, _session_id: &str) -> anyhow::Result<String> {
670        Ok(crate::traits::DEFAULT_PROJECT_ID.to_string())
671    }
672
673    /// Rename a project or change its folder (`Some(None)` clears it).
674    /// `None` when there is no such project.
675    async fn update_work_project(
676        &self,
677        _id: &str,
678        _name: Option<&str>,
679        _path: Option<Option<&str>>,
680    ) -> anyhow::Result<Option<crate::traits::WorkProject>> {
681        anyhow::bail!("work projects are not supported by this store")
682    }
683
684    /// Delete a project: its sessions, goals, runs and journal move to the
685    /// default project, its bots to none, and its worker profiles go with
686    /// it. `false` when there is no such project; the default one cannot
687    /// be deleted.
688    async fn delete_work_project(&self, _id: &str) -> anyhow::Result<bool> {
689        anyhow::bail!("work projects are not supported by this store")
690    }
691
692    /// Every session placed in a project other than the default one, with
693    /// its project id.
694    async fn session_work_projects(&self) -> anyhow::Result<Vec<(String, String)>> {
695        Ok(vec![])
696    }
697
698    async fn set_session_work_project(
699        &self,
700        _session_id: &str,
701        _project_id: &str,
702    ) -> anyhow::Result<bool> {
703        Ok(false)
704    }
705
706    /// Every chat bot sending its direct-message chats to a project: (bot
707    /// channel, project id).
708    async fn channel_work_projects(&self) -> anyhow::Result<Vec<(String, String)>> {
709        Ok(vec![])
710    }
711
712    /// Send bot `channel`'s direct-message chats to `project_id`, or to no
713    /// project (`None`). `false` when there is no such project.
714    async fn set_channel_work_project(
715        &self,
716        _channel: &str,
717        _project_id: Option<&str>,
718    ) -> anyhow::Result<bool> {
719        Ok(false)
720    }
721
722    /// Place a direct-message chat of bot `channel` in that bot's project,
723    /// when the chat was never placed (taking a chat out of its project
724    /// places it in the default one, so that stays). Returns whether it
725    /// was placed now.
726    async fn place_chat_by_channel(
727        &self,
728        _session_id: &str,
729        _channel: &str,
730    ) -> anyhow::Result<bool> {
731        Ok(false)
732    }
733
734    async fn start_goal_run(
735        &self,
736        _goal_id: &str,
737        _trigger_type: &str,
738        _schedule_id: Option<&str>,
739        _root_task_id: Option<&str>,
740    ) -> anyhow::Result<crate::traits::GoalRun> {
741        anyhow::bail!("goal runs are not supported by this store")
742    }
743
744    /// Record an occurrence the scheduler skipped (the daemon was not
745    /// running and it is past its catch-up window) as a closed run with
746    /// status `missed`, started at the time it was due. It is part of the
747    /// automation's history, but never goes through [`Self::finish_goal_run`]:
748    /// a miss is not a failure and leaves the failure budget as it was.
749    async fn record_missed_goal_run(
750        &self,
751        _goal_id: &str,
752        _schedule_id: Option<&str>,
753        _due_at: &str,
754        _summary: &str,
755    ) -> anyhow::Result<crate::traits::GoalRun> {
756        anyhow::bail!("goal runs are not supported by this store")
757    }
758
759    async fn get_current_goal_run(
760        &self,
761        _goal_id: &str,
762    ) -> anyhow::Result<Option<crate::traits::GoalRun>> {
763        Ok(None)
764    }
765
766    async fn get_goal_runs(&self, _goal_id: &str) -> anyhow::Result<Vec<crate::traits::GoalRun>> {
767        Ok(vec![])
768    }
769
770    /// Typed lifecycle owner for a task. Callers must use this relationship,
771    /// never infer run provenance from the task description.
772    async fn get_goal_run_for_task(
773        &self,
774        _task_id: &str,
775    ) -> anyhow::Result<Option<crate::traits::GoalRun>> {
776        Ok(None)
777    }
778
779    async fn get_tasks_for_goal_run(
780        &self,
781        _run_id: &str,
782    ) -> anyhow::Result<Vec<crate::traits::Task>> {
783        Ok(vec![])
784    }
785
786    async fn finish_goal_run(
787        &self,
788        _run_id: &str,
789        _status: &str,
790        _summary: Option<&str>,
791    ) -> anyhow::Result<bool> {
792        Ok(false)
793    }
794
795    async fn claim_task_with_lease(
796        &self,
797        _task_id: &str,
798        _worker_instance_id: &str,
799        _worker_profile_id: Option<&str>,
800        _lease_secs: i64,
801    ) -> anyhow::Result<Option<crate::traits::TaskAttempt>> {
802        Ok(None)
803    }
804
805    async fn get_current_task_attempt(
806        &self,
807        _task_id: &str,
808    ) -> anyhow::Result<Option<crate::traits::TaskAttempt>> {
809        Ok(None)
810    }
811
812    async fn bind_task_attempt_worker(
813        &self,
814        _attempt_id: &str,
815        _lease_token: &str,
816        _worker_instance_id: &str,
817        _worker_profile_id: Option<&str>,
818    ) -> anyhow::Result<bool> {
819        Ok(false)
820    }
821
822    async fn heartbeat_task_attempt(
823        &self,
824        _attempt_id: &str,
825        _lease_token: &str,
826        _lease_secs: i64,
827    ) -> anyhow::Result<bool> {
828        Ok(false)
829    }
830
831    async fn patch_task_from_attempt(
832        &self,
833        _attempt_id: &str,
834        _lease_token: &str,
835        _patch: &crate::traits::TaskAttemptPatch,
836    ) -> anyhow::Result<bool> {
837        Ok(false)
838    }
839
840    /// Expire elapsed leases and return the affected task IDs. Idempotent tasks
841    /// with retry budget are re-queued; ambiguous writes require verification.
842    async fn recover_expired_task_attempts(&self) -> anyhow::Result<Vec<String>> {
843        Ok(vec![])
844    }
845
846    /// Whether any worker still holds an unexpired execution lease on an
847    /// attempt belonging to this goal run. While one does, that worker owns
848    /// the run's outcome; lifecycle reconciliation must not race it.
849    async fn goal_run_has_live_attempt(&self, _run_id: &str) -> anyhow::Result<bool> {
850        Ok(false)
851    }
852
853    async fn append_task_journal(
854        &self,
855        _entry: &crate::traits::TaskJournalEntry,
856    ) -> anyhow::Result<()> {
857        Ok(())
858    }
859
860    async fn get_task_journal(
861        &self,
862        _task_id: &str,
863        _limit: i64,
864    ) -> anyhow::Result<Vec<crate::traits::TaskJournalEntry>> {
865        Ok(vec![])
866    }
867
868    async fn unblock_task(
869        &self,
870        _task_id: &str,
871        _resolution: &str,
872        _actor_id: &str,
873        _source_channel: Option<&str>,
874    ) -> anyhow::Result<bool> {
875        Ok(false)
876    }
877
878    async fn retry_work_task(
879        &self,
880        _task_id: &str,
881        _actor_id: &str,
882        _source_channel: Option<&str>,
883    ) -> anyhow::Result<bool> {
884        Ok(false)
885    }
886
887    async fn cancel_work_task(
888        &self,
889        _task_id: &str,
890        _actor_id: &str,
891        _source_channel: Option<&str>,
892    ) -> anyhow::Result<bool> {
893        Ok(false)
894    }
895
896    async fn upsert_worker_profile(
897        &self,
898        _profile: &crate::traits::WorkerProfile,
899    ) -> anyhow::Result<()> {
900        Ok(())
901    }
902
903    async fn get_worker_profile(
904        &self,
905        _profile_id: &str,
906    ) -> anyhow::Result<Option<crate::traits::WorkerProfile>> {
907        Ok(None)
908    }
909
910    async fn list_worker_profiles(
911        &self,
912        _project_id: Option<&str>,
913    ) -> anyhow::Result<Vec<crate::traits::WorkerProfile>> {
914        Ok(vec![])
915    }
916
917    async fn assign_task_worker_profile(
918        &self,
919        _task_id: &str,
920        _profile_id: &str,
921        _actor_id: &str,
922        _source_channel: Option<&str>,
923    ) -> anyhow::Result<bool> {
924        Ok(false)
925    }
926
927    async fn set_task_workspace_policy(
928        &self,
929        _task_id: &str,
930        _policy: &str,
931    ) -> anyhow::Result<bool> {
932        Ok(false)
933    }
934
935    async fn get_task_workspace_policy(&self, _task_id: &str) -> anyhow::Result<String> {
936        Ok("shared".to_string())
937    }
938
939    /// Whether the task's workspace policy was set on the task itself
940    /// (`set_task_workspace_policy`), rather than defaulted or inherited
941    /// from its worker profile.
942    async fn task_workspace_policy_is_explicit(&self, _task_id: &str) -> anyhow::Result<bool> {
943        Ok(false)
944    }
945
946    async fn create_task_workspace(
947        &self,
948        _workspace: &crate::traits::TaskWorkspace,
949    ) -> anyhow::Result<()> {
950        Ok(())
951    }
952
953    async fn update_task_workspace(
954        &self,
955        _workspace: &crate::traits::TaskWorkspace,
956    ) -> anyhow::Result<()> {
957        Ok(())
958    }
959
960    async fn get_task_workspace(
961        &self,
962        _task_id: &str,
963    ) -> anyhow::Result<Option<crate::traits::TaskWorkspace>> {
964        Ok(None)
965    }
966
967    async fn get_latest_task_handoff(
968        &self,
969        _task_id: &str,
970    ) -> anyhow::Result<Option<crate::traits::TaskHandoff>> {
971        Ok(None)
972    }
973
974    async fn list_work_goals(
975        &self,
976        _project_id: &str,
977        _include_terminal: bool,
978        _limit: i64,
979    ) -> anyhow::Result<Vec<crate::traits::WorkGoalSummary>> {
980        Ok(vec![])
981    }
982
983    async fn list_work_tasks(
984        &self,
985        _project_id: &str,
986        _lane: Option<&str>,
987        _limit: i64,
988    ) -> anyhow::Result<Vec<crate::traits::WorkTaskSummary>> {
989        Ok(vec![])
990    }
991}
992
993/// Goal lifecycle cleanup and user notification bookkeeping.
994#[async_trait]
995pub trait GoalNotificationStore: Send + Sync {
996    /// Count active evergreen (continuous) goals.
997    async fn count_active_evergreen_goals(&self) -> anyhow::Result<i64> {
998        Ok(0)
999    }
1000
1001    /// Get goals that completed/failed but haven't been notified to the user yet.
1002    async fn get_goals_needing_notification(&self) -> anyhow::Result<Vec<crate::traits::Goal>> {
1003        Ok(vec![])
1004    }
1005
1006    /// Mark a goal as notified (set notified_at timestamp).
1007    async fn mark_goal_notified(&self, _goal_id: &str) -> anyhow::Result<()> {
1008        Ok(())
1009    }
1010
1011    /// Mark stale active goals as abandoned/failed.
1012    ///
1013    /// - Finite orchestration goals: active goals with no update in `stale_hours` → failed
1014    /// - Continuous orchestration goals: skipped (they have their own idle detection)
1015    /// - Personal goals: skipped
1016    ///
1017    /// Returns the number of goals cleaned up.
1018    async fn cleanup_stale_goals(&self, _stale_hours: i64) -> anyhow::Result<u64> {
1019        Ok(0)
1020    }
1021}
1022
1023/// Notification delivery queue persistence.
1024#[async_trait]
1025pub trait NotificationStore: Send + Sync {
1026    /// Record a background sub-agent that has started.
1027    async fn record_background_spawn(
1028        &self,
1029        _spawn: &crate::traits::BackgroundSpawn,
1030    ) -> anyhow::Result<()> {
1031        Ok(())
1032    }
1033
1034    /// Forget a background sub-agent that has ended.
1035    async fn finish_background_spawn(&self, _id: &str) -> anyhow::Result<()> {
1036        Ok(())
1037    }
1038
1039    /// The background sub-agents running for a session.
1040    async fn background_spawns_for_session(
1041        &self,
1042        _session_id: &str,
1043    ) -> anyhow::Result<Vec<crate::traits::BackgroundSpawn>> {
1044        Ok(Vec::new())
1045    }
1046
1047    /// Remove and return every recorded background sub-agent.
1048    async fn take_background_spawns(&self) -> anyhow::Result<Vec<crate::traits::BackgroundSpawn>> {
1049        Ok(Vec::new())
1050    }
1051
1052    /// Enqueue a notification for delivery.
1053    async fn enqueue_notification(
1054        &self,
1055        _entry: &crate::traits::NotificationEntry,
1056    ) -> anyhow::Result<()> {
1057        Ok(())
1058    }
1059
1060    /// Atomically claim a goal's notification slot and enqueue its notification.
1061    ///
1062    /// Returns `false` when another writer has already claimed the goal. Stores
1063    /// that do not support transactions may fall back to enqueueing only.
1064    async fn enqueue_goal_notification(
1065        &self,
1066        entry: &crate::traits::NotificationEntry,
1067    ) -> anyhow::Result<bool> {
1068        self.enqueue_notification(entry).await?;
1069        Ok(true)
1070    }
1071
1072    /// Get pending notifications ordered by priority (critical first), then creation time.
1073    async fn get_pending_notifications(
1074        &self,
1075        _limit: i64,
1076    ) -> anyhow::Result<Vec<crate::traits::NotificationEntry>> {
1077        Ok(vec![])
1078    }
1079
1080    /// Mark a notification as delivered.
1081    async fn mark_notification_delivered(&self, _notification_id: &str) -> anyhow::Result<()> {
1082        Ok(())
1083    }
1084
1085    /// Increment the attempt counter for a notification.
1086    async fn increment_notification_attempt(&self, _notification_id: &str) -> anyhow::Result<()> {
1087        Ok(())
1088    }
1089
1090    /// Delete expired status_update notifications (past their expires_at).
1091    async fn cleanup_expired_notifications(&self) -> anyhow::Result<i64> {
1092        Ok(0)
1093    }
1094
1095    /// Notices delivered to `session_id` at or after `since`, oldest first:
1096    /// what the owner was already told while a turn ran, so its reply can
1097    /// agree with them ([`crate::goals::notices_turn_context`]).
1098    async fn notices_delivered_since(
1099        &self,
1100        _session_id: &str,
1101        _since: chrono::DateTime<chrono::Utc>,
1102    ) -> anyhow::Result<Vec<crate::traits::DeliveredNotice>> {
1103        Ok(Vec::new())
1104    }
1105}
1106
1107/// Focused persistence contract used by mandate management. Includes the
1108/// schedule and scheduled-run lifecycle so the mandate surface can project
1109/// its controller goal's authoritative objective status.
1110pub trait MandateToolStore:
1111    MandateStore
1112    + GoalStore
1113    + WorkCoordinationStore
1114    + aidaemon_channels::hub::SessionChannelStore
1115    + GoalBudgetStore
1116    + GoalScheduleStore
1117    + ScheduledRunStore
1118{
1119}
1120
1121impl<T> MandateToolStore for T where
1122    T: MandateStore
1123        + GoalStore
1124        + WorkCoordinationStore
1125        + aidaemon_channels::hub::SessionChannelStore
1126        + GoalBudgetStore
1127        + GoalScheduleStore
1128        + ScheduledRunStore
1129{
1130}
1131
1132/// Focused persistence contract used by goal-trace tooling.
1133pub trait GoalTraceStore:
1134    GoalStore + GoalScheduleStore + MandateStore + TaskStore + WorkCoordinationStore + ScheduledRunStore
1135{
1136}
1137
1138impl<T> GoalTraceStore for T where
1139    T: GoalStore
1140        + GoalScheduleStore
1141        + MandateStore
1142        + TaskStore
1143        + WorkCoordinationStore
1144        + ScheduledRunStore
1145{
1146}
1147
1148/// Focused persistence contract used by goal task management.
1149pub trait ManageGoalTasksStore:
1150    GoalStore + TaskStore + MandateStore + WorkCoordinationStore + NotificationStore
1151{
1152}
1153
1154impl<T> ManageGoalTasksStore for T where
1155    T: GoalStore + TaskStore + MandateStore + WorkCoordinationStore + NotificationStore
1156{
1157}
1158
1159/// Focused persistence contract used by the automation surfaces (scheduled
1160/// goals, reminders and mandates): everything their two engines' tools take.
1161pub trait AutomationStore:
1162    MandateToolStore + ScheduledGoalRunsStore + GoalNotificationStore
1163{
1164}
1165
1166impl<T> AutomationStore for T where
1167    T: MandateToolStore + ScheduledGoalRunsStore + GoalNotificationStore
1168{
1169}
1170
1171/// Focused persistence contract used by blocker reporting.
1172pub trait ReportBlockerStore:
1173    TaskStore + GoalStore + NotificationStore + WorkCoordinationStore
1174{
1175}
1176
1177impl<T> ReportBlockerStore for T where
1178    T: TaskStore + GoalStore + NotificationStore + WorkCoordinationStore
1179{
1180}
1181
1182/// Focused persistence contract used by scheduled-goal tooling.
1183pub trait ScheduledGoalRunsStore:
1184    GoalStore
1185    + GoalScheduleStore
1186    + ScheduledRunStore
1187    + GoalBudgetStore
1188    + TaskStore
1189    + WorkCoordinationStore
1190    + SettingsStore
1191    + MandateStore
1192{
1193}
1194
1195impl<T> ScheduledGoalRunsStore for T where
1196    T: GoalStore
1197        + GoalScheduleStore
1198        + ScheduledRunStore
1199        + GoalBudgetStore
1200        + TaskStore
1201        + WorkCoordinationStore
1202        + SettingsStore
1203        + MandateStore
1204{
1205}
1206
1207/// Database health check: verifies the connection is alive. The scheduler's
1208/// [`DbHealthGate`](crate::heartbeat::DbHealthGate) skips a tick while it fails.
1209#[async_trait]
1210pub trait HealthCheckStore: Send + Sync {
1211    async fn health_check(&self) -> anyhow::Result<()> {
1212        Ok(())
1213    }
1214}