aven-core 0.1.28

Core library for the Aven local-first task manager
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
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;

use crate::ids::WorkspaceId;
use anyhow::{Result, bail};
use sqlx::SqliteConnection;
use tracing::{info, warn};

use crate::change_log::{ChangeEntity, ChangePayload, append_change, op_type};
use crate::choices::{TaskPriority, TaskSource, TaskStatus};
use crate::db::{Database, begin_immediate, set_field_version};
use crate::ids::{TaskId, new_id, now};
use crate::labels::{
    CreatedLabel, resolve_labels_in_workspace, resolve_or_create_labels_in_workspace,
};
use crate::metadata::TaskMetadataInput;
use crate::mutation::{set_task_field, set_task_project};
use crate::projects::resolve_or_create_project_in_workspace;
use crate::refs::{DisplayRefContext, get_task_in_workspace};
use crate::task_fields::TaskField;
use crate::types::Task;
use crate::undo::{
    TaskUndoSnapshot, UndoCommand, UndoContext, UndoPayload, record_tui_undo, task_snapshot,
};
use crate::workspaces::Workspace;

pub struct TaskDraft {
    pub title: String,
    pub description: String,
    pub project: Option<String>,
    pub status: String,
    pub priority: String,
    pub source: TaskSource,
    pub labels: Vec<String>,
    pub metadata: Vec<TaskMetadataInput>,
    pub available_at: Option<String>,
    pub due_on: Option<String>,
    pub is_epic: bool,
}

#[derive(Debug, Clone, Default)]
pub enum TaskCreationUndo {
    #[default]
    None,
    TuiTask,
    TuiEpicChild {
        epic_id: TaskId,
        epic_display_ref: String,
    },
}

#[derive(Debug, Clone)]
pub struct TaskCreationOptions {
    epic_id: Option<TaskId>,
    undo: TaskCreationUndo,
    create_missing_labels: bool,
}

impl TaskCreationOptions {
    pub fn standalone(undo: TaskCreationUndo) -> Self {
        Self {
            epic_id: None,
            undo,
            create_missing_labels: false,
        }
    }

    pub fn for_epic(epic_id: TaskId, undo: TaskCreationUndo) -> Self {
        Self {
            epic_id: Some(epic_id),
            undo,
            create_missing_labels: false,
        }
    }

    pub fn with_create_missing_labels(mut self) -> Self {
        self.create_missing_labels = true;
        self
    }
}

#[derive(Debug)]
pub struct TaskOutcome {
    pub task: Task,
    pub create_change_id: Option<String>,
    pub attachment_change_ids: Vec<String>,
}

struct InsertedTask {
    id: TaskId,
    change_id: String,
    project_key: String,
    label_count: usize,
    created_labels: Vec<CreatedLabel>,
}

#[derive(Debug, Clone)]
pub struct TaskLabelSelection {
    pub selected: Vec<String>,
    pub partial: Vec<String>,
}

#[derive(Clone, Default)]
pub struct TaskUpdate {
    pub title: Option<String>,
    pub description: Option<String>,
    pub project: Option<String>,
    pub status: Option<String>,
    pub priority: Option<String>,
    pub cycle_priority: Option<bool>,
    pub available_at: Option<Option<String>>,
    pub due_on: Option<Option<String>>,
    pub deleted: Option<bool>,
    pub is_epic: Option<bool>,
    pub add_labels: Vec<String>,
    pub remove_labels: Vec<String>,
    pub set_metadata: Vec<TaskMetadataInput>,
    pub remove_metadata: Vec<String>,
    pub label_selection: Option<TaskLabelSelection>,
    pub create_missing_labels: bool,
}

pub struct TaskUpdateOutcome {
    pub task: Task,
    pub changed: bool,
}

#[derive(Debug)]
pub struct TaskMutationOutcome {
    pub task: Task,
    pub before: TaskUndoSnapshot,
    pub after: TaskUndoSnapshot,
    pub changed: bool,
}

#[derive(Debug)]
pub struct TaskMutationReport {
    pub outcomes: Vec<TaskMutationOutcome>,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum TaskMutationDetail {
    Report,
    Compact,
}

struct TaskMutationExecutionOutcome {
    task: Task,
    before: Option<TaskUndoSnapshot>,
    after: Option<TaskUndoSnapshot>,
    changed: bool,
}

impl TaskMutationReport {
    pub fn changed_count(&self) -> usize {
        self.outcomes
            .iter()
            .filter(|outcome| outcome.changed)
            .count()
    }
}

pub struct NoteEditOutcome {
    #[allow(dead_code)]
    pub task_id: TaskId,
    #[allow(dead_code)]
    pub note_id: String,
    pub found: bool,
    pub changed: bool,
}

pub struct NoteDeleteOutcome {
    #[allow(dead_code)]
    pub task_id: TaskId,
    #[allow(dead_code)]
    pub note_id: String,
    pub changed: bool,
}

pub struct NoteOutcome {
    #[allow(dead_code)]
    pub task_id: TaskId,
    pub note_id: String,
    pub change_id: String,
}
impl Database {
    pub async fn create_task(
        &self,
        workspace: &Workspace,
        draft: TaskDraft,
    ) -> Result<TaskOutcome> {
        self.create_task_with_undo(workspace, draft, TaskCreationUndo::None)
            .await
    }

    pub async fn create_task_with_undo(
        &self,
        workspace: &Workspace,
        draft: TaskDraft,
        undo: TaskCreationUndo,
    ) -> Result<TaskOutcome> {
        self.create_task_with_options(workspace, draft, TaskCreationOptions::standalone(undo))
            .await
    }

    pub async fn create_task_with_options(
        &self,
        workspace: &Workspace,
        draft: TaskDraft,
        options: TaskCreationOptions,
    ) -> Result<TaskOutcome> {
        let mut conn = self.acquire_writer().await?;
        create_task_with_epic(&mut conn, workspace, draft, options).await
    }

    pub async fn create_task_for_epic(
        &self,
        workspace: &Workspace,
        draft: TaskDraft,
        epic_id: &TaskId,
    ) -> Result<TaskOutcome> {
        self.create_task_for_epic_with_undo(workspace, draft, epic_id, TaskCreationUndo::None)
            .await
    }

    pub async fn create_task_for_epic_with_undo(
        &self,
        workspace: &Workspace,
        draft: TaskDraft,
        epic_id: &TaskId,
        undo: TaskCreationUndo,
    ) -> Result<TaskOutcome> {
        let mut conn = self.acquire_writer().await?;
        create_task_with_epic(
            &mut conn,
            workspace,
            draft,
            TaskCreationOptions::for_epic(epic_id.clone(), undo),
        )
        .await
    }

    pub async fn create_task_with_attachments(
        &self,
        workspace: &Workspace,
        blob_dir: &Path,
        lifecycle_policy: crate::attachments::lifecycle::LifecyclePolicy,
        draft: TaskDraft,
        attachments: Vec<super::attachments::TaskAttachmentAddInput>,
    ) -> Result<TaskOutcome> {
        self.create_task_with_attachments_and_undo(
            workspace,
            blob_dir,
            lifecycle_policy,
            draft,
            attachments,
            TaskCreationUndo::None,
        )
        .await
    }

    pub async fn create_task_with_attachments_and_undo(
        &self,
        workspace: &Workspace,
        blob_dir: &Path,
        lifecycle_policy: crate::attachments::lifecycle::LifecyclePolicy,
        draft: TaskDraft,
        attachments: Vec<super::attachments::TaskAttachmentAddInput>,
        undo: TaskCreationUndo,
    ) -> Result<TaskOutcome> {
        self.create_task_with_attachments_and_options(
            workspace,
            blob_dir,
            lifecycle_policy,
            draft,
            attachments,
            TaskCreationOptions::standalone(undo),
        )
        .await
    }

    pub async fn create_task_with_attachments_and_options(
        &self,
        workspace: &Workspace,
        blob_dir: &Path,
        lifecycle_policy: crate::attachments::lifecycle::LifecyclePolicy,
        draft: TaskDraft,
        attachments: Vec<super::attachments::TaskAttachmentAddInput>,
        options: TaskCreationOptions,
    ) -> Result<TaskOutcome> {
        let mut conn = self.acquire_writer().await?;
        create_task_with_attachments_and_epic(
            &mut conn,
            workspace,
            blob_dir,
            lifecycle_policy,
            draft,
            attachments,
            options,
        )
        .await
    }

    pub async fn create_task_with_attachments_for_epic(
        &self,
        workspace: &Workspace,
        blob_dir: &Path,
        lifecycle_policy: crate::attachments::lifecycle::LifecyclePolicy,
        draft: TaskDraft,
        attachments: Vec<super::attachments::TaskAttachmentAddInput>,
        epic_id: &TaskId,
    ) -> Result<TaskOutcome> {
        self.create_task_with_attachments_for_epic_and_undo(
            workspace,
            blob_dir,
            lifecycle_policy,
            draft,
            attachments,
            TaskCreationOptions::for_epic(epic_id.clone(), TaskCreationUndo::None),
        )
        .await
    }

    pub async fn create_task_with_attachments_for_epic_and_undo(
        &self,
        workspace: &Workspace,
        blob_dir: &Path,
        lifecycle_policy: crate::attachments::lifecycle::LifecyclePolicy,
        draft: TaskDraft,
        attachments: Vec<super::attachments::TaskAttachmentAddInput>,
        options: TaskCreationOptions,
    ) -> Result<TaskOutcome> {
        let mut conn = self.acquire_writer().await?;
        create_task_with_attachments_and_epic(
            &mut conn,
            workspace,
            blob_dir,
            lifecycle_policy,
            draft,
            attachments,
            options,
        )
        .await
    }

    pub async fn update_task(
        &self,
        workspace: &Workspace,
        task_id: &TaskId,
        update: TaskUpdate,
    ) -> Result<TaskUpdateOutcome> {
        let outcomes = self
            .mutate_tasks_owned(
                workspace,
                vec![(task_id.clone(), update)],
                UndoContext::None,
                TaskMutationDetail::Compact,
            )
            .await?;
        let outcome = outcomes.into_iter().next().unwrap();
        Ok(TaskUpdateOutcome {
            task: outcome.task,
            changed: outcome.changed,
        })
    }

    pub async fn update_tasks(
        &self,
        workspace: &Workspace,
        updates: Vec<(TaskId, TaskUpdate)>,
    ) -> Result<Vec<TaskUpdateOutcome>> {
        Ok(self
            .mutate_tasks_owned(
                workspace,
                updates,
                UndoContext::None,
                TaskMutationDetail::Compact,
            )
            .await?
            .into_iter()
            .map(|outcome| TaskUpdateOutcome {
                task: outcome.task,
                changed: outcome.changed,
            })
            .collect())
    }

    pub async fn mutate_tasks(
        &self,
        workspace: &Workspace,
        updates: Vec<(TaskId, TaskUpdate)>,
        undo: UndoContext,
    ) -> Result<TaskMutationReport> {
        let outcomes = self
            .mutate_tasks_owned(workspace, updates, undo, TaskMutationDetail::Report)
            .await?;
        Ok(TaskMutationReport {
            outcomes: outcomes
                .into_iter()
                .map(|outcome| TaskMutationOutcome {
                    task: outcome.task,
                    before: outcome.before.expect("report mutation before snapshot"),
                    after: outcome.after.expect("report mutation after snapshot"),
                    changed: outcome.changed,
                })
                .collect(),
        })
    }

    async fn mutate_tasks_owned(
        &self,
        workspace: &Workspace,
        updates: Vec<(TaskId, TaskUpdate)>,
        undo: UndoContext,
        detail: TaskMutationDetail,
    ) -> Result<Vec<TaskMutationExecutionOutcome>> {
        for (_, update) in &updates {
            validate_task_update(update)?;
        }
        if updates.is_empty() {
            return Ok(Vec::new());
        }
        if detail == TaskMutationDetail::Compact && !matches!(&undo, UndoContext::None) {
            bail!("compact task mutations cannot record undo");
        }

        let mut conn = self.acquire_writer().await?;
        let mut tx = begin_immediate(&mut conn).await?;
        let mut outcomes = Vec::with_capacity(updates.len());
        let mut affected_attachment_hashes = BTreeSet::new();
        let mut undo_commands = Vec::new();
        let mut created_labels = Vec::new();
        for (task_id, update) in &updates {
            let before =
                if detail == TaskMutationDetail::Report || task_update_requires_snapshot(update) {
                    Some(task_snapshot(&mut tx, &workspace.id, task_id).await?)
                } else {
                    None
                };
            let update = match before.as_ref() {
                Some(before) => materialize_task_update(update, before)?,
                None => update.clone(),
            };
            let (changed, task_created_labels) = apply_task_update(
                &mut tx,
                workspace,
                task_id,
                &update,
                &mut affected_attachment_hashes,
            )
            .await?;
            created_labels.extend(task_created_labels);
            let task = get_task_in_workspace(&mut tx, workspace, task_id).await?;
            let after = if detail == TaskMutationDetail::Report {
                Some(task_snapshot(&mut tx, &workspace.id, task_id).await?)
            } else {
                None
            };
            if let (Some(before), Some(after)) = (&before, &after) {
                append_task_undo_commands(task_id, before, after, &mut undo_commands);
            }
            outcomes.push(TaskMutationExecutionOutcome {
                task,
                changed,
                before,
                after,
            });
        }
        let affected_attachment_hashes = affected_attachment_hashes.into_iter().collect::<Vec<_>>();
        crate::attachments::lifecycle::reconcile_liveness_for_hashes_in_transaction(
            &mut tx,
            &affected_attachment_hashes,
            &crate::attachments::lifecycle::SystemClock,
        )
        .await?;
        let changed_count = outcomes.iter().filter(|outcome| outcome.changed).count();
        append_created_label_undo_commands(&mut undo_commands, &created_labels);
        if let Some(summary) = undo.task_mutation_summary(changed_count) {
            record_tui_undo(
                &mut tx,
                &workspace.id,
                &summary,
                UndoPayload {
                    commands: undo_commands,
                },
            )
            .await?;
        }
        tx.commit().await?;

        for outcome in &outcomes {
            info!(task_id = %outcome.task.id, changed = outcome.changed, "task updated");
        }
        Ok(outcomes)
    }

    pub async fn set_task_deleted(
        &self,
        workspace: &Workspace,
        task_id: &TaskId,
        deleted: bool,
    ) -> Result<TaskOutcome> {
        let outcome = self
            .update_task(
                workspace,
                task_id,
                TaskUpdate {
                    deleted: Some(deleted),
                    ..TaskUpdate::default()
                },
            )
            .await?;
        Ok(TaskOutcome {
            task: outcome.task,
            create_change_id: None,
            attachment_change_ids: Vec::new(),
        })
    }

    pub async fn add_note(
        &self,
        workspace: &Workspace,
        task_id: &TaskId,
        body: String,
    ) -> Result<NoteOutcome> {
        let mut conn = self.acquire_writer().await?;
        add_note_operation(&mut conn, workspace, task_id, body, false).await
    }

    pub async fn add_note_with_tui_undo(
        &self,
        workspace: &Workspace,
        task_id: &TaskId,
        body: String,
    ) -> Result<NoteOutcome> {
        let mut conn = self.acquire_writer().await?;
        add_note_operation(&mut conn, workspace, task_id, body, true).await
    }

    pub async fn edit_note(
        &self,
        workspace: &Workspace,
        task_id: &TaskId,
        note_id: &str,
        body: String,
    ) -> Result<NoteEditOutcome> {
        let mut conn = self.acquire_writer().await?;
        edit_note_operation(&mut conn, workspace, task_id, note_id, body, false).await
    }

    pub async fn edit_note_with_tui_undo(
        &self,
        workspace: &Workspace,
        task_id: &TaskId,
        note_id: &str,
        body: String,
    ) -> Result<NoteEditOutcome> {
        let mut conn = self.acquire_writer().await?;
        edit_note_operation(&mut conn, workspace, task_id, note_id, body, true).await
    }

    pub async fn delete_note(
        &self,
        workspace: &Workspace,
        task_id: &TaskId,
        note_id: &str,
    ) -> Result<NoteDeleteOutcome> {
        let mut conn = self.acquire_writer().await?;
        delete_note_operation(&mut conn, workspace, task_id, note_id, false).await
    }

    pub async fn delete_note_with_tui_undo(
        &self,
        workspace: &Workspace,
        task_id: &TaskId,
        note_id: &str,
    ) -> Result<NoteDeleteOutcome> {
        let mut conn = self.acquire_writer().await?;
        delete_note_operation(&mut conn, workspace, task_id, note_id, true).await
    }
}

#[cfg(any(test, feature = "test-support"))]
pub async fn create_task(
    conn: &mut SqliteConnection,
    workspace: &Workspace,
    draft: TaskDraft,
) -> Result<TaskOutcome> {
    create_task_with_epic(
        conn,
        workspace,
        draft,
        TaskCreationOptions::standalone(TaskCreationUndo::None),
    )
    .await
}

async fn create_task_with_epic(
    conn: &mut SqliteConnection,
    workspace: &Workspace,
    draft: TaskDraft,
    options: TaskCreationOptions,
) -> Result<TaskOutcome> {
    validate_task_draft(&draft)?;
    let TaskCreationOptions {
        epic_id,
        undo,
        create_missing_labels,
    } = options;
    let mut tx = begin_immediate(conn).await?;
    let inserted = insert_task(&mut tx, workspace, draft, create_missing_labels).await?;
    if let Some(epic_id) = epic_id {
        super::add_task_to_epic_in_transaction(&mut tx, workspace, &inserted.id, &epic_id).await?;
    }
    let task = get_task_in_workspace(&mut tx, workspace, &inserted.id).await?;
    record_task_creation_undo(
        &mut tx,
        workspace,
        &task,
        &inserted,
        Vec::new(),
        Vec::new(),
        undo,
    )
    .await?;
    tx.commit().await?;
    info!(
        task_id = %inserted.id,
        project_key = %inserted.project_key,
        label_count = inserted.label_count,
        "task created"
    );
    Ok(TaskOutcome {
        task,
        create_change_id: Some(inserted.change_id),
        attachment_change_ids: Vec::new(),
    })
}

async fn create_task_with_attachments_and_epic(
    conn: &mut SqliteConnection,
    workspace: &Workspace,
    blob_dir: &Path,
    lifecycle_policy: crate::attachments::lifecycle::LifecyclePolicy,
    draft: TaskDraft,
    attachments: Vec<super::attachments::TaskAttachmentAddInput>,
    options: TaskCreationOptions,
) -> Result<TaskOutcome> {
    validate_task_draft(&draft)?;
    let TaskCreationOptions {
        epic_id,
        undo,
        create_missing_labels,
    } = options;
    let mut prepared = Vec::with_capacity(attachments.len());
    for attachment in attachments {
        prepared.push(super::attachments::prepare_task_attachment(attachment).await?);
    }

    let mut unique = BTreeMap::new();
    for attachment in &prepared {
        unique
            .entry(attachment.sha256.clone())
            .or_insert_with(|| attachment.clone());
    }
    let attachment_hashes = unique.keys().cloned().collect::<Vec<_>>();

    let mut capacity_reservations = Vec::new();
    for attachment in unique.values() {
        let available: bool = sqlx::query_scalar(
            "SELECT EXISTS(SELECT 1 FROM blob_inventory WHERE sha256 = ? AND available = 1)",
        )
        .bind(&attachment.sha256)
        .fetch_one(&mut *conn)
        .await?;
        if available {
            continue;
        }
        match crate::attachments::lifecycle::ensure_local_capacity(
            conn,
            blob_dir,
            &attachment.sha256,
            attachment.byte_size,
            lifecycle_policy,
            &crate::attachments::lifecycle::SystemClock,
        )
        .await
        {
            Ok(Some(reservation_id)) => capacity_reservations.push(reservation_id),
            Ok(None) => {}
            Err(error) => {
                for reservation_id in capacity_reservations {
                    let _ =
                        crate::attachments::lifecycle::release_reservation(conn, &reservation_id)
                            .await;
                }
                return Err(error);
            }
        }
    }

    let mut staging_leases = Vec::with_capacity(unique.len());
    for attachment in unique.values() {
        match crate::attachments::lifecycle::acquire_lease(
            conn,
            &attachment.sha256,
            "staging",
            &crate::attachments::lifecycle::SystemClock,
        )
        .await
        {
            Ok(lease_id) => staging_leases.push(lease_id),
            Err(error) => {
                for lease_id in staging_leases {
                    let _ = crate::attachments::lifecycle::release_lease(conn, &lease_id).await;
                }
                for reservation_id in capacity_reservations {
                    let _ =
                        crate::attachments::lifecycle::release_reservation(conn, &reservation_id)
                            .await;
                }
                return Err(error);
            }
        }
    }

    let mut created_hashes = Vec::new();
    for attachment in unique.values() {
        match crate::attachments::storage::stage_blob(
            blob_dir,
            &attachment.sha256,
            &attachment.bytes,
        )
        .await
        {
            Ok(staged) if staged.byte_size == attachment.byte_size => {
                if staged.created {
                    created_hashes.push(staged.sha256);
                }
            }
            Ok(_) => {
                cleanup_attachment_guards(conn, &staging_leases, &capacity_reservations).await;
                cleanup_created_objects(conn, blob_dir, &created_hashes).await;
                bail!("error attachment-staged-size-mismatch");
            }
            Err(error) => {
                cleanup_attachment_guards(conn, &staging_leases, &capacity_reservations).await;
                cleanup_created_objects(conn, blob_dir, &created_hashes).await;
                return Err(error);
            }
        }
    }

    let database_result = async {
        let mut tx = begin_immediate(conn).await?;
        for attachment in unique.values() {
            crate::attachments::storage::upsert_inventory_available(
                &mut tx,
                &attachment.sha256,
                attachment.byte_size,
                &attachment.facts.media_type,
            )
            .await?;
        }
        let inserted = insert_task(&mut tx, workspace, draft, create_missing_labels).await?;
        if let Some(epic_id) = epic_id.as_ref() {
            super::add_task_to_epic_in_transaction(&mut tx, workspace, &inserted.id, epic_id)
                .await?;
        }
        let mut attachment_change_ids = Vec::with_capacity(prepared.len());
        let attachment_base = crate::ids::now_utc();
        for (index, attachment) in prepared.iter().enumerate() {
            let created_at = (attachment_base
                + chrono::TimeDelta::microseconds(i64::try_from(index)?))
            .to_rfc3339_opts(chrono::SecondsFormat::Micros, true);
            attachment_change_ids.push(
                super::attachments::insert_prepared_attachment(
                    &mut tx,
                    workspace,
                    &inserted.id,
                    attachment,
                    &created_at,
                )
                .await?,
            );
        }
        crate::attachments::lifecycle::reconcile_liveness_for_hashes_in_transaction(
            &mut tx,
            &attachment_hashes,
            &crate::attachments::lifecycle::SystemClock,
        )
        .await?;
        let task = get_task_in_workspace(&mut tx, workspace, &inserted.id).await?;
        let attachment_ids = prepared
            .iter()
            .map(|attachment| attachment.attachment_id.clone())
            .collect();
        record_task_creation_undo(
            &mut tx,
            workspace,
            &task,
            &inserted,
            attachment_ids,
            attachment_change_ids.clone(),
            undo,
        )
        .await?;
        tx.commit().await?;
        Ok::<_, anyhow::Error>((inserted, attachment_change_ids, task))
    }
    .await;

    let (inserted, attachment_change_ids, task) = match database_result {
        Ok(value) => value,
        Err(error) => {
            cleanup_attachment_guards(conn, &staging_leases, &capacity_reservations).await;
            cleanup_created_objects(conn, blob_dir, &created_hashes).await;
            return Err(error);
        }
    };
    cleanup_attachment_guards(conn, &staging_leases, &capacity_reservations).await;
    info!(
        task_id = %inserted.id,
        project_key = %inserted.project_key,
        label_count = inserted.label_count,
        attachment_count = prepared.len(),
        "task created"
    );
    Ok(TaskOutcome {
        task,
        create_change_id: Some(inserted.change_id),
        attachment_change_ids,
    })
}

async fn record_task_creation_undo(
    conn: &mut SqliteConnection,
    workspace: &Workspace,
    task: &Task,
    inserted: &InsertedTask,
    attachment_ids: Vec<String>,
    attachment_change_ids: Vec<String>,
    undo: TaskCreationUndo,
) -> Result<()> {
    let (summary, commands) = match undo {
        TaskCreationUndo::None => return Ok(()),
        TaskCreationUndo::TuiTask => {
            let mut commands = vec![UndoCommand::DeleteCreatedTask {
                task_id: task.id.clone(),
                create_change_id: Some(inserted.change_id.clone()),
                expected: task_snapshot(conn, &workspace.id, &task.id).await?,
                attachment_ids,
                attachment_change_ids,
            }];
            append_created_label_undo_commands(&mut commands, &inserted.created_labels);
            (format!("task {}", task.id), commands)
        }
        TaskCreationUndo::TuiEpicChild {
            epic_id,
            epic_display_ref,
        } => {
            let display_refs = DisplayRefContext::for_workspace(conn, &workspace.id).await?;
            let child_ref = display_refs.display_ref(task);
            (
                format!("add {child_ref} to {epic_display_ref}"),
                vec![UndoCommand::AddEpicChild {
                    epic_id,
                    child_id: task.id.clone(),
                }],
            )
        }
    };
    record_tui_undo(conn, &workspace.id, &summary, UndoPayload { commands }).await
}

fn append_created_label_undo_commands(
    commands: &mut Vec<UndoCommand>,
    created_labels: &[CreatedLabel],
) {
    commands.extend(
        created_labels
            .iter()
            .map(|label| UndoCommand::DeleteCreatedLabel {
                label: label.name.clone(),
                create_change_id: label.change_id.clone(),
            }),
    );
}

fn validate_task_draft(draft: &TaskDraft) -> Result<()> {
    TaskStatus::parse(&draft.status)?;
    TaskPriority::parse(&draft.priority)?;
    crate::metadata::validate_metadata_update(&draft.metadata, &[])?;
    if let Some(available_at) = draft.available_at.as_deref() {
        crate::time_validation::validate_available_at_value(available_at)?;
    }
    if let Some(due_on) = draft.due_on.as_deref() {
        crate::time_validation::validate_due_on_value(due_on)?;
    }
    Ok(())
}

async fn insert_task(
    conn: &mut SqliteConnection,
    workspace: &Workspace,
    draft: TaskDraft,
    create_missing_labels: bool,
) -> Result<InsertedTask> {
    let status = TaskStatus::parse(&draft.status)?;
    let priority = TaskPriority::parse(&draft.priority)?;
    let available_at = draft.available_at.as_deref().unwrap_or("");
    let due_on = draft.due_on.as_deref().unwrap_or("");
    let id = TaskId::new();
    let ts = now();
    let project = draft
        .project
        .as_deref()
        .ok_or_else(|| anyhow::anyhow!("error project-required"))?;
    let project = resolve_or_create_project_in_workspace(conn, &workspace.id, project).await?;
    let (labels, created_labels) = if create_missing_labels {
        let resolution =
            resolve_or_create_labels_in_workspace(conn, workspace, &draft.labels).await?;
        (resolution.names, resolution.created)
    } else {
        (
            resolve_labels_in_workspace(conn, &workspace.id, &draft.labels).await?,
            Vec::new(),
        )
    };
    sqlx::query(
        "INSERT INTO tasks(workspace_id, id, title, description, project_id, status, priority, source, created_at, updated_at, queue_activity_at, available_at, due_on, is_epic)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
    )
    .bind(&workspace.id)
    .bind(&id)
    .bind(&draft.title)
    .bind(&draft.description)
    .bind(&project.id)
    .bind(status.as_str())
    .bind(priority.as_str())
    .bind(draft.source.as_str())
    .bind(&ts)
    .bind(&ts)
    .bind(&ts)
    .bind(available_at)
    .bind(due_on)
    .bind(i64::from(draft.is_epic))
    .execute(&mut *conn)
    .await?;
    for label in &labels {
        sqlx::query(
            "INSERT OR IGNORE INTO task_labels(workspace_id, task_id, label) VALUES (?, ?, ?)",
        )
        .bind(&workspace.id)
        .bind(&id)
        .bind(label)
        .execute(&mut *conn)
        .await?;
    }
    let metadata =
        crate::metadata::insert_initial_task_metadata(conn, workspace, &id, &draft.metadata, &ts)
            .await?;
    let change_id = append_change(
        conn,
        ChangeEntity::Task,
        &id,
        None,
        op_type::CREATE_TASK,
        ChangePayload::workspace(workspace)
            .set("title", draft.title)
            .set("description", draft.description)
            .set("project_id", project.id.clone())
            .set("project_key", project.key.clone())
            .set("project_name", project.name.clone())
            .set("project_prefix", project.prefix.clone())
            .set("status", status.as_str())
            .set("priority", priority.as_str())
            .set("source", draft.source.as_str())
            .set("available_at", available_at)
            .set("due_on", due_on)
            .set("is_epic", if draft.is_epic { "1" } else { "0" })
            .set("labels", &labels)
            .set("metadata", &metadata)
            .set("created_at", ts),
    )
    .await?;
    for field in TaskField::VERSIONED {
        set_field_version(conn, &id, field.as_str(), &change_id).await?;
    }
    for value in &metadata {
        set_field_version(
            conn,
            &id,
            &format!("metadata:{}", value.field_id),
            &change_id,
        )
        .await?;
    }
    Ok(InsertedTask {
        id,
        change_id,
        project_key: project.key,
        label_count: labels.len(),
        created_labels,
    })
}

async fn cleanup_attachment_guards(
    conn: &mut SqliteConnection,
    leases: &[String],
    reservations: &[String],
) {
    for lease_id in leases {
        if let Err(error) = crate::attachments::lifecycle::release_lease(conn, lease_id).await {
            warn!(%error, "failed to release attachment staging lease");
        }
    }
    for reservation_id in reservations {
        if let Err(error) =
            crate::attachments::lifecycle::release_reservation(conn, reservation_id).await
        {
            warn!(%error, "failed to release attachment capacity reservation");
        }
    }
}

async fn cleanup_created_objects(conn: &mut SqliteConnection, blob_dir: &Path, hashes: &[String]) {
    for sha256 in hashes {
        crate::attachments::storage::remove_staged_blob_if_unreferenced(conn, blob_dir, sha256)
            .await;
    }
}

#[cfg(any(test, feature = "test-support"))]
pub async fn update_task(
    conn: &mut SqliteConnection,
    workspace: &Workspace,
    task_id: &crate::ids::TaskId,
    update: TaskUpdate,
) -> Result<TaskUpdateOutcome> {
    validate_task_update(&update)?;
    let mut tx = begin_immediate(conn).await?;
    let mut affected_attachment_hashes = BTreeSet::new();
    let (changed, _) = apply_task_update(
        &mut tx,
        workspace,
        task_id,
        &update,
        &mut affected_attachment_hashes,
    )
    .await?;
    let affected_attachment_hashes = affected_attachment_hashes.into_iter().collect::<Vec<_>>();
    crate::attachments::lifecycle::reconcile_liveness_for_hashes_in_transaction(
        &mut tx,
        &affected_attachment_hashes,
        &crate::attachments::lifecycle::SystemClock,
    )
    .await?;
    tx.commit().await?;
    Ok(TaskUpdateOutcome {
        task: get_task_in_workspace(conn, workspace, task_id).await?,
        changed,
    })
}

fn append_task_undo_commands(
    task_id: &TaskId,
    before_snapshot: &TaskUndoSnapshot,
    after_snapshot: &TaskUndoSnapshot,
    commands: &mut Vec<UndoCommand>,
) {
    let before = before_snapshot;
    let after = after_snapshot;
    let fields = [
        ("title", before.title.as_str(), after.title.as_str()),
        (
            "description",
            before.description.as_str(),
            after.description.as_str(),
        ),
        (
            "project",
            before.project_id.as_str(),
            after.project_id.as_str(),
        ),
        ("status", before.status.as_str(), after.status.as_str()),
        (
            "priority",
            before.priority.as_str(),
            after.priority.as_str(),
        ),
        (
            "available_at",
            before.available_at.as_str(),
            after.available_at.as_str(),
        ),
        ("due_on", before.due_on.as_str(), after.due_on.as_str()),
    ];
    for (field, before, after) in fields {
        if before != after {
            commands.push(UndoCommand::SetTaskField {
                task_id: task_id.clone(),
                field: field.to_string(),
                before: before.to_string(),
                after: after.to_string(),
                queue_activity_before: (before_snapshot.queue_activity_at
                    != after_snapshot.queue_activity_at)
                    .then(|| before_snapshot.queue_activity_at.clone()),
                queue_activity_after: (before_snapshot.queue_activity_at
                    != after_snapshot.queue_activity_at)
                    .then(|| after_snapshot.queue_activity_at.clone()),
            });
        }
    }
    let before_deleted = if before.deleted { "1" } else { "0" };
    let after_deleted = if after.deleted { "1" } else { "0" };
    if before_deleted != after_deleted {
        commands.push(UndoCommand::SetTaskField {
            task_id: task_id.clone(),
            field: "deleted".to_string(),
            before: before_deleted.to_string(),
            after: after_deleted.to_string(),
            queue_activity_before: (before.queue_activity_at != after.queue_activity_at)
                .then(|| before.queue_activity_at.clone()),
            queue_activity_after: (before.queue_activity_at != after.queue_activity_at)
                .then(|| after.queue_activity_at.clone()),
        });
    }
    let before_is_epic = if before.is_epic { "1" } else { "0" };
    let after_is_epic = if after.is_epic { "1" } else { "0" };
    if before_is_epic != after_is_epic {
        commands.push(UndoCommand::SetTaskField {
            task_id: task_id.clone(),
            field: "is_epic".to_string(),
            before: before_is_epic.to_string(),
            after: after_is_epic.to_string(),
            queue_activity_before: None,
            queue_activity_after: None,
        });
    }
    if before.labels != after.labels {
        commands.push(UndoCommand::SetTaskLabels {
            task_id: task_id.clone(),
            before: before.labels.clone(),
            after: after.labels.clone(),
        });
    }
    let metadata_fields = before
        .metadata
        .keys()
        .chain(after.metadata.keys())
        .collect::<BTreeSet<_>>();
    for field_id in metadata_fields {
        let before_value = before.metadata.get(field_id);
        let after_value = after.metadata.get(field_id);
        if before_value != after_value {
            commands.push(UndoCommand::SetTaskMetadata {
                task_id: task_id.clone(),
                field_id: field_id
                    .parse()
                    .expect("task snapshots contain valid metadata field IDs"),
                before: before_value.cloned(),
                after: after_value.cloned(),
            });
        }
    }
}

fn cycled_priority(priority: TaskPriority, reverse: bool) -> TaskPriority {
    let index = TaskPriority::ALL
        .iter()
        .position(|candidate| *candidate == priority)
        .unwrap_or(0);
    let next = if reverse {
        (index + TaskPriority::ALL.len() - 1) % TaskPriority::ALL.len()
    } else {
        (index + 1) % TaskPriority::ALL.len()
    };
    TaskPriority::ALL[next]
}

fn task_update_requires_snapshot(update: &TaskUpdate) -> bool {
    update.cycle_priority.is_some() || update.label_selection.is_some()
}

fn materialize_task_update(update: &TaskUpdate, before: &TaskUndoSnapshot) -> Result<TaskUpdate> {
    let mut update = update.clone();
    if let Some(reverse) = update.cycle_priority.take() {
        let priority = TaskPriority::parse(&before.priority)?;
        update.priority = Some(cycled_priority(priority, reverse).to_string());
    }
    if let Some(selection) = update.label_selection.take() {
        let selected = selection.selected.iter().cloned().collect::<BTreeSet<_>>();
        let partial = selection.partial.iter().cloned().collect::<BTreeSet<_>>();
        update.add_labels = selection
            .selected
            .into_iter()
            .filter(|label| !before.labels.contains(label))
            .collect();
        update.remove_labels = before
            .labels
            .iter()
            .filter(|label| !selected.contains(label.as_str()) && !partial.contains(label.as_str()))
            .cloned()
            .collect();
    }
    Ok(update)
}

fn validate_task_update(update: &TaskUpdate) -> Result<()> {
    crate::metadata::validate_metadata_update(&update.set_metadata, &update.remove_metadata)?;
    if update.priority.is_some() && update.cycle_priority.is_some() {
        bail!("error invalid-task-update priority and priority cycle are mutually exclusive");
    }
    if update.label_selection.is_some()
        && (!update.add_labels.is_empty() || !update.remove_labels.is_empty())
    {
        bail!("error invalid-task-update label selection and label deltas are mutually exclusive");
    }
    if let Some(status) = update.status.as_deref() {
        TaskStatus::parse(status)?;
    }
    if let Some(priority) = update.priority.as_deref() {
        TaskPriority::parse(priority)?;
    }
    if let Some(Some(available_at)) = update.available_at.as_ref() {
        crate::time_validation::validate_available_at_value(available_at)?;
    }
    if let Some(Some(due_on)) = update.due_on.as_ref() {
        crate::time_validation::validate_due_on_value(due_on)?;
    }
    Ok(())
}

async fn apply_task_update(
    conn: &mut SqliteConnection,
    workspace: &Workspace,
    task_id: &crate::ids::TaskId,
    update: &TaskUpdate,
    affected_attachment_hashes: &mut BTreeSet<String>,
) -> Result<(bool, Vec<CreatedLabel>)> {
    let created_labels = if update.create_missing_labels {
        resolve_or_create_labels_in_workspace(conn, workspace, &update.add_labels)
            .await?
            .created
    } else {
        Vec::new()
    };
    let mut changed = false;
    if let Some(title) = update.title.as_deref() {
        changed |= update_task_field(conn, workspace, task_id, "title", title).await?;
    }
    if let Some(description) = update.description.as_deref() {
        changed |= update_task_field(conn, workspace, task_id, "description", description).await?;
    }
    if let Some(project) = update.project.as_deref() {
        let project = resolve_or_create_project_in_workspace(conn, &workspace.id, project).await?;
        changed |= set_task_project(conn, workspace, task_id, &project).await?;
    }
    if let Some(status) = update.status.as_deref() {
        changed |= update_task_field(conn, workspace, task_id, "status", status).await?;
    }
    if let Some(priority) = update.priority.as_deref() {
        changed |= update_task_field(conn, workspace, task_id, "priority", priority).await?;
    }
    if let Some(available_at) = update.available_at.as_ref() {
        changed |= update_task_field(
            conn,
            workspace,
            task_id,
            "available_at",
            available_at.as_deref().unwrap_or(""),
        )
        .await?;
    }
    if let Some(due_on) = update.due_on.as_ref() {
        changed |= update_task_field(
            conn,
            workspace,
            task_id,
            "due_on",
            due_on.as_deref().unwrap_or(""),
        )
        .await?;
    }
    if update.deleted.is_some() {
        let attachment_hashes: Vec<String> = sqlx::query_scalar(
            "SELECT DISTINCT sha256 FROM task_attachments
             WHERE workspace_id = ? AND task_id = ?",
        )
        .bind(&workspace.id)
        .bind(task_id)
        .fetch_all(&mut *conn)
        .await?;
        affected_attachment_hashes.extend(attachment_hashes);
    }
    if let Some(deleted) = update.deleted {
        changed |= update_task_field(
            conn,
            workspace,
            task_id,
            "deleted",
            if deleted { "1" } else { "0" },
        )
        .await?;
    }
    if let Some(is_epic) = update.is_epic {
        if !is_epic {
            let task = get_task_in_workspace(conn, workspace, task_id).await?;
            if super::epics::task_has_epic_children(conn, &task.workspace_id, task_id).await? {
                bail!("error epic-has-children task_id={task_id}");
            }
        }
        changed |= update_task_field(
            conn,
            workspace,
            task_id,
            "is_epic",
            if is_epic { "1" } else { "0" },
        )
        .await?;
    }
    changed |= update_task_labels_in_workspace(
        conn,
        &workspace.id,
        task_id,
        &update.add_labels,
        &update.remove_labels,
    )
    .await?;
    crate::metadata::validate_task_metadata_result(
        conn,
        &workspace.id,
        task_id,
        &update.set_metadata,
        &update.remove_metadata,
    )
    .await?;
    for input in &update.set_metadata {
        changed |= crate::metadata::set_task_metadata(conn, workspace, task_id, input).await?;
    }
    for key in &update.remove_metadata {
        changed |= crate::metadata::remove_task_metadata(conn, workspace, task_id, key).await?;
    }
    Ok((changed, created_labels))
}

pub async fn update_task_field(
    conn: &mut SqliteConnection,
    workspace: &Workspace,
    task_id: &crate::ids::TaskId,
    field: &str,
    value: &str,
) -> Result<bool> {
    set_task_field(conn, workspace, task_id, field, value).await
}

pub async fn update_task_labels_in_workspace(
    conn: &mut SqliteConnection,
    workspace_id: &WorkspaceId,
    task_id: &crate::ids::TaskId,
    add_labels: &[String],
    remove_labels: &[String],
) -> Result<bool> {
    let workspace = crate::workspaces::workspace_for_id(conn, workspace_id).await?;
    crate::operations::route_recurrence_task_field(conn, &workspace, task_id, "labels", "").await?;
    let mut changed = false;
    for label in resolve_labels_in_workspace(conn, &workspace.id, add_labels).await? {
        let rows_affected = sqlx::query(
            "INSERT OR IGNORE INTO task_labels(workspace_id, task_id, label) VALUES (?, ?, ?)",
        )
        .bind(&workspace.id)
        .bind(task_id)
        .bind(&label)
        .execute(&mut *conn)
        .await?
        .rows_affected();
        if rows_affected > 0 {
            append_change(
                conn,
                ChangeEntity::Task,
                task_id,
                Some("labels"),
                op_type::LABEL_ADD,
                ChangePayload::workspace(&workspace).set("label", label),
            )
            .await?;
            changed = true;
        }
    }
    for label in resolve_labels_in_workspace(conn, &workspace.id, remove_labels).await? {
        let rows_affected = sqlx::query(
            "DELETE FROM task_labels WHERE workspace_id = ? AND task_id = ? AND label = ?",
        )
        .bind(&workspace.id)
        .bind(task_id)
        .bind(&label)
        .execute(&mut *conn)
        .await?
        .rows_affected();
        if rows_affected > 0 {
            append_change(
                conn,
                ChangeEntity::Task,
                task_id,
                Some("labels"),
                op_type::LABEL_REMOVE,
                ChangePayload::workspace(&workspace).set("label", label),
            )
            .await?;
            changed = true;
        }
    }
    if changed {
        info!(
            task_id = %task_id,
            added = add_labels.len(),
            removed = remove_labels.len(),
            "task labels changed"
        );
    }
    Ok(changed)
}

pub(super) async fn add_note_operation(
    conn: &mut SqliteConnection,
    workspace: &Workspace,
    task_id: &crate::ids::TaskId,
    body: String,
    tui_undo: bool,
) -> Result<NoteOutcome> {
    let note_id = new_id();
    let ts = now();
    let mut tx = begin_immediate(conn).await?;
    crate::operations::route_recurrence_task_field(&mut tx, workspace, task_id, "notes", "")
        .await?;
    let change_id = append_change(
        &mut tx,
        ChangeEntity::Task,
        task_id,
        Some("notes"),
        op_type::NOTE_ADD,
        ChangePayload::workspace(workspace)
            .set("note_id", &note_id)
            .set("body", &body)
            .set("created_at", &ts),
    )
    .await?;
    sqlx::query(
        "INSERT INTO notes(workspace_id, id, task_id, body, created_at, change_id) VALUES (?, ?, ?, ?, ?, ?)",
    )
    .bind(&workspace.id)
    .bind(&note_id)
    .bind(task_id)
    .bind(&body)
    .bind(&ts)
    .bind(&change_id)
    .execute(&mut *tx)
    .await?;
    sqlx::query("UPDATE tasks SET queue_activity_at = ? WHERE workspace_id = ? AND id = ?")
        .bind(&ts)
        .bind(&workspace.id)
        .bind(task_id)
        .execute(&mut *tx)
        .await?;
    if tui_undo {
        record_tui_undo(
            &mut tx,
            &workspace.id,
            &format!("note {note_id}"),
            UndoPayload {
                commands: vec![UndoCommand::DeleteCreatedNote {
                    task_id: task_id.clone(),
                    note_id: note_id.clone(),
                    note_add_change_id: change_id.clone(),
                }],
            },
        )
        .await?;
    }
    tx.commit().await?;
    info!(task_id = %task_id, note_id = %note_id, "note added");
    Ok(NoteOutcome {
        task_id: task_id.clone(),
        note_id,
        change_id,
    })
}

async fn edit_note_operation(
    conn: &mut SqliteConnection,
    workspace: &Workspace,
    task_id: &crate::ids::TaskId,
    note_id: &str,
    body: String,
    tui_undo: bool,
) -> Result<NoteEditOutcome> {
    let mut tx = begin_immediate(conn).await?;
    crate::operations::route_recurrence_task_field(&mut tx, workspace, task_id, "notes", "")
        .await?;
    let before = sqlx::query_scalar::<_, String>(
        "SELECT body FROM notes WHERE workspace_id = ? AND task_id = ? AND id = ?",
    )
    .bind(&workspace.id)
    .bind(task_id)
    .bind(note_id)
    .fetch_optional(&mut *tx)
    .await?;
    let found = before.is_some();
    let changed = before.as_ref().is_some_and(|before| before != &body);
    if changed {
        let edited_at = now();
        sqlx::query("UPDATE notes SET body = ? WHERE workspace_id = ? AND task_id = ? AND id = ?")
            .bind(&body)
            .bind(&workspace.id)
            .bind(task_id)
            .bind(note_id)
            .execute(&mut *tx)
            .await?;
        sqlx::query("UPDATE tasks SET queue_activity_at = ? WHERE workspace_id = ? AND id = ?")
            .bind(&edited_at)
            .bind(&workspace.id)
            .bind(task_id)
            .execute(&mut *tx)
            .await?;
        append_change(
            &mut tx,
            ChangeEntity::Task,
            task_id,
            Some("notes"),
            op_type::NOTE_EDIT,
            ChangePayload::workspace(workspace)
                .set("note_id", note_id)
                .set("body", &body)
                .set("edited_at", edited_at),
        )
        .await?;
        if tui_undo {
            record_tui_undo(
                &mut tx,
                &workspace.id,
                &format!("edit note {note_id}"),
                UndoPayload {
                    commands: vec![UndoCommand::SetNoteBody {
                        task_id: task_id.clone(),
                        note_id: note_id.to_string(),
                        before: before.expect("changed note has before body"),
                        after: body,
                    }],
                },
            )
            .await?;
        }
    }
    tx.commit().await?;
    if changed {
        info!(task_id = %task_id, note_id = %note_id, "note edited");
    }
    Ok(NoteEditOutcome {
        task_id: task_id.clone(),
        note_id: note_id.to_string(),
        found,
        changed,
    })
}

async fn delete_note_operation(
    conn: &mut SqliteConnection,
    workspace: &Workspace,
    task_id: &crate::ids::TaskId,
    note_id: &str,
    tui_undo: bool,
) -> Result<NoteDeleteOutcome> {
    let mut tx = begin_immediate(conn).await?;
    crate::operations::route_recurrence_task_field(&mut tx, workspace, task_id, "notes", "")
        .await?;
    let before = sqlx::query_as::<_, (String, String)>(
        "SELECT body, created_at FROM notes WHERE workspace_id = ? AND task_id = ? AND id = ?",
    )
    .bind(&workspace.id)
    .bind(task_id)
    .bind(note_id)
    .fetch_optional(&mut *tx)
    .await?;
    let deleted_at = now();
    let deleted =
        sqlx::query("DELETE FROM notes WHERE workspace_id = ? AND task_id = ? AND id = ?")
            .bind(&workspace.id)
            .bind(task_id)
            .bind(note_id)
            .execute(&mut *tx)
            .await?
            .rows_affected();
    if deleted > 0 {
        sqlx::query("UPDATE tasks SET queue_activity_at = ? WHERE workspace_id = ? AND id = ?")
            .bind(&deleted_at)
            .bind(&workspace.id)
            .bind(task_id)
            .execute(&mut *tx)
            .await?;
        append_change(
            &mut tx,
            ChangeEntity::Task,
            task_id,
            Some("notes"),
            op_type::NOTE_DELETE,
            ChangePayload::workspace(workspace)
                .set("note_id", note_id)
                .set(
                    "body",
                    &before.as_ref().expect("deleted note has before state").0,
                )
                .set("deleted_at", deleted_at),
        )
        .await?;
        if tui_undo {
            let (body, created_at) = before.expect("deleted note has before state");
            record_tui_undo(
                &mut tx,
                &workspace.id,
                &format!("delete note {note_id}"),
                UndoPayload {
                    commands: vec![UndoCommand::RestoreDeletedNote {
                        task_id: task_id.clone(),
                        note_id: note_id.to_string(),
                        body,
                        created_at,
                    }],
                },
            )
            .await?;
        }
    }
    tx.commit().await?;
    if deleted > 0 {
        info!(task_id = %task_id, note_id = %note_id, "note deleted");
    }
    Ok(NoteDeleteOutcome {
        task_id: task_id.clone(),
        note_id: note_id.to_string(),
        changed: deleted > 0,
    })
}