aidaemon-work 0.25.1

Goals, mandates, tasks and work coordination with a SQLite store; internal to aidaemon, no stability promise
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
//! The store traits for goals, mandates, tasks, work and notifications.

use aidaemon_tools::services::SettingsStore;
use async_trait::async_trait;

/// Goal lifecycle and confirmation-flow persistence. Task, schedule, budget,
/// scheduled-run, dispatch, and notification concerns live in the sibling
/// traits: [`TaskStore`], [`GoalScheduleStore`], [`GoalBudgetStore`],
/// [`ScheduledRunStore`], [`TaskDispatchStore`], and [`GoalNotificationStore`].
#[async_trait]
pub trait GoalStore: Send + Sync {
    /// Create a new goal.
    async fn create_goal(&self, _goal: &crate::traits::Goal) -> anyhow::Result<()> {
        Ok(())
    }

    /// Get a goal by ID.
    async fn get_goal(&self, _id: &str) -> anyhow::Result<Option<crate::traits::Goal>> {
        Ok(None)
    }

    /// Update a goal (full replacement).
    async fn update_goal(&self, _goal: &crate::traits::Goal) -> anyhow::Result<()> {
        Ok(())
    }

    /// Get all active orchestration goals (status = "active" or "pending").
    async fn get_active_goals(&self) -> anyhow::Result<Vec<crate::traits::Goal>> {
        Ok(vec![])
    }

    /// Get active personal goals (tracked, never dispatched).
    async fn get_active_personal_goals(
        &self,
        _limit: i64,
    ) -> anyhow::Result<Vec<crate::traits::Goal>> {
        Ok(vec![])
    }

    /// Update a personal goal's status and/or append a progress note.
    async fn update_personal_goal(
        &self,
        _goal_id: &str,
        _status: Option<&str>,
        _progress_note: Option<&str>,
    ) -> anyhow::Result<()> {
        Ok(())
    }

    /// Get orchestration goals for a specific session.
    async fn get_goals_for_session(
        &self,
        _session_id: &str,
    ) -> anyhow::Result<Vec<crate::traits::Goal>> {
        Ok(vec![])
    }

    /// Get scheduled goals awaiting confirmation in a session.
    async fn get_pending_confirmation_goals(
        &self,
        _session_id: &str,
    ) -> anyhow::Result<Vec<crate::traits::Goal>> {
        Ok(vec![])
    }

    /// Activate a pending-confirmation goal.
    /// Returns true when the status transition was applied.
    async fn activate_goal(&self, _goal_id: &str) -> anyhow::Result<bool> {
        Ok(false)
    }
}

/// Owner mandates, agent deliberation cycles, and intentions.
#[async_trait]
pub trait MandateStore: Send + Sync {
    /// Atomically create the continuous controller goal and its mandate.
    /// Adaptive review timing lives on the mandate, not in `goal_schedules`.
    async fn create_mandate_controller(
        &self,
        _goal: &crate::traits::Goal,
        _mandate: &crate::traits::Mandate,
    ) -> anyhow::Result<()> {
        anyhow::bail!("mandate controllers are not supported by this store")
    }

    async fn get_mandate(&self, _id: &str) -> anyhow::Result<Option<crate::traits::Mandate>> {
        Ok(None)
    }

    async fn get_mandate_for_goal(
        &self,
        _goal_id: &str,
    ) -> anyhow::Result<Option<crate::traits::Mandate>> {
        Ok(None)
    }

    async fn list_mandates(
        &self,
        _session_id: Option<&str>,
        _include_terminal: bool,
    ) -> anyhow::Result<Vec<crate::traits::Mandate>> {
        Ok(Vec::new())
    }

    /// Authorize one exact presentation session through the mandate's stable
    /// principal mapping. Session-string similarity is never sufficient.
    async fn is_mandate_session_authorized(
        &self,
        _mandate_id: &str,
        _session_id: &str,
    ) -> anyhow::Result<bool> {
        Ok(false)
    }

    /// Append one receipt-backed metric observation for the exact current
    /// mandate run and policy version.
    async fn record_mandate_objective_measurement(
        &self,
        _measurement: &crate::traits::MandateObjectiveMeasurement,
    ) -> anyhow::Result<()> {
        anyhow::bail!("mandate objective measurements are not supported by this store")
    }

    async fn list_mandate_objective_measurements(
        &self,
        _mandate_id: &str,
        _limit: i64,
    ) -> anyhow::Result<Vec<crate::traits::MandateObjectiveMeasurement>> {
        Ok(Vec::new())
    }

    /// Optimistic owner-policy update. `mandate.version` must be exactly one
    /// greater than the currently stored version.
    async fn update_mandate(&self, _mandate: &crate::traits::Mandate) -> anyhow::Result<()> {
        anyhow::bail!("mandates are not supported by this store")
    }

    /// Atomically consume an explicit owner confirmation and activate both the
    /// mandate and its continuous controller. This is the only path that may
    /// turn an unconfirmed mandate into active authority.
    async fn confirm_mandate(
        &self,
        _mandate_id: &str,
        _expected_version: i64,
        _activation_duration_secs: Option<i64>,
    ) -> anyhow::Result<bool> {
        Ok(false)
    }

    /// Atomic lifecycle/authority-epoch transition. Implementations must
    /// invalidate open decision runs and stale ACT authority before returning.
    async fn transition_mandate_status(
        &self,
        _mandate_id: &str,
        _from_status: crate::traits::MandateStatus,
        _to_status: crate::traits::MandateStatus,
    ) -> anyhow::Result<bool> {
        Ok(false)
    }

    /// Resume a paused/awaiting-input mandate and update its controller
    /// context in the same expected-version transaction. This prevents owner
    /// guidance from overwriting a concurrent cancel/pause lifecycle state.
    async fn resume_mandate_with_context(
        &self,
        _mandate_id: &str,
        _from_status: crate::traits::MandateStatus,
        _expected_version: i64,
        _controller_context: Option<&str>,
    ) -> anyhow::Result<bool> {
        Ok(false)
    }

    /// Record a late owner answer on an active mandate by replacing its
    /// controller context, fenced on the mandate still being active at the
    /// expected version for this owner. Authority is never touched.
    async fn record_active_mandate_owner_guidance(
        &self,
        _mandate_id: &str,
        _expected_version: i64,
        _owner_session: &str,
        _controller_context: &str,
    ) -> anyhow::Result<bool> {
        Ok(false)
    }

    /// Atomically create one mandate review run and its root task under the
    /// caller's current review lease. A failed root insert must
    /// leave no open run behind.
    async fn create_mandate_review_run(
        &self,
        _mandate_id: &str,
        _review_lease_token: &str,
        _goal_run_id: &str,
        _root_task: &crate::traits::Task,
    ) -> anyhow::Result<crate::traits::GoalRun> {
        anyhow::bail!("mandate review runs are not supported by this store")
    }

    /// Repair controller runtime state only while the exact mandate authority
    /// epoch is still active. The state check and goal update must be one
    /// atomic database statement so a racing owner pause/cancel wins.
    async fn keep_mandate_controller_active(
        &self,
        _mandate_id: &str,
        _expected_version: i64,
    ) -> anyhow::Result<bool> {
        Ok(false)
    }

    /// Claim due reviews with a durable lease. Concurrent callers must never
    /// receive the same mandate before the lease expires.
    async fn claim_due_mandates(
        &self,
        _limit: i64,
        _lease_owner: &str,
        _lease_secs: i64,
    ) -> anyhow::Result<Vec<crate::traits::Mandate>> {
        Ok(Vec::new())
    }

    async fn release_mandate_review_lease(
        &self,
        _mandate_id: &str,
        _lease_token: &str,
        _retry_at: &str,
    ) -> anyhow::Result<bool> {
        Ok(false)
    }

    /// Insert one non-root action task into an exact mandate run while the
    /// dispatcher-owned root attempt remains current. Implementations must
    /// validate the mandate/run/attempt fence and task cap atomically and must
    /// never create or rebind a goal run by goal id.
    async fn create_mandate_task_from_attempt(
        &self,
        _task: &crate::traits::Task,
        _mandate_id: &str,
        _mandate_version: i64,
        _goal_run_id: &str,
        _root_task_attempt_id: &str,
        _max_non_root_tasks: i64,
    ) -> anyhow::Result<bool> {
        Ok(false)
    }

    /// Claim one pending non-root task inside an exact running mandate cycle.
    /// The root task-attempt remains the control-plane lease; the returned
    /// child attempt deliberately carries no worker-profile/workspace binding.
    /// The independently fenced identifiers remain explicit because wrapping
    /// them would churn the stable store API without reducing validation work.
    #[allow(clippy::too_many_arguments)]
    async fn claim_mandate_task_from_attempt(
        &self,
        _task_id: &str,
        _worker_instance_id: &str,
        _mandate_id: &str,
        _mandate_version: i64,
        _goal_run_id: &str,
        _root_task_attempt_id: &str,
        _lease_secs: i64,
    ) -> anyhow::Result<Option<crate::traits::TaskAttempt>> {
        Ok(None)
    }

    /// Insert exactly one deliberation result for a goal run, plus its ACT
    /// intention when present. Implementations must commit both atomically.
    async fn record_mandate_decision(
        &self,
        _decision: &crate::traits::MandateDecisionCycle,
        _intention: Option<&crate::traits::Intention>,
        _task_attempt_id: Option<&str>,
    ) -> anyhow::Result<()> {
        anyhow::bail!("mandate decisions are not supported by this store")
    }

    async fn record_mandate_decision_with_updates(
        &self,
        decision: &crate::traits::MandateDecisionCycle,
        intention: Option<&crate::traits::Intention>,
        operating_updates: Option<&crate::traits::MandateOperatingUpdates>,
        task_attempt_id: Option<&str>,
    ) -> anyhow::Result<()> {
        anyhow::ensure!(
            operating_updates.is_none_or(|updates| updates.learning_note.is_none()),
            "adaptive mandate operating updates are not supported by this store"
        );
        self.record_mandate_decision(decision, intention, task_attempt_id)
            .await
    }

    async fn get_mandate_decision_for_run(
        &self,
        _goal_run_id: &str,
    ) -> anyhow::Result<Option<crate::traits::MandateDecisionCycle>> {
        Ok(None)
    }

    /// Tool-call ids of the run's successful structured receipts that may
    /// back a decision or measurement (newest first, at most `limit`): the
    /// same receipts `evidence_receipt_ids` accepts, minus the mandate
    /// protocol's own control tools.
    async fn current_run_evidence_receipt_ids(
        &self,
        _goal_run_id: &str,
        _limit: usize,
    ) -> anyhow::Result<Vec<String>> {
        Ok(Vec::new())
    }

    async fn list_mandate_decisions(
        &self,
        _mandate_id: &str,
        _limit: i64,
    ) -> anyhow::Result<Vec<crate::traits::MandateDecisionCycle>> {
        Ok(Vec::new())
    }

    async fn list_intentions(
        &self,
        _mandate_id: &str,
        _limit: i64,
    ) -> anyhow::Result<Vec<crate::traits::Intention>> {
        Ok(Vec::new())
    }

    /// Persist one bounded, advisory learning note only after all cited
    /// receipts are proven to belong to this mandate.
    async fn record_mandate_learning_note(
        &self,
        _note: &crate::traits::MandateLearningNote,
    ) -> anyhow::Result<()> {
        anyhow::bail!("mandate learning is not supported by this store")
    }

    async fn list_mandate_learning_notes(
        &self,
        _mandate_id: &str,
        _limit: i64,
    ) -> anyhow::Result<Vec<crate::traits::MandateLearningNote>> {
        Ok(Vec::new())
    }

    /// Deduplicate and route one content-free external signal to matching
    /// Autopilot mandates. Matching is structural and cannot widen authority.
    async fn wake_mandates_for_signal(
        &self,
        _signal: &crate::traits::MandateWakeSignal,
    ) -> anyhow::Result<Vec<String>> {
        Ok(Vec::new())
    }

    /// Resolve an awaiting-input state with a typed owner action. Question
    /// answers and external-effect reconciliation are intentionally distinct.
    #[allow(clippy::too_many_arguments)]
    async fn resolve_mandate_suspension(
        &self,
        _mandate_id: &str,
        _expected_version: i64,
        _expected_kind: crate::traits::MandateSuspensionKind,
        _controller_context: Option<&str>,
        _reconciliation_resolution: Option<crate::traits::MandateReconciliationResolution>,
        _owner_guidance: &str,
        _owner_session: &str,
    ) -> anyhow::Result<bool> {
        Ok(false)
    }

    /// Atomically reserve the exact next mutation attempt under the current
    /// cycle, rolling-24h, cooldown, mandate, run, intention, task, and lease
    /// fences. Implementations must insert the durable ledger row and advance
    /// the cycle counter in one transaction.
    async fn reserve_mandate_action_attempt(
        &self,
        _reservation: &crate::traits::MandateMutationReservation,
    ) -> anyhow::Result<Option<crate::traits::MandateMutationAttempt>> {
        Ok(None)
    }

    /// Atomically claim one exact reserved mutation at the last common
    /// dispatcher. A claim is one-use and must fail if any authority, run,
    /// task-attempt, tool-call, digest, or reservation field is stale.
    async fn claim_mandate_mutation_dispatch(
        &self,
        _claim: &crate::traits::MandateMutationDispatchClaim,
    ) -> anyhow::Result<bool> {
        Ok(false)
    }

    /// Read the typed, cross-cycle mutation quota projection at one instant.
    /// This is advisory for deliberation; reservation remains authoritative.
    async fn get_mandate_mutation_quota_state(
        &self,
        _mandate_id: &str,
        _as_of: &str,
    ) -> anyhow::Result<Option<crate::traits::MandateMutationQuotaState>> {
        Ok(None)
    }

    async fn list_mandate_mutation_attempts_for_run(
        &self,
        _goal_run_id: &str,
    ) -> anyhow::Result<Vec<crate::traits::MandateMutationAttempt>> {
        Ok(Vec::new())
    }

    /// Atomically prove and close a mandate run. Satisfied outcomes close the
    /// goal run (and ACT intention) inside the proof transaction; reconciliation
    /// results leave lifecycle state untouched for the caller's explicit path.
    async fn finalize_mandate_run_from_proof(
        &self,
        _request: &crate::traits::MandateRunFinalizationRequest,
    ) -> anyhow::Result<crate::traits::MandateRunFinalizationResult> {
        Ok(crate::traits::MandateRunFinalizationResult::Rejected {
            reason: crate::traits::MandateFinalizationRejectReason::InvalidRequest,
        })
    }
}

/// Task persistence and task activity logs.
#[async_trait]
pub trait TaskStore: Send + Sync {
    /// Create a new task within a goal.
    async fn create_task(&self, _task: &crate::traits::Task) -> anyhow::Result<()> {
        Ok(())
    }

    /// Get a task by ID.
    async fn get_task(&self, _id: &str) -> anyhow::Result<Option<crate::traits::Task>> {
        Ok(None)
    }

    /// Update a task (full replacement).
    async fn update_task(&self, _task: &crate::traits::Task) -> anyhow::Result<()> {
        Ok(())
    }

    /// Get all tasks for a goal.
    async fn get_tasks_for_goal(&self, _goal_id: &str) -> anyhow::Result<Vec<crate::traits::Task>> {
        Ok(vec![])
    }

    /// Count completed/skipped tasks for a goal (used by progress-based circuit breaker).
    async fn count_completed_tasks_for_goal(&self, _goal_id: &str) -> anyhow::Result<i64> {
        Ok(0)
    }

    /// Atomically claim a pending task for an executor.
    async fn claim_task(&self, _task_id: &str, _agent_id: &str) -> anyhow::Result<bool> {
        Ok(false)
    }

    /// Log an activity entry for a task.
    async fn log_task_activity(
        &self,
        _activity: &crate::traits::TaskActivity,
    ) -> anyhow::Result<()> {
        Ok(())
    }

    /// Get activity log for a task.
    async fn get_task_activities(
        &self,
        _task_id: &str,
    ) -> anyhow::Result<Vec<crate::traits::TaskActivity>> {
        Ok(vec![])
    }
}

/// Goal schedule and scheduled-run persistence.
#[async_trait]
pub trait GoalScheduleStore: Send + Sync {
    /// Create a new schedule for a goal.
    async fn create_goal_schedule(
        &self,
        _schedule: &crate::traits::GoalSchedule,
    ) -> anyhow::Result<()> {
        Ok(())
    }

    /// Get a schedule by ID.
    async fn get_goal_schedule(
        &self,
        _schedule_id: &str,
    ) -> anyhow::Result<Option<crate::traits::GoalSchedule>> {
        Ok(None)
    }

    /// List schedules for a goal.
    async fn get_schedules_for_goal(
        &self,
        _goal_id: &str,
    ) -> anyhow::Result<Vec<crate::traits::GoalSchedule>> {
        Ok(vec![])
    }

    /// Get due schedules for active orchestration goals.
    async fn get_due_goal_schedules(
        &self,
        _limit: i64,
    ) -> anyhow::Result<Vec<crate::traits::GoalSchedule>> {
        Ok(vec![])
    }

    /// Update a schedule (full replacement).
    async fn update_goal_schedule(
        &self,
        _schedule: &crate::traits::GoalSchedule,
    ) -> anyhow::Result<()> {
        Ok(())
    }

    /// Delete a schedule by ID. Returns true if a row was deleted.
    async fn delete_goal_schedule(&self, _schedule_id: &str) -> anyhow::Result<bool> {
        Ok(false)
    }

    /// Cancel pending-confirmation goals older than max_age_secs.
    async fn cancel_stale_pending_confirmation_goals(
        &self,
        _max_age_secs: i64,
    ) -> anyhow::Result<u64> {
        Ok(0)
    }

    /// Get all orchestration goals that have schedules or are awaiting confirmation.
    async fn get_scheduled_goals(&self) -> anyhow::Result<Vec<crate::traits::Goal>> {
        Ok(vec![])
    }

    /// Active continuous orchestration goals with no schedule and no mandate
    /// behind them: nothing will ever run them. Listed so they can be seen
    /// and cancelled.
    async fn get_unscheduled_active_goals(&self) -> anyhow::Result<Vec<crate::traits::Goal>> {
        Ok(vec![])
    }
}

/// Goal token budget persistence and accounting.
#[async_trait]
pub trait GoalBudgetStore: Send + Sync {
    /// Reset tokens_used_today only for active goals whose usage belongs to a
    /// prior UTC day. Safe to call repeatedly or at process startup.
    async fn reset_daily_token_budgets(&self) -> anyhow::Result<u64> {
        Ok(0)
    }

    /// Update budget columns only. `None` = keep current value (COALESCE), NOT "clear to NULL".
    /// This is a targeted UPDATE that avoids the race with `add_goal_tokens_and_get_budget_status()`
    /// which atomically increments `tokens_used_today` — a full `update_goal()` would clobber that.
    async fn set_goal_budgets(
        &self,
        _goal_id: &str,
        _budget_per_check: Option<i64>,
        _budget_daily: Option<i64>,
    ) -> anyhow::Result<()> {
        Ok(())
    }

    /// Atomically add tokens to a goal's daily usage counter and return budget status.
    ///
    /// Use `delta_tokens = 0` to read the latest counters without modifying them.
    async fn add_goal_tokens_and_get_budget_status(
        &self,
        _goal_id: &str,
        _delta_tokens: i64,
    ) -> anyhow::Result<Option<crate::traits::GoalTokenBudgetStatus>> {
        Ok(None)
    }
}

/// Scheduled run runtime-state persistence.
#[async_trait]
pub trait ScheduledRunStore: Send + Sync {
    /// Persist runtime state for an active scheduled run.
    async fn upsert_scheduled_run_state(
        &self,
        _state: &crate::traits::ScheduledRunState,
    ) -> anyhow::Result<()> {
        Ok(())
    }

    /// Load persisted runtime state for an active scheduled run.
    async fn get_scheduled_run_state(
        &self,
        _goal_id: &str,
    ) -> anyhow::Result<Option<crate::traits::ScheduledRunState>> {
        Ok(None)
    }

    async fn get_scheduled_recovery_state(
        &self,
        _goal_id: &str,
    ) -> anyhow::Result<Option<crate::traits::ScheduledRecoveryState>> {
        Ok(None)
    }

    /// Escalated scheduled objectives that the recovery machine itself paused,
    /// whose cool-down has elapsed and whose automatic recovery attempts are
    /// still under the cap.
    async fn list_escalated_recovery_candidates(
        &self,
        _cooldown_secs: i64,
        _max_attempts: u16,
    ) -> anyhow::Result<Vec<crate::traits::ScheduledRecoveryState>> {
        Ok(Vec::new())
    }

    /// Record that an automatic recovery run was launched for the goal.
    async fn record_scheduled_recovery_attempt(&self, _goal_id: &str) -> anyhow::Result<()> {
        Ok(())
    }

    /// Delete persisted runtime state for an active scheduled run.
    async fn delete_scheduled_run_state(&self, _goal_id: &str) -> anyhow::Result<bool> {
        Ok(false)
    }
}

/// Task dispatch bookkeeping for executor scheduling and recovery.
#[async_trait]
pub trait TaskDispatchStore: Send + Sync {
    /// Get pending tasks ordered by priority, filtering out those with unmet dependencies.
    async fn get_pending_tasks_by_priority(
        &self,
        _limit: i64,
    ) -> anyhow::Result<Vec<crate::traits::Task>> {
        Ok(vec![])
    }

    /// Get tasks stuck in running/claimed state longer than timeout_secs.
    async fn get_stuck_tasks(
        &self,
        _timeout_secs: i64,
    ) -> anyhow::Result<Vec<crate::traits::Task>> {
        Ok(vec![])
    }

    /// Get tasks completed after a given timestamp.
    async fn get_recently_completed_tasks(
        &self,
        _since: &str,
    ) -> anyhow::Result<Vec<crate::traits::Task>> {
        Ok(vec![])
    }

    /// Mark a running/claimed task as interrupted (e.g., after crash or timeout).
    async fn mark_task_interrupted(&self, _task_id: &str) -> anyhow::Result<bool> {
        Ok(false)
    }
}

/// Durable coordination for goal runs, fenced task attempts, collaboration
/// records, named worker policies, project scope, and attempt workspaces.
#[async_trait]
pub trait WorkCoordinationStore: Send + Sync {
    async fn create_work_project(
        &self,
        _name: &str,
        _description: Option<&str>,
    ) -> anyhow::Result<crate::traits::WorkProject> {
        anyhow::bail!("work projects are not supported by this store")
    }

    async fn list_work_projects(&self) -> anyhow::Result<Vec<crate::traits::WorkProject>> {
        Ok(vec![])
    }

    async fn get_session_work_project(&self, _session_id: &str) -> anyhow::Result<String> {
        Ok(crate::traits::DEFAULT_PROJECT_ID.to_string())
    }

    /// Rename a project or change its folder (`Some(None)` clears it).
    /// `None` when there is no such project.
    async fn update_work_project(
        &self,
        _id: &str,
        _name: Option<&str>,
        _path: Option<Option<&str>>,
    ) -> anyhow::Result<Option<crate::traits::WorkProject>> {
        anyhow::bail!("work projects are not supported by this store")
    }

    /// Delete a project: its sessions, goals, runs and journal move to the
    /// default project, its bots to none, and its worker profiles go with
    /// it. `false` when there is no such project; the default one cannot
    /// be deleted.
    async fn delete_work_project(&self, _id: &str) -> anyhow::Result<bool> {
        anyhow::bail!("work projects are not supported by this store")
    }

    /// Every session placed in a project other than the default one, with
    /// its project id.
    async fn session_work_projects(&self) -> anyhow::Result<Vec<(String, String)>> {
        Ok(vec![])
    }

    async fn set_session_work_project(
        &self,
        _session_id: &str,
        _project_id: &str,
    ) -> anyhow::Result<bool> {
        Ok(false)
    }

    /// Every chat bot sending its direct-message chats to a project: (bot
    /// channel, project id).
    async fn channel_work_projects(&self) -> anyhow::Result<Vec<(String, String)>> {
        Ok(vec![])
    }

    /// Send bot `channel`'s direct-message chats to `project_id`, or to no
    /// project (`None`). `false` when there is no such project.
    async fn set_channel_work_project(
        &self,
        _channel: &str,
        _project_id: Option<&str>,
    ) -> anyhow::Result<bool> {
        Ok(false)
    }

    /// Place a direct-message chat of bot `channel` in that bot's project,
    /// when the chat was never placed (taking a chat out of its project
    /// places it in the default one, so that stays). Returns whether it
    /// was placed now.
    async fn place_chat_by_channel(
        &self,
        _session_id: &str,
        _channel: &str,
    ) -> anyhow::Result<bool> {
        Ok(false)
    }

    async fn start_goal_run(
        &self,
        _goal_id: &str,
        _trigger_type: &str,
        _schedule_id: Option<&str>,
        _root_task_id: Option<&str>,
    ) -> anyhow::Result<crate::traits::GoalRun> {
        anyhow::bail!("goal runs are not supported by this store")
    }

    /// Record an occurrence the scheduler skipped (the daemon was not
    /// running and it is past its catch-up window) as a closed run with
    /// status `missed`, started at the time it was due. It is part of the
    /// automation's history, but never goes through [`Self::finish_goal_run`]:
    /// a miss is not a failure and leaves the failure budget as it was.
    async fn record_missed_goal_run(
        &self,
        _goal_id: &str,
        _schedule_id: Option<&str>,
        _due_at: &str,
        _summary: &str,
    ) -> anyhow::Result<crate::traits::GoalRun> {
        anyhow::bail!("goal runs are not supported by this store")
    }

    async fn get_current_goal_run(
        &self,
        _goal_id: &str,
    ) -> anyhow::Result<Option<crate::traits::GoalRun>> {
        Ok(None)
    }

    async fn get_goal_runs(&self, _goal_id: &str) -> anyhow::Result<Vec<crate::traits::GoalRun>> {
        Ok(vec![])
    }

    /// Typed lifecycle owner for a task. Callers must use this relationship,
    /// never infer run provenance from the task description.
    async fn get_goal_run_for_task(
        &self,
        _task_id: &str,
    ) -> anyhow::Result<Option<crate::traits::GoalRun>> {
        Ok(None)
    }

    async fn get_tasks_for_goal_run(
        &self,
        _run_id: &str,
    ) -> anyhow::Result<Vec<crate::traits::Task>> {
        Ok(vec![])
    }

    async fn finish_goal_run(
        &self,
        _run_id: &str,
        _status: &str,
        _summary: Option<&str>,
    ) -> anyhow::Result<bool> {
        Ok(false)
    }

    async fn claim_task_with_lease(
        &self,
        _task_id: &str,
        _worker_instance_id: &str,
        _worker_profile_id: Option<&str>,
        _lease_secs: i64,
    ) -> anyhow::Result<Option<crate::traits::TaskAttempt>> {
        Ok(None)
    }

    async fn get_current_task_attempt(
        &self,
        _task_id: &str,
    ) -> anyhow::Result<Option<crate::traits::TaskAttempt>> {
        Ok(None)
    }

    async fn bind_task_attempt_worker(
        &self,
        _attempt_id: &str,
        _lease_token: &str,
        _worker_instance_id: &str,
        _worker_profile_id: Option<&str>,
    ) -> anyhow::Result<bool> {
        Ok(false)
    }

    async fn heartbeat_task_attempt(
        &self,
        _attempt_id: &str,
        _lease_token: &str,
        _lease_secs: i64,
    ) -> anyhow::Result<bool> {
        Ok(false)
    }

    async fn patch_task_from_attempt(
        &self,
        _attempt_id: &str,
        _lease_token: &str,
        _patch: &crate::traits::TaskAttemptPatch,
    ) -> anyhow::Result<bool> {
        Ok(false)
    }

    /// Expire elapsed leases and return the affected task IDs. Idempotent tasks
    /// with retry budget are re-queued; ambiguous writes require verification.
    async fn recover_expired_task_attempts(&self) -> anyhow::Result<Vec<String>> {
        Ok(vec![])
    }

    /// Whether any worker still holds an unexpired execution lease on an
    /// attempt belonging to this goal run. While one does, that worker owns
    /// the run's outcome; lifecycle reconciliation must not race it.
    async fn goal_run_has_live_attempt(&self, _run_id: &str) -> anyhow::Result<bool> {
        Ok(false)
    }

    async fn append_task_journal(
        &self,
        _entry: &crate::traits::TaskJournalEntry,
    ) -> anyhow::Result<()> {
        Ok(())
    }

    async fn get_task_journal(
        &self,
        _task_id: &str,
        _limit: i64,
    ) -> anyhow::Result<Vec<crate::traits::TaskJournalEntry>> {
        Ok(vec![])
    }

    async fn unblock_task(
        &self,
        _task_id: &str,
        _resolution: &str,
        _actor_id: &str,
        _source_channel: Option<&str>,
    ) -> anyhow::Result<bool> {
        Ok(false)
    }

    async fn retry_work_task(
        &self,
        _task_id: &str,
        _actor_id: &str,
        _source_channel: Option<&str>,
    ) -> anyhow::Result<bool> {
        Ok(false)
    }

    async fn cancel_work_task(
        &self,
        _task_id: &str,
        _actor_id: &str,
        _source_channel: Option<&str>,
    ) -> anyhow::Result<bool> {
        Ok(false)
    }

    async fn upsert_worker_profile(
        &self,
        _profile: &crate::traits::WorkerProfile,
    ) -> anyhow::Result<()> {
        Ok(())
    }

    async fn get_worker_profile(
        &self,
        _profile_id: &str,
    ) -> anyhow::Result<Option<crate::traits::WorkerProfile>> {
        Ok(None)
    }

    async fn list_worker_profiles(
        &self,
        _project_id: Option<&str>,
    ) -> anyhow::Result<Vec<crate::traits::WorkerProfile>> {
        Ok(vec![])
    }

    async fn assign_task_worker_profile(
        &self,
        _task_id: &str,
        _profile_id: &str,
        _actor_id: &str,
        _source_channel: Option<&str>,
    ) -> anyhow::Result<bool> {
        Ok(false)
    }

    async fn set_task_workspace_policy(
        &self,
        _task_id: &str,
        _policy: &str,
    ) -> anyhow::Result<bool> {
        Ok(false)
    }

    async fn get_task_workspace_policy(&self, _task_id: &str) -> anyhow::Result<String> {
        Ok("shared".to_string())
    }

    /// Whether the task's workspace policy was set on the task itself
    /// (`set_task_workspace_policy`), rather than defaulted or inherited
    /// from its worker profile.
    async fn task_workspace_policy_is_explicit(&self, _task_id: &str) -> anyhow::Result<bool> {
        Ok(false)
    }

    async fn create_task_workspace(
        &self,
        _workspace: &crate::traits::TaskWorkspace,
    ) -> anyhow::Result<()> {
        Ok(())
    }

    async fn update_task_workspace(
        &self,
        _workspace: &crate::traits::TaskWorkspace,
    ) -> anyhow::Result<()> {
        Ok(())
    }

    async fn get_task_workspace(
        &self,
        _task_id: &str,
    ) -> anyhow::Result<Option<crate::traits::TaskWorkspace>> {
        Ok(None)
    }

    async fn get_latest_task_handoff(
        &self,
        _task_id: &str,
    ) -> anyhow::Result<Option<crate::traits::TaskHandoff>> {
        Ok(None)
    }

    async fn list_work_goals(
        &self,
        _project_id: &str,
        _include_terminal: bool,
        _limit: i64,
    ) -> anyhow::Result<Vec<crate::traits::WorkGoalSummary>> {
        Ok(vec![])
    }

    async fn list_work_tasks(
        &self,
        _project_id: &str,
        _lane: Option<&str>,
        _limit: i64,
    ) -> anyhow::Result<Vec<crate::traits::WorkTaskSummary>> {
        Ok(vec![])
    }
}

/// Goal lifecycle cleanup and user notification bookkeeping.
#[async_trait]
pub trait GoalNotificationStore: Send + Sync {
    /// Count active evergreen (continuous) goals.
    async fn count_active_evergreen_goals(&self) -> anyhow::Result<i64> {
        Ok(0)
    }

    /// Get goals that completed/failed but haven't been notified to the user yet.
    async fn get_goals_needing_notification(&self) -> anyhow::Result<Vec<crate::traits::Goal>> {
        Ok(vec![])
    }

    /// Mark a goal as notified (set notified_at timestamp).
    async fn mark_goal_notified(&self, _goal_id: &str) -> anyhow::Result<()> {
        Ok(())
    }

    /// Mark stale active goals as abandoned/failed.
    ///
    /// - Finite orchestration goals: active goals with no update in `stale_hours` → failed
    /// - Continuous orchestration goals: skipped (they have their own idle detection)
    /// - Personal goals: skipped
    ///
    /// Returns the number of goals cleaned up.
    async fn cleanup_stale_goals(&self, _stale_hours: i64) -> anyhow::Result<u64> {
        Ok(0)
    }
}

/// Notification delivery queue persistence.
#[async_trait]
pub trait NotificationStore: Send + Sync {
    /// Record a background sub-agent that has started.
    async fn record_background_spawn(
        &self,
        _spawn: &crate::traits::BackgroundSpawn,
    ) -> anyhow::Result<()> {
        Ok(())
    }

    /// Forget a background sub-agent that has ended.
    async fn finish_background_spawn(&self, _id: &str) -> anyhow::Result<()> {
        Ok(())
    }

    /// The background sub-agents running for a session.
    async fn background_spawns_for_session(
        &self,
        _session_id: &str,
    ) -> anyhow::Result<Vec<crate::traits::BackgroundSpawn>> {
        Ok(Vec::new())
    }

    /// Remove and return every recorded background sub-agent.
    async fn take_background_spawns(&self) -> anyhow::Result<Vec<crate::traits::BackgroundSpawn>> {
        Ok(Vec::new())
    }

    /// Enqueue a notification for delivery.
    async fn enqueue_notification(
        &self,
        _entry: &crate::traits::NotificationEntry,
    ) -> anyhow::Result<()> {
        Ok(())
    }

    /// Atomically claim a goal's notification slot and enqueue its notification.
    ///
    /// Returns `false` when another writer has already claimed the goal. Stores
    /// that do not support transactions may fall back to enqueueing only.
    async fn enqueue_goal_notification(
        &self,
        entry: &crate::traits::NotificationEntry,
    ) -> anyhow::Result<bool> {
        self.enqueue_notification(entry).await?;
        Ok(true)
    }

    /// Get pending notifications ordered by priority (critical first), then creation time.
    async fn get_pending_notifications(
        &self,
        _limit: i64,
    ) -> anyhow::Result<Vec<crate::traits::NotificationEntry>> {
        Ok(vec![])
    }

    /// Mark a notification as delivered.
    async fn mark_notification_delivered(&self, _notification_id: &str) -> anyhow::Result<()> {
        Ok(())
    }

    /// Increment the attempt counter for a notification.
    async fn increment_notification_attempt(&self, _notification_id: &str) -> anyhow::Result<()> {
        Ok(())
    }

    /// Delete expired status_update notifications (past their expires_at).
    async fn cleanup_expired_notifications(&self) -> anyhow::Result<i64> {
        Ok(0)
    }

    /// Notices delivered to `session_id` at or after `since`, oldest first:
    /// what the owner was already told while a turn ran, so its reply can
    /// agree with them ([`crate::goals::notices_turn_context`]).
    async fn notices_delivered_since(
        &self,
        _session_id: &str,
        _since: chrono::DateTime<chrono::Utc>,
    ) -> anyhow::Result<Vec<crate::traits::DeliveredNotice>> {
        Ok(Vec::new())
    }
}

/// Focused persistence contract used by mandate management. Includes the
/// schedule and scheduled-run lifecycle so the mandate surface can project
/// its controller goal's authoritative objective status.
pub trait MandateToolStore:
    MandateStore
    + GoalStore
    + WorkCoordinationStore
    + aidaemon_channels::hub::SessionChannelStore
    + GoalBudgetStore
    + GoalScheduleStore
    + ScheduledRunStore
{
}

impl<T> MandateToolStore for T where
    T: MandateStore
        + GoalStore
        + WorkCoordinationStore
        + aidaemon_channels::hub::SessionChannelStore
        + GoalBudgetStore
        + GoalScheduleStore
        + ScheduledRunStore
{
}

/// Focused persistence contract used by goal-trace tooling.
pub trait GoalTraceStore:
    GoalStore + GoalScheduleStore + MandateStore + TaskStore + WorkCoordinationStore + ScheduledRunStore
{
}

impl<T> GoalTraceStore for T where
    T: GoalStore
        + GoalScheduleStore
        + MandateStore
        + TaskStore
        + WorkCoordinationStore
        + ScheduledRunStore
{
}

/// Focused persistence contract used by goal task management.
pub trait ManageGoalTasksStore:
    GoalStore + TaskStore + MandateStore + WorkCoordinationStore + NotificationStore
{
}

impl<T> ManageGoalTasksStore for T where
    T: GoalStore + TaskStore + MandateStore + WorkCoordinationStore + NotificationStore
{
}

/// Focused persistence contract used by the automation surfaces (scheduled
/// goals, reminders and mandates): everything their two engines' tools take.
pub trait AutomationStore:
    MandateToolStore + ScheduledGoalRunsStore + GoalNotificationStore
{
}

impl<T> AutomationStore for T where
    T: MandateToolStore + ScheduledGoalRunsStore + GoalNotificationStore
{
}

/// Focused persistence contract used by blocker reporting.
pub trait ReportBlockerStore:
    TaskStore + GoalStore + NotificationStore + WorkCoordinationStore
{
}

impl<T> ReportBlockerStore for T where
    T: TaskStore + GoalStore + NotificationStore + WorkCoordinationStore
{
}

/// Focused persistence contract used by scheduled-goal tooling.
pub trait ScheduledGoalRunsStore:
    GoalStore
    + GoalScheduleStore
    + ScheduledRunStore
    + GoalBudgetStore
    + TaskStore
    + WorkCoordinationStore
    + SettingsStore
    + MandateStore
{
}

impl<T> ScheduledGoalRunsStore for T where
    T: GoalStore
        + GoalScheduleStore
        + ScheduledRunStore
        + GoalBudgetStore
        + TaskStore
        + WorkCoordinationStore
        + SettingsStore
        + MandateStore
{
}

/// Database health check: verifies the connection is alive. The scheduler's
/// [`DbHealthGate`](crate::heartbeat::DbHealthGate) skips a tick while it fails.
#[async_trait]
pub trait HealthCheckStore: Send + Sync {
    async fn health_check(&self) -> anyhow::Result<()> {
        Ok(())
    }
}