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