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    /// Orchestration goals with pending/running scheduled, manual run-now, or
543    /// recovery runs, even after a one-shot schedule has been consumed.
544    /// Matches scheduled-run reconciliation; run-level blocked and mandate
545    /// runs have separate lifecycle handling.
546    async fn get_goals_with_open_scheduled_runs(&self) -> anyhow::Result<Vec<crate::traits::Goal>> {
547        Ok(vec![])
548    }
549
550    /// Active continuous orchestration goals with no schedule and no mandate
551    /// behind them: nothing will ever run them. Listed so they can be seen
552    /// and cancelled.
553    async fn get_unscheduled_active_goals(&self) -> anyhow::Result<Vec<crate::traits::Goal>> {
554        Ok(vec![])
555    }
556}
557
558/// Goal token budget persistence and accounting.
559#[async_trait]
560pub trait GoalBudgetStore: Send + Sync {
561    /// Reset tokens_used_today only for active goals whose usage belongs to a
562    /// prior UTC day. Safe to call repeatedly or at process startup.
563    async fn reset_daily_token_budgets(&self) -> anyhow::Result<u64> {
564        Ok(0)
565    }
566
567    /// Update budget columns only. `None` = keep current value (COALESCE), NOT "clear to NULL".
568    /// This is a targeted UPDATE that avoids the race with `add_goal_tokens_and_get_budget_status()`
569    /// which atomically increments `tokens_used_today` — a full `update_goal()` would clobber that.
570    async fn set_goal_budgets(
571        &self,
572        _goal_id: &str,
573        _budget_per_check: Option<i64>,
574        _budget_daily: Option<i64>,
575    ) -> anyhow::Result<()> {
576        Ok(())
577    }
578
579    /// Atomically add tokens to a goal's daily usage counter and return budget status.
580    ///
581    /// Use `delta_tokens = 0` to read the latest counters without modifying them.
582    async fn add_goal_tokens_and_get_budget_status(
583        &self,
584        _goal_id: &str,
585        _delta_tokens: i64,
586    ) -> anyhow::Result<Option<crate::traits::GoalTokenBudgetStatus>> {
587        Ok(None)
588    }
589}
590
591/// Scheduled run runtime-state persistence.
592#[async_trait]
593pub trait ScheduledRunStore: Send + Sync {
594    /// Persist runtime state for an active scheduled run.
595    async fn upsert_scheduled_run_state(
596        &self,
597        _state: &crate::traits::ScheduledRunState,
598    ) -> anyhow::Result<()> {
599        Ok(())
600    }
601
602    /// Load persisted runtime state for an active scheduled run.
603    async fn get_scheduled_run_state(
604        &self,
605        _goal_id: &str,
606    ) -> anyhow::Result<Option<crate::traits::ScheduledRunState>> {
607        Ok(None)
608    }
609
610    async fn get_scheduled_recovery_state(
611        &self,
612        _goal_id: &str,
613    ) -> anyhow::Result<Option<crate::traits::ScheduledRecoveryState>> {
614        Ok(None)
615    }
616
617    /// Escalated scheduled objectives that the recovery machine itself paused,
618    /// whose cool-down has elapsed and whose automatic recovery attempts are
619    /// still under the cap.
620    async fn list_escalated_recovery_candidates(
621        &self,
622        _cooldown_secs: i64,
623        _max_attempts: u16,
624    ) -> anyhow::Result<Vec<crate::traits::ScheduledRecoveryState>> {
625        Ok(Vec::new())
626    }
627
628    /// Record that an automatic recovery run was launched for the goal.
629    async fn record_scheduled_recovery_attempt(&self, _goal_id: &str) -> anyhow::Result<()> {
630        Ok(())
631    }
632
633    /// Delete persisted runtime state for an active scheduled run.
634    async fn delete_scheduled_run_state(&self, _goal_id: &str) -> anyhow::Result<bool> {
635        Ok(false)
636    }
637}
638
639/// Task dispatch bookkeeping for executor scheduling and recovery.
640#[async_trait]
641pub trait TaskDispatchStore: Send + Sync {
642    /// Get pending tasks ordered by priority, filtering out those with unmet dependencies.
643    async fn get_pending_tasks_by_priority(
644        &self,
645        _limit: i64,
646    ) -> anyhow::Result<Vec<crate::traits::Task>> {
647        Ok(vec![])
648    }
649
650    /// Get tasks stuck in running/claimed state longer than timeout_secs.
651    async fn get_stuck_tasks(
652        &self,
653        _timeout_secs: i64,
654    ) -> anyhow::Result<Vec<crate::traits::Task>> {
655        Ok(vec![])
656    }
657
658    /// Get tasks completed after a given timestamp.
659    async fn get_recently_completed_tasks(
660        &self,
661        _since: &str,
662    ) -> anyhow::Result<Vec<crate::traits::Task>> {
663        Ok(vec![])
664    }
665
666    /// Mark a running/claimed task as interrupted (e.g., after crash or timeout).
667    async fn mark_task_interrupted(&self, _task_id: &str) -> anyhow::Result<bool> {
668        Ok(false)
669    }
670}
671
672/// Durable coordination for goal runs, fenced task attempts, collaboration
673/// records, named worker policies, project scope, and attempt workspaces.
674#[async_trait]
675pub trait WorkCoordinationStore: Send + Sync {
676    async fn create_work_project(
677        &self,
678        _name: &str,
679        _description: Option<&str>,
680    ) -> anyhow::Result<crate::traits::WorkProject> {
681        anyhow::bail!("work projects are not supported by this store")
682    }
683
684    async fn list_work_projects(&self) -> anyhow::Result<Vec<crate::traits::WorkProject>> {
685        Ok(vec![])
686    }
687
688    async fn get_session_work_project(&self, _session_id: &str) -> anyhow::Result<String> {
689        Ok(crate::traits::DEFAULT_PROJECT_ID.to_string())
690    }
691
692    /// Rename a project or change its folder (`Some(None)` clears it).
693    /// `None` when there is no such project.
694    async fn update_work_project(
695        &self,
696        _id: &str,
697        _name: Option<&str>,
698        _path: Option<Option<&str>>,
699    ) -> anyhow::Result<Option<crate::traits::WorkProject>> {
700        anyhow::bail!("work projects are not supported by this store")
701    }
702
703    /// Delete a project: its sessions, goals, runs and journal move to the
704    /// default project, its bots to none, and its worker profiles go with
705    /// it. `false` when there is no such project; the default one cannot
706    /// be deleted.
707    async fn delete_work_project(&self, _id: &str) -> anyhow::Result<bool> {
708        anyhow::bail!("work projects are not supported by this store")
709    }
710
711    /// Every session placed in a project other than the default one, with
712    /// its project id.
713    async fn session_work_projects(&self) -> anyhow::Result<Vec<(String, String)>> {
714        Ok(vec![])
715    }
716
717    async fn set_session_work_project(
718        &self,
719        _session_id: &str,
720        _project_id: &str,
721    ) -> anyhow::Result<bool> {
722        Ok(false)
723    }
724
725    /// Every chat bot sending its direct-message chats to a project: (bot
726    /// channel, project id).
727    async fn channel_work_projects(&self) -> anyhow::Result<Vec<(String, String)>> {
728        Ok(vec![])
729    }
730
731    /// Send bot `channel`'s direct-message chats to `project_id`, or to no
732    /// project (`None`). `false` when there is no such project.
733    async fn set_channel_work_project(
734        &self,
735        _channel: &str,
736        _project_id: Option<&str>,
737    ) -> anyhow::Result<bool> {
738        Ok(false)
739    }
740
741    /// Place a direct-message chat of bot `channel` in that bot's project,
742    /// when the chat was never placed (taking a chat out of its project
743    /// places it in the default one, so that stays). Returns whether it
744    /// was placed now.
745    async fn place_chat_by_channel(
746        &self,
747        _session_id: &str,
748        _channel: &str,
749    ) -> anyhow::Result<bool> {
750        Ok(false)
751    }
752
753    /// Atomically consume the expected occurrence and persist its run and root.
754    /// `None` means the occurrence or its admission state changed; nothing fired.
755    async fn enqueue_scheduled_occurrence(
756        &self,
757        _schedule: &crate::traits::GoalSchedule,
758        _next_run_at: &str,
759        _goal: &crate::traits::Goal,
760        _root: &crate::traits::Task,
761        _effective_daily_budget: Option<i64>,
762    ) -> anyhow::Result<Option<crate::traits::GoalRun>> {
763        anyhow::bail!("atomic scheduled occurrences are not supported by this store")
764    }
765
766    async fn start_goal_run(
767        &self,
768        _goal_id: &str,
769        _trigger_type: &str,
770        _schedule_id: Option<&str>,
771        _root_task_id: Option<&str>,
772    ) -> anyhow::Result<crate::traits::GoalRun> {
773        anyhow::bail!("goal runs are not supported by this store")
774    }
775
776    /// Record an occurrence the scheduler skipped (the daemon was not
777    /// running and it is past its catch-up window) as a closed run with
778    /// status `missed`, started at the time it was due. It is part of the
779    /// automation's history, but never goes through [`Self::finish_goal_run`]:
780    /// a miss is not a failure and leaves the failure budget as it was.
781    async fn record_missed_goal_run(
782        &self,
783        _goal_id: &str,
784        _schedule_id: Option<&str>,
785        _due_at: &str,
786        _summary: &str,
787    ) -> anyhow::Result<crate::traits::GoalRun> {
788        anyhow::bail!("goal runs are not supported by this store")
789    }
790
791    async fn get_current_goal_run(
792        &self,
793        _goal_id: &str,
794    ) -> anyhow::Result<Option<crate::traits::GoalRun>> {
795        Ok(None)
796    }
797
798    async fn get_goal_runs(&self, _goal_id: &str) -> anyhow::Result<Vec<crate::traits::GoalRun>> {
799        Ok(vec![])
800    }
801
802    /// Typed lifecycle owner for a task. Callers must use this relationship,
803    /// never infer run provenance from the task description.
804    async fn get_goal_run_for_task(
805        &self,
806        _task_id: &str,
807    ) -> anyhow::Result<Option<crate::traits::GoalRun>> {
808        Ok(None)
809    }
810
811    async fn get_tasks_for_goal_run(
812        &self,
813        _run_id: &str,
814    ) -> anyhow::Result<Vec<crate::traits::Task>> {
815        Ok(vec![])
816    }
817
818    async fn finish_goal_run(
819        &self,
820        _run_id: &str,
821        _status: &str,
822        _summary: Option<&str>,
823    ) -> anyhow::Result<bool> {
824        Ok(false)
825    }
826
827    async fn claim_task_with_lease(
828        &self,
829        _task_id: &str,
830        _worker_instance_id: &str,
831        _worker_profile_id: Option<&str>,
832        _lease_secs: i64,
833    ) -> anyhow::Result<Option<crate::traits::TaskAttempt>> {
834        Ok(None)
835    }
836
837    async fn get_current_task_attempt(
838        &self,
839        _task_id: &str,
840    ) -> anyhow::Result<Option<crate::traits::TaskAttempt>> {
841        Ok(None)
842    }
843
844    async fn bind_task_attempt_worker(
845        &self,
846        _attempt_id: &str,
847        _lease_token: &str,
848        _worker_instance_id: &str,
849        _worker_profile_id: Option<&str>,
850    ) -> anyhow::Result<bool> {
851        Ok(false)
852    }
853
854    async fn heartbeat_task_attempt(
855        &self,
856        _attempt_id: &str,
857        _lease_token: &str,
858        _lease_secs: i64,
859    ) -> anyhow::Result<bool> {
860        Ok(false)
861    }
862
863    async fn patch_task_from_attempt(
864        &self,
865        _attempt_id: &str,
866        _lease_token: &str,
867        _patch: &crate::traits::TaskAttemptPatch,
868    ) -> anyhow::Result<bool> {
869        Ok(false)
870    }
871
872    /// Release the execution leases a previous daemon process left on
873    /// claimed or running attempts: those started before `started_before`
874    /// (RFC 3339), this process's boot instant, still holding a live lease.
875    /// Each lease ends now and its attempt is journaled
876    /// ([`JOURNAL_PREVIOUS_INSTANCE_STOPPED`](crate::traits::JOURNAL_PREVIOUS_INSTANCE_STOPPED));
877    /// [`recover_expired_task_attempts`](Self::recover_expired_task_attempts)
878    /// then recovers them as it does any expired lease. Only sound at boot,
879    /// under the single-instance lock, so no other live process owns one.
880    /// Also interrupts empty pending scheduled/manual runs created before that
881    /// boot instant: their prior-process creator cannot still attach tasks.
882    /// Returns how many leases were released.
883    async fn expire_attempts_of_previous_instance(
884        &self,
885        _started_before: &str,
886    ) -> anyhow::Result<u64> {
887        Ok(0)
888    }
889
890    /// Boot-swept scheduled roots eligible for a one-time effect-free replay.
891    /// Each pair is (attempt ID, goal run ID); eligibility is rechecked on write.
892    async fn scheduled_restart_replay_candidates(&self) -> anyhow::Result<Vec<(String, String)>> {
893        Ok(vec![])
894    }
895
896    /// The sessions that worked on a goal run's attempts (each attempt's
897    /// worker instance): a task lead's run is found through them. A store
898    /// that cannot answer refuses, so no replay is proven on a partial tree.
899    async fn goal_run_worker_sessions(&self, _goal_run_id: &str) -> anyhow::Result<Vec<String>> {
900        anyhow::bail!("this store does not record attempt worker sessions")
901    }
902
903    /// Replay a boot-swept scheduled root after the runtime proved its entire
904    /// task tree effect-free. The caller must hold the boot single-instance
905    /// boundary, before dispatch starts. Persist the replay allowance atomically.
906    async fn replay_effect_free_scheduled_attempt(
907        &self,
908        _attempt_id: &str,
909    ) -> anyhow::Result<bool> {
910        Ok(false)
911    }
912
913    /// At a requested shutdown, before anything is cancelled: journal every
914    /// attempt still holding a live lease as
915    /// [`JOURNAL_STOPPED_ON_REQUEST`](crate::traits::JOURNAL_STOPPED_ON_REQUEST).
916    /// Its lease is left as it is (the next boot's sweep releases it).
917    /// Returns how many attempts were marked.
918    async fn journal_live_attempts_stopped_on_request(&self) -> anyhow::Result<u64> {
919        Ok(0)
920    }
921
922    /// Scheduled roots a requested stop cut off (their attempt carries
923    /// [`JOURNAL_STOPPED_ON_REQUEST`](crate::traits::JOURNAL_STOPPED_ON_REQUEST)
924    /// and its lease has ended, whether the boot sweep released it or it had
925    /// already lapsed) and not yet resumed once: (attempt ID, goal run ID). Eligibility is rechecked on
926    /// write; whether the tree's changes are settled is the runtime's call.
927    async fn restart_resume_candidates(&self) -> anyhow::Result<Vec<(String, String)>> {
928        Ok(vec![])
929    }
930
931    /// Requeue a stopped-on-request scheduled root once after the runtime proved
932    /// every change its tree made settled, journaling
933    /// [`JOURNAL_RESTART_RESUME`](crate::traits::JOURNAL_RESTART_RESUME)
934    /// with `summary` (what the cut-off run changed) as its payload. The
935    /// caller must hold the boot single-instance boundary.
936    async fn resume_stopped_scheduled_attempt(
937        &self,
938        _attempt_id: &str,
939        _summary: &str,
940    ) -> anyhow::Result<bool> {
941        Ok(false)
942    }
943
944    /// Expire elapsed leases and return the affected task IDs. Idempotent tasks
945    /// with retry budget are re-queued; ambiguous writes require verification.
946    async fn recover_expired_task_attempts(&self) -> anyhow::Result<Vec<String>> {
947        Ok(vec![])
948    }
949
950    /// Whether any worker still holds an unexpired execution lease on an
951    /// attempt belonging to this goal run. While one does, that worker owns
952    /// the run's outcome; lifecycle reconciliation must not race it.
953    async fn goal_run_has_live_attempt(&self, _run_id: &str) -> anyhow::Result<bool> {
954        Ok(false)
955    }
956
957    async fn append_task_journal(
958        &self,
959        _entry: &crate::traits::TaskJournalEntry,
960    ) -> anyhow::Result<()> {
961        Ok(())
962    }
963
964    async fn get_task_journal(
965        &self,
966        _task_id: &str,
967        _limit: i64,
968    ) -> anyhow::Result<Vec<crate::traits::TaskJournalEntry>> {
969        Ok(vec![])
970    }
971
972    async fn unblock_task(
973        &self,
974        _task_id: &str,
975        _resolution: &str,
976        _actor_id: &str,
977        _source_channel: Option<&str>,
978    ) -> anyhow::Result<bool> {
979        Ok(false)
980    }
981
982    async fn retry_work_task(
983        &self,
984        _task_id: &str,
985        _actor_id: &str,
986        _source_channel: Option<&str>,
987    ) -> anyhow::Result<bool> {
988        Ok(false)
989    }
990
991    async fn cancel_work_task(
992        &self,
993        _task_id: &str,
994        _actor_id: &str,
995        _source_channel: Option<&str>,
996    ) -> anyhow::Result<bool> {
997        Ok(false)
998    }
999
1000    async fn upsert_worker_profile(
1001        &self,
1002        _profile: &crate::traits::WorkerProfile,
1003    ) -> anyhow::Result<()> {
1004        Ok(())
1005    }
1006
1007    async fn get_worker_profile(
1008        &self,
1009        _profile_id: &str,
1010    ) -> anyhow::Result<Option<crate::traits::WorkerProfile>> {
1011        Ok(None)
1012    }
1013
1014    async fn list_worker_profiles(
1015        &self,
1016        _project_id: Option<&str>,
1017    ) -> anyhow::Result<Vec<crate::traits::WorkerProfile>> {
1018        Ok(vec![])
1019    }
1020
1021    async fn assign_task_worker_profile(
1022        &self,
1023        _task_id: &str,
1024        _profile_id: &str,
1025        _actor_id: &str,
1026        _source_channel: Option<&str>,
1027    ) -> anyhow::Result<bool> {
1028        Ok(false)
1029    }
1030
1031    async fn set_task_workspace_policy(
1032        &self,
1033        _task_id: &str,
1034        _policy: &str,
1035    ) -> anyhow::Result<bool> {
1036        Ok(false)
1037    }
1038
1039    async fn get_task_workspace_policy(&self, _task_id: &str) -> anyhow::Result<String> {
1040        Ok("shared".to_string())
1041    }
1042
1043    /// Whether the task's workspace policy was set on the task itself
1044    /// (`set_task_workspace_policy`), rather than defaulted or inherited
1045    /// from its worker profile.
1046    async fn task_workspace_policy_is_explicit(&self, _task_id: &str) -> anyhow::Result<bool> {
1047        Ok(false)
1048    }
1049
1050    async fn create_task_workspace(
1051        &self,
1052        _workspace: &crate::traits::TaskWorkspace,
1053    ) -> anyhow::Result<()> {
1054        Ok(())
1055    }
1056
1057    async fn update_task_workspace(
1058        &self,
1059        _workspace: &crate::traits::TaskWorkspace,
1060    ) -> anyhow::Result<()> {
1061        Ok(())
1062    }
1063
1064    async fn get_task_workspace(
1065        &self,
1066        _task_id: &str,
1067    ) -> anyhow::Result<Option<crate::traits::TaskWorkspace>> {
1068        Ok(None)
1069    }
1070
1071    async fn get_latest_task_handoff(
1072        &self,
1073        _task_id: &str,
1074    ) -> anyhow::Result<Option<crate::traits::TaskHandoff>> {
1075        Ok(None)
1076    }
1077
1078    async fn list_work_goals(
1079        &self,
1080        _project_id: &str,
1081        _include_terminal: bool,
1082        _limit: i64,
1083    ) -> anyhow::Result<Vec<crate::traits::WorkGoalSummary>> {
1084        Ok(vec![])
1085    }
1086
1087    async fn list_work_tasks(
1088        &self,
1089        _project_id: &str,
1090        _lane: Option<&str>,
1091        _limit: i64,
1092    ) -> anyhow::Result<Vec<crate::traits::WorkTaskSummary>> {
1093        Ok(vec![])
1094    }
1095}
1096
1097/// Goal lifecycle cleanup and user notification bookkeeping.
1098#[async_trait]
1099pub trait GoalNotificationStore: Send + Sync {
1100    /// Count active evergreen (continuous) goals.
1101    async fn count_active_evergreen_goals(&self) -> anyhow::Result<i64> {
1102        Ok(0)
1103    }
1104
1105    /// Get goals that completed/failed but haven't been notified to the user yet.
1106    async fn get_goals_needing_notification(&self) -> anyhow::Result<Vec<crate::traits::Goal>> {
1107        Ok(vec![])
1108    }
1109
1110    /// Mark a goal as notified (set notified_at timestamp).
1111    async fn mark_goal_notified(&self, _goal_id: &str) -> anyhow::Result<()> {
1112        Ok(())
1113    }
1114
1115    /// Mark stale active goals as abandoned/failed.
1116    ///
1117    /// - Finite orchestration goals: active goals with no update in `stale_hours` → failed
1118    /// - Continuous orchestration goals: skipped (they have their own idle detection)
1119    /// - Personal goals: skipped
1120    ///
1121    /// Returns the number of goals cleaned up.
1122    async fn cleanup_stale_goals(&self, _stale_hours: i64) -> anyhow::Result<u64> {
1123        Ok(0)
1124    }
1125}
1126
1127/// Notification delivery queue persistence.
1128#[async_trait]
1129pub trait NotificationStore: Send + Sync {
1130    /// Record a background sub-agent that has started.
1131    async fn record_background_spawn(
1132        &self,
1133        _spawn: &crate::traits::BackgroundSpawn,
1134    ) -> anyhow::Result<()> {
1135        Ok(())
1136    }
1137
1138    /// Forget a background sub-agent that has ended.
1139    async fn finish_background_spawn(&self, _id: &str) -> anyhow::Result<()> {
1140        Ok(())
1141    }
1142
1143    /// The background sub-agents running for a session.
1144    async fn background_spawns_for_session(
1145        &self,
1146        _session_id: &str,
1147    ) -> anyhow::Result<Vec<crate::traits::BackgroundSpawn>> {
1148        Ok(Vec::new())
1149    }
1150
1151    /// Remove and return every recorded background sub-agent.
1152    async fn take_background_spawns(&self) -> anyhow::Result<Vec<crate::traits::BackgroundSpawn>> {
1153        Ok(Vec::new())
1154    }
1155
1156    /// Enqueue a notification for delivery.
1157    async fn enqueue_notification(
1158        &self,
1159        _entry: &crate::traits::NotificationEntry,
1160    ) -> anyhow::Result<()> {
1161        Ok(())
1162    }
1163
1164    /// Atomically claim a goal's notification slot and enqueue its notification.
1165    ///
1166    /// Returns `false` when another writer has already claimed the goal. Stores
1167    /// that do not support transactions may fall back to enqueueing only.
1168    async fn enqueue_goal_notification(
1169        &self,
1170        entry: &crate::traits::NotificationEntry,
1171    ) -> anyhow::Result<bool> {
1172        self.enqueue_notification(entry).await?;
1173        Ok(true)
1174    }
1175
1176    /// Get pending notifications ordered by priority (critical first), then creation time.
1177    async fn get_pending_notifications(
1178        &self,
1179        _limit: i64,
1180    ) -> anyhow::Result<Vec<crate::traits::NotificationEntry>> {
1181        Ok(vec![])
1182    }
1183
1184    /// Mark a notification as delivered.
1185    async fn mark_notification_delivered(&self, _notification_id: &str) -> anyhow::Result<()> {
1186        Ok(())
1187    }
1188
1189    /// Increment the attempt counter for a notification.
1190    async fn increment_notification_attempt(&self, _notification_id: &str) -> anyhow::Result<()> {
1191        Ok(())
1192    }
1193
1194    /// Delete expired status_update notifications (past their expires_at).
1195    async fn cleanup_expired_notifications(&self) -> anyhow::Result<i64> {
1196        Ok(0)
1197    }
1198
1199    /// Notices delivered to `session_id` at or after `since`, oldest first:
1200    /// what the owner was already told while a turn ran, so its reply can
1201    /// agree with them ([`crate::goals::notices_turn_context`]).
1202    async fn notices_delivered_since(
1203        &self,
1204        _session_id: &str,
1205        _since: chrono::DateTime<chrono::Utc>,
1206    ) -> anyhow::Result<Vec<crate::traits::DeliveredNotice>> {
1207        Ok(Vec::new())
1208    }
1209}
1210
1211/// Focused persistence contract used by mandate management. Includes the
1212/// schedule and scheduled-run lifecycle so the mandate surface can project
1213/// its controller goal's authoritative objective status.
1214pub trait MandateToolStore:
1215    MandateStore
1216    + GoalStore
1217    + WorkCoordinationStore
1218    + aidaemon_channels::hub::SessionChannelStore
1219    + GoalBudgetStore
1220    + GoalScheduleStore
1221    + ScheduledRunStore
1222{
1223}
1224
1225impl<T> MandateToolStore for T where
1226    T: MandateStore
1227        + GoalStore
1228        + WorkCoordinationStore
1229        + aidaemon_channels::hub::SessionChannelStore
1230        + GoalBudgetStore
1231        + GoalScheduleStore
1232        + ScheduledRunStore
1233{
1234}
1235
1236/// Focused persistence contract used by goal-trace tooling.
1237pub trait GoalTraceStore:
1238    GoalStore + GoalScheduleStore + MandateStore + TaskStore + WorkCoordinationStore + ScheduledRunStore
1239{
1240}
1241
1242impl<T> GoalTraceStore for T where
1243    T: GoalStore
1244        + GoalScheduleStore
1245        + MandateStore
1246        + TaskStore
1247        + WorkCoordinationStore
1248        + ScheduledRunStore
1249{
1250}
1251
1252/// Focused persistence contract used by goal task management.
1253pub trait ManageGoalTasksStore:
1254    GoalStore + TaskStore + MandateStore + WorkCoordinationStore + NotificationStore
1255{
1256}
1257
1258impl<T> ManageGoalTasksStore for T where
1259    T: GoalStore + TaskStore + MandateStore + WorkCoordinationStore + NotificationStore
1260{
1261}
1262
1263/// Focused persistence contract used by the automation surfaces (scheduled
1264/// goals, reminders and mandates): everything their two engines' tools take.
1265pub trait AutomationStore:
1266    MandateToolStore + ScheduledGoalRunsStore + GoalNotificationStore
1267{
1268}
1269
1270impl<T> AutomationStore for T where
1271    T: MandateToolStore + ScheduledGoalRunsStore + GoalNotificationStore
1272{
1273}
1274
1275/// Focused persistence contract used by blocker reporting.
1276pub trait ReportBlockerStore:
1277    TaskStore + GoalStore + NotificationStore + WorkCoordinationStore
1278{
1279}
1280
1281impl<T> ReportBlockerStore for T where
1282    T: TaskStore + GoalStore + NotificationStore + WorkCoordinationStore
1283{
1284}
1285
1286/// Focused persistence contract used by scheduled-goal tooling.
1287pub trait ScheduledGoalRunsStore:
1288    GoalStore
1289    + GoalScheduleStore
1290    + ScheduledRunStore
1291    + GoalBudgetStore
1292    + TaskStore
1293    + WorkCoordinationStore
1294    + SettingsStore
1295    + MandateStore
1296{
1297}
1298
1299impl<T> ScheduledGoalRunsStore for T where
1300    T: GoalStore
1301        + GoalScheduleStore
1302        + ScheduledRunStore
1303        + GoalBudgetStore
1304        + TaskStore
1305        + WorkCoordinationStore
1306        + SettingsStore
1307        + MandateStore
1308{
1309}
1310
1311/// Database health check: verifies the connection is alive. The scheduler's
1312/// [`DbHealthGate`](crate::heartbeat::DbHealthGate) skips a tick while it fails.
1313#[async_trait]
1314pub trait HealthCheckStore: Send + Sync {
1315    async fn health_check(&self) -> anyhow::Result<()> {
1316        Ok(())
1317    }
1318}