aidaemon 0.11.13

A personal AI agent that runs as a background daemon, accessible via Telegram, Slack, or Discord, with tool use, MCP integration, and persistent memory
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
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
use super::*;
use crate::traits::GoalNotificationStore;

#[async_trait]
impl crate::traits::GoalStore for SqliteStateStore {
    async fn create_goal(&self, goal: &Goal) -> anyhow::Result<()> {
        // Enforce hard cap of 10 active evergreen goals (orchestration only).
        if goal.domain == "orchestration" && goal.goal_type == "continuous" {
            let count = self.count_active_evergreen_goals().await?;
            if count >= 10 {
                anyhow::bail!(
                    "Cannot create evergreen goal: hard cap of 10 active evergreen goals reached (current: {})",
                    count
                );
            }
        }

        let progress_notes_json = goal
            .progress_notes
            .as_ref()
            .map(|p| serde_json::to_string(p).unwrap_or_default());

        sqlx::query(
            "INSERT INTO goals (
                id, description, domain, goal_type, status, priority, conditions, context, resources,
                budget_per_check, budget_daily, tokens_used_today, tokens_used_day, last_useful_action,
                created_at, updated_at, completed_at, parent_goal_id, session_id, notified_at,
                notification_attempts, dispatch_failures, progress_notes, source_episode_id, legacy_int_id
             )
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
        )
        .bind(&goal.id)
        .bind(&goal.description)
        .bind(&goal.domain)
        .bind(&goal.goal_type)
        .bind(&goal.status)
        .bind(&goal.priority)
        .bind(&goal.conditions)
        .bind(&goal.context)
        .bind(&goal.resources)
        .bind(goal.budget_per_check)
        .bind(goal.budget_daily)
        .bind(goal.tokens_used_today)
        .bind(&goal.tokens_used_day)
        .bind(&goal.last_useful_action)
        .bind(&goal.created_at)
        .bind(&goal.updated_at)
        .bind(&goal.completed_at)
        .bind(&goal.parent_goal_id)
        .bind(&goal.session_id)
        .bind(&goal.notified_at)
        .bind(goal.notification_attempts)
        .bind(goal.dispatch_failures)
        .bind(&progress_notes_json)
        .bind(goal.source_episode_id)
        .bind(goal.legacy_int_id)
        .execute(&self.pool)
        .await?;
        Ok(())
    }

    async fn get_goal(&self, id: &str) -> anyhow::Result<Option<Goal>> {
        let row = sqlx::query(
            "SELECT id, description, domain, goal_type, status, priority, conditions,
             context, resources, budget_per_check, budget_daily, tokens_used_today, tokens_used_day,
             last_useful_action, created_at, updated_at, completed_at, parent_goal_id, session_id,
             notified_at, notification_attempts, dispatch_failures, progress_notes, source_episode_id, legacy_int_id
             FROM goals WHERE id = ?",
        )
        .bind(id)
        .fetch_optional(&self.pool)
        .await?;

        Ok(row.map(|r| {
            let progress_notes_json: Option<String> = r.get("progress_notes");
            let progress_notes = progress_notes_json.and_then(|j| serde_json::from_str(&j).ok());

            Goal {
                id: r.get("id"),
                description: r.get("description"),
                domain: r.get("domain"),
                goal_type: r.get("goal_type"),
                status: r.get("status"),
                priority: r.get("priority"),
                conditions: r.get("conditions"),
                context: r.get("context"),
                resources: r.get("resources"),
                budget_per_check: r.get("budget_per_check"),
                budget_daily: r.get("budget_daily"),
                tokens_used_today: r.get("tokens_used_today"),
                tokens_used_day: r.get("tokens_used_day"),
                last_useful_action: r.get("last_useful_action"),
                created_at: r.get("created_at"),
                updated_at: r.get("updated_at"),
                completed_at: r.get("completed_at"),
                parent_goal_id: r.get("parent_goal_id"),
                session_id: r.get("session_id"),
                notified_at: r.get("notified_at"),
                notification_attempts: r.get::<i32, _>("notification_attempts"),
                dispatch_failures: r.get::<i32, _>("dispatch_failures"),
                progress_notes,
                source_episode_id: r.get("source_episode_id"),
                legacy_int_id: r.get("legacy_int_id"),
            }
        }))
    }

    async fn update_goal(&self, goal: &Goal) -> anyhow::Result<()> {
        let now = chrono::Utc::now().to_rfc3339();
        let progress_notes_json = goal
            .progress_notes
            .as_ref()
            .map(|p| serde_json::to_string(p).unwrap_or_default());
        sqlx::query(
            "UPDATE goals SET description = ?, domain = ?, goal_type = ?, status = ?, priority = ?,
             conditions = ?, context = ?, resources = ?,
             budget_per_check = ?, budget_daily = ?, tokens_used_today = ?, tokens_used_day = ?,
             last_useful_action = ?, updated_at = ?, completed_at = ?,
             parent_goal_id = ?, session_id = ?, notified_at = ?, notification_attempts = ?, dispatch_failures = ?,
             progress_notes = ?, source_episode_id = ?, legacy_int_id = ?
             WHERE id = ?",
        )
        .bind(&goal.description)
        .bind(&goal.domain)
        .bind(&goal.goal_type)
        .bind(&goal.status)
        .bind(&goal.priority)
        .bind(&goal.conditions)
        .bind(&goal.context)
        .bind(&goal.resources)
        .bind(goal.budget_per_check)
        .bind(goal.budget_daily)
        .bind(goal.tokens_used_today)
        .bind(&goal.tokens_used_day)
        .bind(&goal.last_useful_action)
        .bind(&now)
        .bind(&goal.completed_at)
        .bind(&goal.parent_goal_id)
        .bind(&goal.session_id)
        .bind(&goal.notified_at)
        .bind(goal.notification_attempts)
        .bind(goal.dispatch_failures)
        .bind(&progress_notes_json)
        .bind(goal.source_episode_id)
        .bind(goal.legacy_int_id)
        .bind(&goal.id)
        .execute(&self.pool)
        .await?;

        // If a goal is terminal, purge schedules so they don't linger as dead rows.
        // This keeps the DB consistent even when cancellation/completion happens via
        // bulk tools or non-tool code paths.
        if goal.domain == "orchestration"
            && matches!(goal.status.as_str(), "cancelled" | "completed")
        {
            sqlx::query("DELETE FROM goal_schedules WHERE goal_id = ?")
                .bind(&goal.id)
                .execute(&self.pool)
                .await?;
        }

        Ok(())
    }

    async fn get_active_goals(&self) -> anyhow::Result<Vec<Goal>> {
        let rows = sqlx::query(
            "SELECT id, description, domain, goal_type, status, priority, conditions,
             context, resources, budget_per_check, budget_daily, tokens_used_today, tokens_used_day,
             last_useful_action, created_at, updated_at, completed_at, parent_goal_id, session_id,
             notified_at, notification_attempts, dispatch_failures, progress_notes, source_episode_id, legacy_int_id
             FROM goals
             WHERE domain = 'orchestration' AND status IN ('active', 'pending')
             ORDER BY created_at DESC",
        )
        .fetch_all(&self.pool)
        .await?;

        Ok(rows
            .iter()
            .map(|r| {
                let progress_notes_json: Option<String> = r.get("progress_notes");
                let progress_notes =
                    progress_notes_json.and_then(|j| serde_json::from_str(&j).ok());
                Goal {
                    id: r.get("id"),
                    description: r.get("description"),
                    domain: r.get("domain"),
                    goal_type: r.get("goal_type"),
                    status: r.get("status"),
                    priority: r.get("priority"),
                    conditions: r.get("conditions"),
                    context: r.get("context"),
                    resources: r.get("resources"),
                    budget_per_check: r.get("budget_per_check"),
                    budget_daily: r.get("budget_daily"),
                    tokens_used_today: r.get("tokens_used_today"),
                    tokens_used_day: r.get("tokens_used_day"),
                    last_useful_action: r.get("last_useful_action"),
                    created_at: r.get("created_at"),
                    updated_at: r.get("updated_at"),
                    completed_at: r.get("completed_at"),
                    parent_goal_id: r.get("parent_goal_id"),
                    session_id: r.get("session_id"),
                    notified_at: r.get("notified_at"),
                    notification_attempts: r.get::<i32, _>("notification_attempts"),
                    dispatch_failures: r.get::<i32, _>("dispatch_failures"),
                    progress_notes,
                    source_episode_id: r.get("source_episode_id"),
                    legacy_int_id: r.get("legacy_int_id"),
                }
            })
            .collect())
    }

    async fn get_active_personal_goals(&self, limit: i64) -> anyhow::Result<Vec<Goal>> {
        let limit = limit.clamp(0, 100);
        let rows = sqlx::query(
            "SELECT id, description, domain, goal_type, status, priority, conditions,
             context, resources, budget_per_check, budget_daily, tokens_used_today, tokens_used_day,
             last_useful_action, created_at, updated_at, completed_at, parent_goal_id, session_id,
             notified_at, notification_attempts, dispatch_failures, progress_notes, source_episode_id, legacy_int_id
             FROM goals
             WHERE domain = 'personal' AND status = 'active'
             ORDER BY
               CASE priority WHEN 'high' THEN 1 WHEN 'medium' THEN 2 WHEN 'low' THEN 3 ELSE 4 END,
               created_at DESC
             LIMIT ?",
        )
        .bind(limit)
        .fetch_all(&self.pool)
        .await?;

        Ok(rows
            .iter()
            .map(|r| {
                let progress_notes_json: Option<String> = r.get("progress_notes");
                let progress_notes =
                    progress_notes_json.and_then(|j| serde_json::from_str(&j).ok());
                Goal {
                    id: r.get("id"),
                    description: r.get("description"),
                    domain: r.get("domain"),
                    goal_type: r.get("goal_type"),
                    status: r.get("status"),
                    priority: r.get("priority"),
                    conditions: r.get("conditions"),
                    context: r.get("context"),
                    resources: r.get("resources"),
                    budget_per_check: r.get("budget_per_check"),
                    budget_daily: r.get("budget_daily"),
                    tokens_used_today: r.get("tokens_used_today"),
                    tokens_used_day: r.get("tokens_used_day"),
                    last_useful_action: r.get("last_useful_action"),
                    created_at: r.get("created_at"),
                    updated_at: r.get("updated_at"),
                    completed_at: r.get("completed_at"),
                    parent_goal_id: r.get("parent_goal_id"),
                    session_id: r.get("session_id"),
                    notified_at: r.get("notified_at"),
                    notification_attempts: r.get::<i32, _>("notification_attempts"),
                    dispatch_failures: r.get::<i32, _>("dispatch_failures"),
                    progress_notes,
                    source_episode_id: r.get("source_episode_id"),
                    legacy_int_id: r.get("legacy_int_id"),
                }
            })
            .collect())
    }

    async fn update_personal_goal(
        &self,
        goal_id: &str,
        status: Option<&str>,
        progress_note: Option<&str>,
    ) -> anyhow::Result<()> {
        let now = chrono::Utc::now().to_rfc3339();

        let mut tx = self.pool.begin().await?;

        if let Some(note) = progress_note {
            let row = sqlx::query(
                "SELECT progress_notes FROM goals WHERE id = ? AND domain = 'personal'",
            )
            .bind(goal_id)
            .fetch_optional(&mut *tx)
            .await?;

            let mut notes: Vec<String> = row
                .and_then(|r| r.get::<Option<String>, _>("progress_notes"))
                .and_then(|j| serde_json::from_str(&j).ok())
                .unwrap_or_default();
            notes.push(note.to_string());
            let notes_json = serde_json::to_string(&notes)?;

            sqlx::query(
                "UPDATE goals
                 SET progress_notes = ?, updated_at = ?
                 WHERE id = ? AND domain = 'personal'",
            )
            .bind(&notes_json)
            .bind(&now)
            .bind(goal_id)
            .execute(&mut *tx)
            .await?;
        }

        if let Some(s) = status {
            let completed_at = if s == "completed" {
                Some(now.clone())
            } else {
                None
            };
            sqlx::query(
                "UPDATE goals
                 SET status = ?, updated_at = ?, completed_at = COALESCE(?, completed_at)
                 WHERE id = ? AND domain = 'personal'",
            )
            .bind(s)
            .bind(&now)
            .bind(&completed_at)
            .bind(goal_id)
            .execute(&mut *tx)
            .await?;
        }

        tx.commit().await?;
        Ok(())
    }

    async fn get_goals_for_session(&self, session_id: &str) -> anyhow::Result<Vec<Goal>> {
        let rows = sqlx::query(
            "SELECT id, description, domain, goal_type, status, priority, conditions,
             context, resources, budget_per_check, budget_daily, tokens_used_today, tokens_used_day,
             last_useful_action, created_at, updated_at, completed_at, parent_goal_id, session_id,
             notified_at, notification_attempts, dispatch_failures, progress_notes, source_episode_id, legacy_int_id
             FROM goals
             WHERE domain = 'orchestration' AND session_id = ?
             ORDER BY created_at DESC",
        )
        .bind(session_id)
        .fetch_all(&self.pool)
        .await?;

        Ok(rows
            .iter()
            .map(|r| {
                let progress_notes_json: Option<String> = r.get("progress_notes");
                let progress_notes =
                    progress_notes_json.and_then(|j| serde_json::from_str(&j).ok());
                Goal {
                    id: r.get("id"),
                    description: r.get("description"),
                    domain: r.get("domain"),
                    goal_type: r.get("goal_type"),
                    status: r.get("status"),
                    priority: r.get("priority"),
                    conditions: r.get("conditions"),
                    context: r.get("context"),
                    resources: r.get("resources"),
                    budget_per_check: r.get("budget_per_check"),
                    budget_daily: r.get("budget_daily"),
                    tokens_used_today: r.get("tokens_used_today"),
                    tokens_used_day: r.get("tokens_used_day"),
                    last_useful_action: r.get("last_useful_action"),
                    created_at: r.get("created_at"),
                    updated_at: r.get("updated_at"),
                    completed_at: r.get("completed_at"),
                    parent_goal_id: r.get("parent_goal_id"),
                    session_id: r.get("session_id"),
                    notified_at: r.get("notified_at"),
                    notification_attempts: r.get::<i32, _>("notification_attempts"),
                    dispatch_failures: r.get::<i32, _>("dispatch_failures"),
                    progress_notes,
                    source_episode_id: r.get("source_episode_id"),
                    legacy_int_id: r.get("legacy_int_id"),
                }
            })
            .collect())
    }

    async fn get_pending_confirmation_goals(&self, session_id: &str) -> anyhow::Result<Vec<Goal>> {
        let rows = sqlx::query(
            "SELECT id, description, domain, goal_type, status, priority, conditions,
             context, resources, budget_per_check, budget_daily, tokens_used_today, tokens_used_day,
             last_useful_action, created_at, updated_at, completed_at, parent_goal_id, session_id,
             notified_at, notification_attempts, dispatch_failures, progress_notes, source_episode_id, legacy_int_id
             FROM goals
             WHERE domain = 'orchestration' AND session_id = ? AND status = 'pending_confirmation'
             ORDER BY created_at DESC",
        )
        .bind(session_id)
        .fetch_all(&self.pool)
        .await?;

        Ok(rows
            .iter()
            .map(|r| {
                let progress_notes_json: Option<String> = r.get("progress_notes");
                let progress_notes =
                    progress_notes_json.and_then(|j| serde_json::from_str(&j).ok());
                Goal {
                    id: r.get("id"),
                    description: r.get("description"),
                    domain: r.get("domain"),
                    goal_type: r.get("goal_type"),
                    status: r.get("status"),
                    priority: r.get("priority"),
                    conditions: r.get("conditions"),
                    context: r.get("context"),
                    resources: r.get("resources"),
                    budget_per_check: r.get("budget_per_check"),
                    budget_daily: r.get("budget_daily"),
                    tokens_used_today: r.get("tokens_used_today"),
                    tokens_used_day: r.get("tokens_used_day"),
                    last_useful_action: r.get("last_useful_action"),
                    created_at: r.get("created_at"),
                    updated_at: r.get("updated_at"),
                    completed_at: r.get("completed_at"),
                    parent_goal_id: r.get("parent_goal_id"),
                    session_id: r.get("session_id"),
                    notified_at: r.get("notified_at"),
                    notification_attempts: r.get::<i32, _>("notification_attempts"),
                    dispatch_failures: r.get::<i32, _>("dispatch_failures"),
                    progress_notes,
                    source_episode_id: r.get("source_episode_id"),
                    legacy_int_id: r.get("legacy_int_id"),
                }
            })
            .collect())
    }

    async fn activate_goal(&self, goal_id: &str) -> anyhow::Result<bool> {
        let goal_row = sqlx::query(
            "SELECT goal_type
             FROM goals
             WHERE id = ? AND domain = 'orchestration' AND status = 'pending_confirmation'",
        )
        .bind(goal_id)
        .fetch_optional(&self.pool)
        .await?;

        let Some(row) = goal_row else {
            return Ok(false);
        };

        let goal_type: String = row.get("goal_type");
        if goal_type == "continuous" {
            let active_evergreen = self.count_active_evergreen_goals().await?;
            if active_evergreen >= 10 {
                anyhow::bail!(
                    "Cannot activate recurring goal: hard cap of 10 active evergreen goals reached (current: {})",
                    active_evergreen
                );
            }
        }

        let now = chrono::Utc::now().to_rfc3339();
        let result = sqlx::query(
            "UPDATE goals
             SET status = 'active', updated_at = ?
             WHERE id = ? AND domain = 'orchestration' AND status = 'pending_confirmation'",
        )
        .bind(&now)
        .bind(goal_id)
        .execute(&self.pool)
        .await?;

        Ok(result.rows_affected() > 0)
    }
}

#[async_trait]
impl crate::traits::TaskStore for SqliteStateStore {
    async fn create_task(&self, task: &Task) -> anyhow::Result<()> {
        sqlx::query(
            "INSERT INTO tasks (id, goal_id, description, status, priority, task_order,
             parallel_group, depends_on, agent_id, context, result, error, blocker,
             idempotent, retry_count, max_retries, created_at, started_at, completed_at)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
        )
        .bind(&task.id)
        .bind(&task.goal_id)
        .bind(&task.description)
        .bind(&task.status)
        .bind(&task.priority)
        .bind(task.task_order)
        .bind(&task.parallel_group)
        .bind(&task.depends_on)
        .bind(&task.agent_id)
        .bind(&task.context)
        .bind(&task.result)
        .bind(&task.error)
        .bind(&task.blocker)
        .bind(task.idempotent as i32)
        .bind(task.retry_count)
        .bind(task.max_retries)
        .bind(&task.created_at)
        .bind(&task.started_at)
        .bind(&task.completed_at)
        .execute(&self.pool)
        .await?;
        Ok(())
    }

    async fn get_task(&self, id: &str) -> anyhow::Result<Option<Task>> {
        let row = sqlx::query(
            "SELECT id, goal_id, description, status, priority, task_order,
             parallel_group, depends_on, agent_id, context, result, error, blocker,
             idempotent, retry_count, max_retries, created_at, started_at, completed_at
             FROM tasks WHERE id = ?",
        )
        .bind(id)
        .fetch_optional(&self.pool)
        .await?;

        Ok(row.map(|r| Task {
            id: r.get("id"),
            goal_id: r.get("goal_id"),
            description: r.get("description"),
            status: r.get("status"),
            priority: r.get("priority"),
            task_order: r.get("task_order"),
            parallel_group: r.get("parallel_group"),
            depends_on: r.get("depends_on"),
            agent_id: r.get("agent_id"),
            context: r.get("context"),
            result: r.get("result"),
            error: r.get("error"),
            blocker: r.get("blocker"),
            idempotent: r.get::<i32, _>("idempotent") != 0,
            retry_count: r.get("retry_count"),
            max_retries: r.get("max_retries"),
            created_at: r.get("created_at"),
            started_at: r.get("started_at"),
            completed_at: r.get("completed_at"),
        }))
    }

    async fn update_task(&self, task: &Task) -> anyhow::Result<()> {
        sqlx::query(
            "UPDATE tasks SET description = ?, status = ?, priority = ?, task_order = ?,
             parallel_group = ?, depends_on = ?, agent_id = ?, context = ?,
             result = ?, error = ?, blocker = ?, idempotent = ?,
             retry_count = ?, max_retries = ?, started_at = ?, completed_at = ?
             WHERE id = ?",
        )
        .bind(&task.description)
        .bind(&task.status)
        .bind(&task.priority)
        .bind(task.task_order)
        .bind(&task.parallel_group)
        .bind(&task.depends_on)
        .bind(&task.agent_id)
        .bind(&task.context)
        .bind(&task.result)
        .bind(&task.error)
        .bind(&task.blocker)
        .bind(task.idempotent as i32)
        .bind(task.retry_count)
        .bind(task.max_retries)
        .bind(&task.started_at)
        .bind(&task.completed_at)
        .bind(&task.id)
        .execute(&self.pool)
        .await?;
        Ok(())
    }

    async fn get_tasks_for_goal(&self, goal_id: &str) -> anyhow::Result<Vec<Task>> {
        let rows = sqlx::query(
            "SELECT id, goal_id, description, status, priority, task_order,
             parallel_group, depends_on, agent_id, context, result, error, blocker,
             idempotent, retry_count, max_retries, created_at, started_at, completed_at
             FROM tasks WHERE goal_id = ?
             ORDER BY task_order ASC",
        )
        .bind(goal_id)
        .fetch_all(&self.pool)
        .await?;

        Ok(rows
            .iter()
            .map(|r| Task {
                id: r.get("id"),
                goal_id: r.get("goal_id"),
                description: r.get("description"),
                status: r.get("status"),
                priority: r.get("priority"),
                task_order: r.get("task_order"),
                parallel_group: r.get("parallel_group"),
                depends_on: r.get("depends_on"),
                agent_id: r.get("agent_id"),
                context: r.get("context"),
                result: r.get("result"),
                error: r.get("error"),
                blocker: r.get("blocker"),
                idempotent: r.get::<i32, _>("idempotent") != 0,
                retry_count: r.get("retry_count"),
                max_retries: r.get("max_retries"),
                created_at: r.get("created_at"),
                started_at: r.get("started_at"),
                completed_at: r.get("completed_at"),
            })
            .collect())
    }

    async fn count_completed_tasks_for_goal(&self, goal_id: &str) -> anyhow::Result<i64> {
        let row = sqlx::query(
            "SELECT COUNT(*) as cnt FROM tasks
             WHERE goal_id = ? AND status IN ('completed', 'skipped')",
        )
        .bind(goal_id)
        .fetch_one(&self.pool)
        .await?;
        Ok(row.get::<i64, _>("cnt"))
    }

    async fn claim_task(&self, task_id: &str, agent_id: &str) -> anyhow::Result<bool> {
        let now = chrono::Utc::now().to_rfc3339();
        let result = sqlx::query(
            "UPDATE tasks SET status = 'claimed', agent_id = ?, started_at = ?
             WHERE id = ? AND status = 'pending'",
        )
        .bind(agent_id)
        .bind(&now)
        .bind(task_id)
        .execute(&self.pool)
        .await?;
        Ok(result.rows_affected() > 0)
    }

    async fn log_task_activity(&self, activity: &TaskActivity) -> anyhow::Result<()> {
        // Redact secrets from tool_args and result before persisting
        let redacted_args = activity
            .tool_args
            .as_deref()
            .map(crate::tools::sanitize::redact_secrets);
        let redacted_result = activity
            .result
            .as_deref()
            .map(crate::tools::sanitize::redact_secrets);

        sqlx::query(
            "INSERT INTO task_activity (task_id, activity_type, tool_name, tool_args,
             result, success, tokens_used, created_at)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
        )
        .bind(&activity.task_id)
        .bind(&activity.activity_type)
        .bind(&activity.tool_name)
        .bind(&redacted_args)
        .bind(&redacted_result)
        .bind(activity.success.map(|b| b as i32))
        .bind(activity.tokens_used)
        .bind(&activity.created_at)
        .execute(&self.pool)
        .await?;
        Ok(())
    }

    async fn get_task_activities(&self, task_id: &str) -> anyhow::Result<Vec<TaskActivity>> {
        let rows = sqlx::query(
            "SELECT id, task_id, activity_type, tool_name, tool_args, result, success,
             tokens_used, created_at
             FROM task_activity WHERE task_id = ?
             ORDER BY created_at ASC",
        )
        .bind(task_id)
        .fetch_all(&self.pool)
        .await?;

        Ok(rows
            .iter()
            .map(|r| TaskActivity {
                id: r.get("id"),
                task_id: r.get("task_id"),
                activity_type: r.get("activity_type"),
                tool_name: r.get("tool_name"),
                tool_args: r.get("tool_args"),
                result: r.get("result"),
                success: r.get::<Option<i32>, _>("success").map(|v| v != 0),
                tokens_used: r.get("tokens_used"),
                created_at: r.get("created_at"),
            })
            .collect())
    }
}

#[async_trait]
impl crate::traits::GoalScheduleStore for SqliteStateStore {
    async fn create_goal_schedule(&self, schedule: &GoalSchedule) -> anyhow::Result<()> {
        if schedule.tz != "local" {
            anyhow::bail!(
                "Only tz='local' is supported for schedules (got tz='{}')",
                schedule.tz
            );
        }

        // Safety: schedules only apply to orchestration goals.
        let domain_row = sqlx::query("SELECT domain FROM goals WHERE id = ?")
            .bind(&schedule.goal_id)
            .fetch_optional(&self.pool)
            .await?;
        if let Some(row) = domain_row {
            let domain: String = row.get("domain");
            if domain != "orchestration" {
                anyhow::bail!(
                    "Cannot create schedule for non-orchestration goal {} (domain={})",
                    schedule.goal_id,
                    domain
                );
            }
        }

        sqlx::query(
            "INSERT INTO goal_schedules
                (id, goal_id, cron_expr, tz, original_schedule, fire_policy, is_one_shot, is_paused, last_run_at, next_run_at, created_at, updated_at)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
        )
        .bind(&schedule.id)
        .bind(&schedule.goal_id)
        .bind(&schedule.cron_expr)
        .bind(&schedule.tz)
        .bind(&schedule.original_schedule)
        .bind(&schedule.fire_policy)
        .bind(schedule.is_one_shot as i32)
        .bind(schedule.is_paused as i32)
        .bind(&schedule.last_run_at)
        .bind(&schedule.next_run_at)
        .bind(&schedule.created_at)
        .bind(&schedule.updated_at)
        .execute(&self.pool)
        .await?;
        Ok(())
    }

    async fn get_goal_schedule(&self, schedule_id: &str) -> anyhow::Result<Option<GoalSchedule>> {
        let row = sqlx::query(
            "SELECT id, goal_id, cron_expr, tz, original_schedule, fire_policy, is_one_shot, is_paused, last_run_at, next_run_at, created_at, updated_at
             FROM goal_schedules WHERE id = ?",
        )
        .bind(schedule_id)
        .fetch_optional(&self.pool)
        .await?;

        Ok(row.map(|r| GoalSchedule {
            id: r.get("id"),
            goal_id: r.get("goal_id"),
            cron_expr: r.get("cron_expr"),
            tz: r.get("tz"),
            original_schedule: r.get("original_schedule"),
            fire_policy: r.get("fire_policy"),
            is_one_shot: r.get::<i64, _>("is_one_shot") != 0,
            is_paused: r.get::<i64, _>("is_paused") != 0,
            last_run_at: r.get("last_run_at"),
            next_run_at: r.get("next_run_at"),
            created_at: r.get("created_at"),
            updated_at: r.get("updated_at"),
        }))
    }

    async fn get_schedules_for_goal(&self, goal_id: &str) -> anyhow::Result<Vec<GoalSchedule>> {
        let rows = sqlx::query(
            "SELECT id, goal_id, cron_expr, tz, original_schedule, fire_policy, is_one_shot, is_paused, last_run_at, next_run_at, created_at, updated_at
             FROM goal_schedules
             WHERE goal_id = ?
             ORDER BY next_run_at ASC",
        )
        .bind(goal_id)
        .fetch_all(&self.pool)
        .await?;

        Ok(rows
            .iter()
            .map(|r| GoalSchedule {
                id: r.get("id"),
                goal_id: r.get("goal_id"),
                cron_expr: r.get("cron_expr"),
                tz: r.get("tz"),
                original_schedule: r.get("original_schedule"),
                fire_policy: r.get("fire_policy"),
                is_one_shot: r.get::<i64, _>("is_one_shot") != 0,
                is_paused: r.get::<i64, _>("is_paused") != 0,
                last_run_at: r.get("last_run_at"),
                next_run_at: r.get("next_run_at"),
                created_at: r.get("created_at"),
                updated_at: r.get("updated_at"),
            })
            .collect())
    }

    async fn get_due_goal_schedules(&self, limit: i64) -> anyhow::Result<Vec<GoalSchedule>> {
        let limit = limit.clamp(0, 500);
        let now = chrono::Utc::now().to_rfc3339();
        let rows = sqlx::query(
            "SELECT s.id, s.goal_id, s.cron_expr, s.tz, s.original_schedule, s.fire_policy, s.is_one_shot, s.is_paused, s.last_run_at, s.next_run_at, s.created_at, s.updated_at
             FROM goal_schedules s
             JOIN goals g ON g.id = s.goal_id
             WHERE s.is_paused = 0
               AND s.tz = 'local'
               AND s.next_run_at <= ?
               AND g.domain = 'orchestration'
               AND g.status = 'active'
             ORDER BY s.next_run_at ASC
             LIMIT ?",
        )
        .bind(&now)
        .bind(limit)
        .fetch_all(&self.pool)
        .await?;

        Ok(rows
            .iter()
            .map(|r| GoalSchedule {
                id: r.get("id"),
                goal_id: r.get("goal_id"),
                cron_expr: r.get("cron_expr"),
                tz: r.get("tz"),
                original_schedule: r.get("original_schedule"),
                fire_policy: r.get("fire_policy"),
                is_one_shot: r.get::<i64, _>("is_one_shot") != 0,
                is_paused: r.get::<i64, _>("is_paused") != 0,
                last_run_at: r.get("last_run_at"),
                next_run_at: r.get("next_run_at"),
                created_at: r.get("created_at"),
                updated_at: r.get("updated_at"),
            })
            .collect())
    }

    async fn update_goal_schedule(&self, schedule: &GoalSchedule) -> anyhow::Result<()> {
        if schedule.tz != "local" {
            anyhow::bail!(
                "Only tz='local' is supported for schedules (got tz='{}')",
                schedule.tz
            );
        }

        let now = chrono::Utc::now().to_rfc3339();
        sqlx::query(
            "UPDATE goal_schedules
             SET goal_id = ?, cron_expr = ?, tz = ?, original_schedule = ?, fire_policy = ?,
                 is_one_shot = ?, is_paused = ?, last_run_at = ?, next_run_at = ?, updated_at = ?
             WHERE id = ?",
        )
        .bind(&schedule.goal_id)
        .bind(&schedule.cron_expr)
        .bind(&schedule.tz)
        .bind(&schedule.original_schedule)
        .bind(&schedule.fire_policy)
        .bind(schedule.is_one_shot as i32)
        .bind(schedule.is_paused as i32)
        .bind(&schedule.last_run_at)
        .bind(&schedule.next_run_at)
        .bind(&now)
        .bind(&schedule.id)
        .execute(&self.pool)
        .await?;
        Ok(())
    }

    async fn delete_goal_schedule(&self, schedule_id: &str) -> anyhow::Result<bool> {
        let result = sqlx::query("DELETE FROM goal_schedules WHERE id = ?")
            .bind(schedule_id)
            .execute(&self.pool)
            .await?;
        Ok(result.rows_affected() > 0)
    }

    async fn cancel_stale_pending_confirmation_goals(
        &self,
        max_age_secs: i64,
    ) -> anyhow::Result<u64> {
        let now = chrono::Utc::now().to_rfc3339();
        let cutoff = (chrono::Utc::now() - chrono::Duration::seconds(max_age_secs)).to_rfc3339();
        let mut tx = self.pool.begin().await?;

        // If we're cancelling stale pending confirmations, remove their schedules
        // so they don't appear as "scheduled" (zombie schedules).
        sqlx::query(
            "DELETE FROM goal_schedules
             WHERE goal_id IN (
               SELECT id FROM goals WHERE status = 'pending_confirmation' AND created_at < ?
             )",
        )
        .bind(&cutoff)
        .execute(&mut *tx)
        .await?;

        let result = sqlx::query(
            "UPDATE goals
             SET status = 'cancelled', updated_at = ?, completed_at = ?
             WHERE status = 'pending_confirmation' AND created_at < ?",
        )
        .bind(&now)
        .bind(&now)
        .bind(&cutoff)
        .execute(&mut *tx)
        .await?;
        tx.commit().await?;
        Ok(result.rows_affected())
    }

    async fn get_scheduled_goals(&self) -> anyhow::Result<Vec<Goal>> {
        let rows = sqlx::query(
            "SELECT id, description, domain, goal_type, status, priority, conditions,
             context, resources, budget_per_check, budget_daily, tokens_used_today, tokens_used_day,
             last_useful_action, created_at, updated_at, completed_at, parent_goal_id, session_id,
             notified_at, notification_attempts, dispatch_failures, progress_notes, source_episode_id, legacy_int_id
             FROM goals
             WHERE domain = 'orchestration'
               AND (
                 EXISTS (SELECT 1 FROM goal_schedules s WHERE s.goal_id = goals.id)
                 OR status = 'pending_confirmation'
               )
             ORDER BY created_at DESC",
        )
        .fetch_all(&self.pool)
        .await?;

        Ok(rows
            .iter()
            .map(|r| {
                let progress_notes_json: Option<String> = r.get("progress_notes");
                let progress_notes =
                    progress_notes_json.and_then(|j| serde_json::from_str(&j).ok());
                Goal {
                    id: r.get("id"),
                    description: r.get("description"),
                    domain: r.get("domain"),
                    goal_type: r.get("goal_type"),
                    status: r.get("status"),
                    priority: r.get("priority"),
                    conditions: r.get("conditions"),
                    context: r.get("context"),
                    resources: r.get("resources"),
                    budget_per_check: r.get("budget_per_check"),
                    budget_daily: r.get("budget_daily"),
                    tokens_used_today: r.get("tokens_used_today"),
                    tokens_used_day: r.get("tokens_used_day"),
                    last_useful_action: r.get("last_useful_action"),
                    created_at: r.get("created_at"),
                    updated_at: r.get("updated_at"),
                    completed_at: r.get("completed_at"),
                    parent_goal_id: r.get("parent_goal_id"),
                    session_id: r.get("session_id"),
                    notified_at: r.get("notified_at"),
                    notification_attempts: r.get::<i32, _>("notification_attempts"),
                    dispatch_failures: r.get::<i32, _>("dispatch_failures"),
                    progress_notes,
                    source_episode_id: r.get("source_episode_id"),
                    legacy_int_id: r.get("legacy_int_id"),
                }
            })
            .collect())
    }
}

#[async_trait]
impl crate::traits::GoalBudgetStore for SqliteStateStore {
    async fn reset_daily_token_budgets(&self) -> anyhow::Result<u64> {
        let result = sqlx::query(
            "UPDATE goals
             SET tokens_used_today = 0, tokens_used_day = date('now')
             WHERE domain = 'orchestration' AND status = 'active'",
        )
        .execute(&self.pool)
        .await?;
        Ok(result.rows_affected())
    }

    async fn set_goal_budgets(
        &self,
        goal_id: &str,
        budget_per_check: Option<i64>,
        budget_daily: Option<i64>,
    ) -> anyhow::Result<()> {
        sqlx::query(
            "UPDATE goals SET budget_per_check = COALESCE(?, budget_per_check),
                              budget_daily = COALESCE(?, budget_daily),
                              updated_at = ? WHERE id = ?",
        )
        .bind(budget_per_check)
        .bind(budget_daily)
        .bind(chrono::Utc::now().to_rfc3339())
        .bind(goal_id)
        .execute(&self.pool)
        .await?;
        Ok(())
    }

    async fn add_goal_tokens_and_get_budget_status(
        &self,
        goal_id: &str,
        delta_tokens: i64,
    ) -> anyhow::Result<Option<GoalTokenBudgetStatus>> {
        let mut tx = self.pool.begin().await?;
        let today = chrono::Utc::now().date_naive().to_string();

        // Lazy daily reset keyed by UTC day anchor.
        let _ = sqlx::query(
            "UPDATE goals
             SET tokens_used_today = 0, tokens_used_day = ?
             WHERE id = ? AND (tokens_used_day IS NULL OR tokens_used_day != ?)",
        )
        .bind(&today)
        .bind(goal_id)
        .bind(&today)
        .execute(&mut *tx)
        .await;

        if delta_tokens != 0 {
            sqlx::query(
                "UPDATE goals
                 SET tokens_used_today = MAX(0, tokens_used_today + ?)
                 WHERE id = ?",
            )
            .bind(delta_tokens)
            .bind(goal_id)
            .execute(&mut *tx)
            .await?;
        }

        let row = sqlx::query(
            "SELECT budget_per_check, budget_daily, tokens_used_today
             FROM goals
             WHERE id = ?",
        )
        .bind(goal_id)
        .fetch_optional(&mut *tx)
        .await?;

        tx.commit().await?;

        Ok(row.map(|r| GoalTokenBudgetStatus {
            budget_per_check: r.get("budget_per_check"),
            budget_daily: r.get("budget_daily"),
            tokens_used_today: r.get("tokens_used_today"),
        }))
    }
}

#[async_trait]
impl crate::traits::ScheduledRunStore for SqliteStateStore {
    async fn upsert_scheduled_run_state(&self, state: &ScheduledRunState) -> anyhow::Result<()> {
        let health_json = serde_json::to_string(&state.health)?;
        sqlx::query(
            "INSERT INTO scheduled_run_state (
                goal_id, root_task_id, effective_budget_per_check, tokens_used,
                budget_extensions_count, health_json, created_at, updated_at
             ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
             ON CONFLICT(goal_id) DO UPDATE SET
                root_task_id = excluded.root_task_id,
                effective_budget_per_check = excluded.effective_budget_per_check,
                tokens_used = excluded.tokens_used,
                budget_extensions_count = excluded.budget_extensions_count,
                health_json = excluded.health_json,
                updated_at = excluded.updated_at",
        )
        .bind(&state.goal_id)
        .bind(&state.root_task_id)
        .bind(state.effective_budget_per_check)
        .bind(state.tokens_used)
        .bind(state.budget_extensions_count as i64)
        .bind(health_json)
        .bind(&state.created_at)
        .bind(&state.updated_at)
        .execute(&self.pool)
        .await?;
        Ok(())
    }

    async fn get_scheduled_run_state(
        &self,
        goal_id: &str,
    ) -> anyhow::Result<Option<ScheduledRunState>> {
        let row = sqlx::query(
            "SELECT goal_id, root_task_id, effective_budget_per_check, tokens_used,
                    budget_extensions_count, health_json, created_at, updated_at
             FROM scheduled_run_state
             WHERE goal_id = ?",
        )
        .bind(goal_id)
        .fetch_optional(&self.pool)
        .await?;

        Ok(row.map(|r| ScheduledRunState {
            goal_id: r.get("goal_id"),
            root_task_id: r.get("root_task_id"),
            effective_budget_per_check: r.get("effective_budget_per_check"),
            tokens_used: r.get("tokens_used"),
            budget_extensions_count: r.get::<i64, _>("budget_extensions_count") as usize,
            health: r
                .try_get::<String, _>("health_json")
                .ok()
                .and_then(|raw| serde_json::from_str(&raw).ok())
                .unwrap_or_default(),
            created_at: r.get("created_at"),
            updated_at: r.get("updated_at"),
        }))
    }

    async fn delete_scheduled_run_state(&self, goal_id: &str) -> anyhow::Result<bool> {
        let result = sqlx::query("DELETE FROM scheduled_run_state WHERE goal_id = ?")
            .bind(goal_id)
            .execute(&self.pool)
            .await?;
        Ok(result.rows_affected() > 0)
    }
}

#[async_trait]
impl crate::traits::TaskDispatchStore for SqliteStateStore {
    async fn get_pending_tasks_by_priority(&self, limit: i64) -> anyhow::Result<Vec<Task>> {
        let rows = sqlx::query(
            "SELECT t.id, t.goal_id, t.description, t.status, t.priority, t.task_order,
             t.parallel_group, t.depends_on, t.agent_id, t.context, t.result, t.error,
             t.blocker, t.idempotent, t.retry_count, t.max_retries, t.created_at,
             t.started_at, t.completed_at
             FROM tasks t
             JOIN goals g ON t.goal_id = g.id AND g.domain = 'orchestration' AND g.status = 'active'
             WHERE t.status = 'pending'
             AND NOT EXISTS (
                 SELECT 1 FROM json_each(COALESCE(t.depends_on, '[]')) AS dep
                 WHERE NOT EXISTS (
                     SELECT 1 FROM tasks d WHERE d.id = dep.value AND d.status = 'completed'
                 )
             )
             ORDER BY
                 CASE t.priority WHEN 'high' THEN 1 WHEN 'medium' THEN 2 WHEN 'low' THEN 3 ELSE 4 END,
                 t.task_order ASC
             LIMIT ?",
        )
        .bind(limit)
        .fetch_all(&self.pool)
        .await?;

        Ok(rows
            .iter()
            .map(|r| Task {
                id: r.get("id"),
                goal_id: r.get("goal_id"),
                description: r.get("description"),
                status: r.get("status"),
                priority: r.get("priority"),
                task_order: r.get("task_order"),
                parallel_group: r.get("parallel_group"),
                depends_on: r.get("depends_on"),
                agent_id: r.get("agent_id"),
                context: r.get("context"),
                result: r.get("result"),
                error: r.get("error"),
                blocker: r.get("blocker"),
                idempotent: r.get::<i32, _>("idempotent") != 0,
                retry_count: r.get("retry_count"),
                max_retries: r.get("max_retries"),
                created_at: r.get("created_at"),
                started_at: r.get("started_at"),
                completed_at: r.get("completed_at"),
            })
            .collect())
    }

    async fn get_stuck_tasks(&self, timeout_secs: i64) -> anyhow::Result<Vec<Task>> {
        let rows = sqlx::query(
            "SELECT id, goal_id, description, status, priority, task_order,
             parallel_group, depends_on, agent_id, context, result, error,
             blocker, idempotent, retry_count, max_retries, created_at,
             started_at, completed_at
             FROM tasks
             WHERE status IN ('running', 'claimed')
             AND datetime(started_at) < datetime('now', '-' || ? || ' seconds')
             ORDER BY started_at ASC",
        )
        .bind(timeout_secs)
        .fetch_all(&self.pool)
        .await?;

        Ok(rows
            .iter()
            .map(|r| Task {
                id: r.get("id"),
                goal_id: r.get("goal_id"),
                description: r.get("description"),
                status: r.get("status"),
                priority: r.get("priority"),
                task_order: r.get("task_order"),
                parallel_group: r.get("parallel_group"),
                depends_on: r.get("depends_on"),
                agent_id: r.get("agent_id"),
                context: r.get("context"),
                result: r.get("result"),
                error: r.get("error"),
                blocker: r.get("blocker"),
                idempotent: r.get::<i32, _>("idempotent") != 0,
                retry_count: r.get("retry_count"),
                max_retries: r.get("max_retries"),
                created_at: r.get("created_at"),
                started_at: r.get("started_at"),
                completed_at: r.get("completed_at"),
            })
            .collect())
    }

    async fn get_recently_completed_tasks(&self, since: &str) -> anyhow::Result<Vec<Task>> {
        let rows = sqlx::query(
            "SELECT id, goal_id, description, status, priority, task_order,
             parallel_group, depends_on, agent_id, context, result, error,
             blocker, idempotent, retry_count, max_retries, created_at,
             started_at, completed_at
             FROM tasks
             WHERE status = 'completed' AND completed_at > ?
             ORDER BY completed_at DESC",
        )
        .bind(since)
        .fetch_all(&self.pool)
        .await?;

        Ok(rows
            .iter()
            .map(|r| Task {
                id: r.get("id"),
                goal_id: r.get("goal_id"),
                description: r.get("description"),
                status: r.get("status"),
                priority: r.get("priority"),
                task_order: r.get("task_order"),
                parallel_group: r.get("parallel_group"),
                depends_on: r.get("depends_on"),
                agent_id: r.get("agent_id"),
                context: r.get("context"),
                result: r.get("result"),
                error: r.get("error"),
                blocker: r.get("blocker"),
                idempotent: r.get::<i32, _>("idempotent") != 0,
                retry_count: r.get("retry_count"),
                max_retries: r.get("max_retries"),
                created_at: r.get("created_at"),
                started_at: r.get("started_at"),
                completed_at: r.get("completed_at"),
            })
            .collect())
    }

    async fn mark_task_interrupted(&self, task_id: &str) -> anyhow::Result<bool> {
        let result = sqlx::query(
            "UPDATE tasks SET status = 'interrupted',
             completed_at = datetime('now')
             WHERE id = ? AND status IN ('running', 'claimed')",
        )
        .bind(task_id)
        .execute(&self.pool)
        .await?;
        Ok(result.rows_affected() > 0)
    }
}

#[async_trait]
impl crate::traits::GoalNotificationStore for SqliteStateStore {
    async fn count_active_evergreen_goals(&self) -> anyhow::Result<i64> {
        let row = sqlx::query(
            "SELECT COUNT(*) as cnt FROM goals
             WHERE domain = 'orchestration' AND goal_type = 'continuous' AND status = 'active'",
        )
        .fetch_one(&self.pool)
        .await?;
        Ok(row.get::<i64, _>("cnt"))
    }

    async fn get_goals_needing_notification(&self) -> anyhow::Result<Vec<Goal>> {
        let rows = sqlx::query(
            "SELECT id, description, domain, goal_type, status, priority, conditions,
             context, resources, budget_per_check, budget_daily, tokens_used_today, tokens_used_day,
             last_useful_action, created_at, updated_at, completed_at, parent_goal_id,
             session_id, notified_at, notification_attempts, dispatch_failures, progress_notes, source_episode_id, legacy_int_id
             FROM goals
             WHERE domain = 'orchestration'
               AND status IN ('completed', 'failed', 'stalled')
               AND notified_at IS NULL
               AND goal_type = 'finite'
               AND notification_attempts < 3",
        )
        .fetch_all(&self.pool)
        .await?;

        Ok(rows
            .iter()
            .map(|r| {
                let progress_notes_json: Option<String> = r.get("progress_notes");
                let progress_notes =
                    progress_notes_json.and_then(|j| serde_json::from_str(&j).ok());
                Goal {
                    id: r.get("id"),
                    description: r.get("description"),
                    domain: r.get("domain"),
                    goal_type: r.get("goal_type"),
                    status: r.get("status"),
                    priority: r.get("priority"),
                    conditions: r.get("conditions"),
                    context: r.get("context"),
                    resources: r.get("resources"),
                    budget_per_check: r.get("budget_per_check"),
                    budget_daily: r.get("budget_daily"),
                    tokens_used_today: r.get("tokens_used_today"),
                    tokens_used_day: r.get("tokens_used_day"),
                    last_useful_action: r.get("last_useful_action"),
                    created_at: r.get("created_at"),
                    updated_at: r.get("updated_at"),
                    completed_at: r.get("completed_at"),
                    parent_goal_id: r.get("parent_goal_id"),
                    session_id: r.get("session_id"),
                    notified_at: r.get("notified_at"),
                    notification_attempts: r.get::<i32, _>("notification_attempts"),
                    dispatch_failures: r.get::<i32, _>("dispatch_failures"),
                    progress_notes,
                    source_episode_id: r.get("source_episode_id"),
                    legacy_int_id: r.get("legacy_int_id"),
                }
            })
            .collect())
    }

    async fn mark_goal_notified(&self, goal_id: &str) -> anyhow::Result<()> {
        let now = chrono::Utc::now().to_rfc3339();
        sqlx::query("UPDATE goals SET notified_at = ? WHERE id = ?")
            .bind(&now)
            .bind(goal_id)
            .execute(&self.pool)
            .await?;
        Ok(())
    }

    async fn cleanup_stale_goals(&self, stale_hours: i64) -> anyhow::Result<u64> {
        let cutoff = (chrono::Utc::now() - chrono::Duration::hours(stale_hours)).to_rfc3339();
        let now = chrono::Utc::now().to_rfc3339();

        // Finite orchestration goals without schedules: stale active/pending -> failed.
        let result = sqlx::query(
            "UPDATE goals
             SET status = 'failed', updated_at = ?, completed_at = ?
             WHERE domain = 'orchestration'
               AND status IN ('active', 'pending')
               AND goal_type = 'finite'
               AND updated_at < ?
               AND NOT EXISTS (
                   SELECT 1 FROM goal_schedules s WHERE s.goal_id = goals.id
               )",
        )
        .bind(&now)
        .bind(&now)
        .bind(&cutoff)
        .execute(&self.pool)
        .await?;

        Ok(result.rows_affected())
    }
}