ai-dispatch 10.35.0

Multi-AI CLI team orchestrator
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
// Store write operations for tasks, workgroups, and events.
// Exports: Store mutation methods.
// Deps: rusqlite, chrono, crate::types.

use anyhow::Result;
use chrono::Local;
use rusqlite::{params, OptionalExtension};

use super::schema::row_to_memory;
use super::status_guard::status_guard_warn_only;
use super::Store;
use crate::types::*;

pub struct TaskCompletionUpdate<'a> {
    pub id: &'a str,
    pub status: TaskStatus,
    pub tokens: Option<i64>,
    pub duration_ms: i64,
    /// What the CLI reported it actually ran, or `None` when it reported
    /// nothing. Never the dispatched request — writing that here is what made
    /// `t-bd455a68` claim the `claude` CLI ran `gemini-3.6-flash-low`.
    pub observed_model: Option<&'a str>,
    /// The grade of `observed_model`. Moves with it: `None` whenever the model
    /// is `None`.
    pub attribution_source: Option<AttributionSource>,
    pub cost_usd: Option<f64>,
    pub exit_code: Option<i32>,
}

impl Store {
    pub fn insert_task(&self, task: &Task) -> Result<()> {
        let agent_value = if task.agent == AgentKind::Custom {
            task.custom_agent_name.as_deref().unwrap_or("custom")
        } else {
            task.agent.as_str()
        };
        self.db().execute(
            "INSERT INTO tasks (id, agent, prompt, resolved_prompt, status, parent_task_id, workgroup_id,
             caller_kind, caller_session_id, agent_session_id, repo_path, project_id, worktree_path, worktree_branch,
             final_head_sha, final_branch, start_sha, log_path, output_path, tokens, prompt_tokens, duration_ms, model, cost_usd, exit_code,
             created_at, completed_at, verify, verify_status, read_only, budget, custom_agent_name,
             category, pending_reason, audit_verdict, audit_report_path, delivery_assessment, observed_model, attribution_source, effective_dir)
             VALUES (?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)",
            params![
                task.id.as_str(),
                agent_value,
                task.prompt,
                task.resolved_prompt,
                task.status.as_str(),
                task.parent_task_id,
                task.workgroup_id,
                task.caller_kind,
                task.caller_session_id,
                task.agent_session_id,
                task.repo_path,
                task.project_id,
                task.worktree_path,
                task.worktree_branch,
                task.final_head_sha,
                task.final_branch,
                task.start_sha,
                task.log_path,
                task.output_path,
                task.tokens,
                task.prompt_tokens,
                task.duration_ms,
                task.requested_model,
                task.cost_usd,
                task.exit_code,
                task.created_at.to_rfc3339(),
                task.completed_at.map(|t| t.to_rfc3339()),
                task.verify,
                task.verify_status.as_str(),
                task.read_only,
                task.budget,
                task.custom_agent_name,
                task.category,
                task.pending_reason,
                task.audit_verdict,
                task.audit_report_path,
                task.delivery_assessment.map(|value| value.as_str()),
                task.observed_model,
                task.attribution_source.map(|value| value.as_str()),
                task.effective_dir,
            ],
        )?;
        Ok(())
    }

    /// Insert a waiting task placeholder with enough config for faithful retry.
    pub fn insert_waiting_task(
        &self,
        id: &str,
        agent: &str,
        prompt: &str,
        resolved_prompt: Option<&str>,
        workgroup_id: Option<&str>,
        dir: Option<&str>,
        worktree_branch: Option<&str>,
        model: Option<&str>,
        verify: Option<&str>,
        read_only: bool,
        budget: bool,
    ) -> Result<()> {
        self.db().execute(
            "INSERT INTO tasks (
             id, agent, prompt, resolved_prompt, status, workgroup_id, repo_path,
             worktree_branch, model, created_at, verify, verify_status, read_only, budget
             ) VALUES (?1, ?2, ?3, ?4, 'waiting', ?5, ?6, ?7, ?8, ?9, ?10, 'skipped', ?11, ?12)",
            params![
                id,
                agent,
                prompt,
                resolved_prompt,
                workgroup_id,
                dir,
                worktree_branch,
                model,
                Local::now().to_rfc3339(),
                verify,
                read_only,
                budget,
            ],
        )?;
        Ok(())
    }

    /// Replace a waiting task's row with full task data (called when dispatch begins).
    pub fn replace_waiting_task(&self, task: &Task) -> Result<()> {
        let agent_value = if task.agent == AgentKind::Custom {
            task.custom_agent_name.as_deref().unwrap_or("custom")
        } else {
            task.agent.as_str()
        };
        self.db().execute(
            "UPDATE tasks SET agent=?2, prompt=?3, resolved_prompt=?4, status=?5,
             parent_task_id=?6, workgroup_id=?7, caller_kind=?8, caller_session_id=?9,
             agent_session_id=?10, repo_path=?11, project_id=?12, worktree_path=?13, worktree_branch=?14,
             final_head_sha=?15, final_branch=?16, start_sha=?17, log_path=?18, output_path=?19, model=?20, verify=?21,
             verify_status=?22, read_only=?23, budget=?24, custom_agent_name=?25,
             category=?26, pending_reason=?27, audit_verdict=?28, audit_report_path=?29,
             delivery_assessment=?30, effective_dir=?31
             WHERE id=?1",
            params![
                task.id.as_str(), agent_value, task.prompt, task.resolved_prompt,
                task.status.as_str(), task.parent_task_id, task.workgroup_id,
                task.caller_kind, task.caller_session_id, task.agent_session_id,
                task.repo_path, task.project_id, task.worktree_path, task.worktree_branch,
                task.final_head_sha, task.final_branch,
                task.start_sha, task.log_path, task.output_path, task.requested_model,
                task.verify, task.verify_status.as_str(), task.read_only,
                task.budget, task.custom_agent_name, task.category,
                task.pending_reason,
                task.audit_verdict,
                task.audit_report_path,
                task.delivery_assessment.map(|value| value.as_str()),
                task.effective_dir,
            ],
        )?;
        Ok(())
    }

    pub fn create_workgroup(
        &self,
        name: &str,
        shared_context: &str,
        created_by: Option<&str>,
        custom_id: Option<&str>,
    ) -> Result<Workgroup> {
        let now = Local::now();
        let workgroup = Workgroup {
            id: custom_id
                .map(|s| WorkgroupId(s.to_string()))
                .unwrap_or_else(WorkgroupId::generate),
            name: name.to_string(),
            shared_context: shared_context.to_string(),
            created_by: created_by.map(str::to_string),
            created_at: now,
            updated_at: now,
        };
        self.db().execute(
            "INSERT INTO workgroups (id, name, shared_context, created_by, created_at, updated_at)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
            params![
                workgroup.id.as_str(),
                workgroup.name,
                workgroup.shared_context,
                workgroup.created_by,
                workgroup.created_at.to_rfc3339(),
                workgroup.updated_at.to_rfc3339(),
            ],
        )?;
        let workspace_dir = crate::paths::workspace_dir(workgroup.id.as_str())?;
        if let Err(e) = std::fs::create_dir_all(&workspace_dir) {
            // Rollback DB row to avoid orphaned workgroup without workspace
            let _ = self.db().execute(
                "DELETE FROM workgroups WHERE id = ?1",
                params![workgroup.id.as_str()],
            );
            return Err(e.into());
        }
        Ok(workgroup)
    }

    pub fn update_task_status(&self, id: &str, status: TaskStatus) -> Result<bool> {
        if !self.guard_status_transition(id, status, false)? {
            return Ok(false);
        }
        let rows = self.db().execute(
            "UPDATE tasks SET status = ?1 WHERE id = ?2",
            params![status.as_str(), id],
        )?;
        Ok(rows > 0)
    }

    pub(crate) fn rescue_task_to_done(&self, id: &str) -> Result<bool> {
        if !self.guard_status_transition(id, TaskStatus::Done, true)? {
            return Ok(false);
        }
        let rows = self.db().execute(
            "UPDATE tasks SET status = 'done' WHERE id = ?1 AND status = 'failed'",
            params![id],
        )?;
        Ok(rows > 0)
    }

    /// Set status to Failed only if currently Running or Waiting.
    /// Prevents zombie cleanup from clobbering a real completion status.
    pub fn fail_if_running(&self, id: &str) -> Result<bool> {
        if !self.guard_current_status(
            id,
            &[TaskStatus::Running, TaskStatus::Waiting],
            TaskStatus::Failed,
        )? {
            return Ok(false);
        }
        let rows = self.db().execute(
            "UPDATE tasks SET status = 'failed' WHERE id = ?1
             AND status IN ('running', 'waiting')",
            params![id],
        )?;
        Ok(rows > 0)
    }

    pub fn fail_pending_with_reason(
        &self,
        id: &str,
        pending_reason: PendingReason,
    ) -> Result<bool> {
        if !self.guard_current_status(id, &[TaskStatus::Pending], TaskStatus::Failed)? {
            return Ok(false);
        }
        let rows = self.db().execute(
            "UPDATE tasks SET status = 'failed', pending_reason = ?2
             WHERE id = ?1 AND status = 'pending'",
            params![id, pending_reason.as_str()],
        )?;
        Ok(rows > 0)
    }

    pub fn fail_waiting_with_reason(&self, id: &str, detail: &str) -> Result<bool> {
        if !self.guard_current_status(id, &[TaskStatus::Waiting], TaskStatus::Failed)? {
            return Ok(false);
        }
        let now = Local::now();
        let rows = self.db().execute(
            "UPDATE tasks SET status = 'failed', completed_at = ?2, pending_reason = ?3
             WHERE id = ?1 AND status = 'waiting'",
            params![id, now.to_rfc3339(), PendingReason::WaitTimeout.as_str()],
        )?;
        if rows == 0 {
            return Ok(false);
        }
        self.insert_event(&TaskEvent {
            task_id: TaskId(id.to_string()),
            timestamp: now,
            event_kind: EventKind::Error,
            detail: detail.to_string(),
            metadata: Some(serde_json::json!({ "failure_kind": "wait_timeout" })),
        })?;
        Ok(true)
    }

    pub fn update_resolved_prompt(&self, id: &str, resolved_prompt: &str) -> Result<()> {
        self.db().execute(
            "UPDATE tasks SET resolved_prompt = ?1 WHERE id = ?2",
            params![resolved_prompt, id],
        )?;
        Ok(())
    }

    pub fn update_task_dispatch_args(&self, id: &str, dispatch_args: &str) -> Result<()> {
        self.db().execute(
            "UPDATE tasks SET dispatch_args = ?1 WHERE id = ?2",
            params![dispatch_args, id],
        )?;
        Ok(())
    }

    pub fn update_prompt_tokens(&self, id: &str, tokens: i64) -> Result<()> {
        self.db().execute(
            "UPDATE tasks SET prompt_tokens = ?1 WHERE id = ?2",
            params![tokens, id],
        )?;
        Ok(())
    }

    pub(crate) fn update_task_worktree(
        &self,
        id: &str,
        repo_path: Option<&str>,
        worktree_path: Option<&str>,
        worktree_branch: Option<&str>,
        effective_dir: Option<&str>,
    ) -> Result<()> {
        self.db().execute(
            "UPDATE tasks SET repo_path = ?1, worktree_path = ?2, worktree_branch = ?3, effective_dir = ?4 WHERE id = ?5",
            params![repo_path, worktree_path, worktree_branch, effective_dir, id],
        )?;
        Ok(())
    }

    pub(crate) fn update_task_project_id(&self, id: &str, project_id: Option<&str>) -> Result<()> {
        self.db().execute(
            "UPDATE tasks SET project_id = ?1 WHERE id = ?2",
            params![project_id, id],
        )?;
        Ok(())
    }

    pub fn update_start_sha(&self, id: &str, start_sha: &str) -> Result<()> {
        self.db().execute(
            "UPDATE tasks SET start_sha = ?1 WHERE id = ?2",
            params![start_sha, id],
        )?;
        Ok(())
    }

    pub(crate) fn update_task_final_state(
        &self,
        id: &str,
        final_head_sha: Option<&str>,
        final_branch: Option<&str>,
    ) -> Result<()> {
        self.db().execute(
            "UPDATE tasks SET final_head_sha = ?1, final_branch = ?2 WHERE id = ?3",
            params![final_head_sha, final_branch, id],
        )?;
        Ok(())
    }

    pub fn update_output_path(&self, task_id: &str, output_path: &str) -> Result<()> {
        self.db().execute(
            "UPDATE tasks SET output_path = ?1 WHERE id = ?2",
            params![output_path, task_id],
        )?;
        Ok(())
    }

    pub fn update_agent_session_id(&self, id: &str, session_id: &str) -> Result<()> {
        self.db().execute(
            "UPDATE tasks SET agent_session_id = ?1 WHERE id = ?2",
            params![session_id, id],
        )?;
        Ok(())
    }

    pub fn update_task_completion(&self, payload: TaskCompletionUpdate<'_>) -> Result<bool> {
        if !self.guard_completion_transition(payload.id, payload.status)? {
            return Ok(false);
        }
        let now = Local::now().to_rfc3339();
        let rows = self.db().execute(
            // COALESCE, not assignment: a second completion write that learned
            // nothing must not erase a model the first one observed. The
            // requested model in `model` is never touched here — a completion
            // has no business rewriting what was asked for.
            "UPDATE tasks SET status = ?1, tokens = ?2, duration_ms = ?3, completed_at = ?4,
             observed_model = COALESCE(?5, observed_model), attribution_source = COALESCE(?9, attribution_source), cost_usd = ?6, exit_code = ?7 WHERE id = ?8
             AND status NOT IN ('failed', 'stopped')",
            params![
                payload.status.as_str(),
                payload.tokens,
                payload.duration_ms,
                now,
                payload.observed_model,
                payload.cost_usd,
                payload.exit_code,
                payload.id,
                payload.attribution_source.map(|value| value.as_str()),
            ],
        )?;
        Ok(rows > 0)
    }

    /// Atomically update task completion AND insert the completion event.
    /// Prevents inconsistent state if process crashes between the two writes.
    pub fn complete_task_atomic(
        &self,
        payload: TaskCompletionUpdate<'_>,
        event: &TaskEvent,
    ) -> Result<bool> {
        if !self.guard_completion_transition(payload.id, payload.status)? {
            return Ok(false);
        }
        let conn = self.db();
        let tx = conn.unchecked_transaction()?;
        let now = Local::now().to_rfc3339();
        let rows = tx.execute(
            // COALESCE, not assignment: a second completion write that learned
            // nothing must not erase a model the first one observed. The
            // requested model in `model` is never touched here — a completion
            // has no business rewriting what was asked for.
            "UPDATE tasks SET status = ?1, tokens = ?2, duration_ms = ?3, completed_at = ?4,
             observed_model = COALESCE(?5, observed_model), attribution_source = COALESCE(?9, attribution_source), cost_usd = ?6, exit_code = ?7 WHERE id = ?8
             AND status NOT IN ('failed', 'stopped')",
            params![
                payload.status.as_str(),
                payload.tokens,
                payload.duration_ms,
                now,
                payload.observed_model,
                payload.cost_usd,
                payload.exit_code,
                payload.id,
                payload.attribution_source.map(|value| value.as_str()),
            ],
        )?;
        let metadata_str = event.metadata.as_ref().map(|m| m.to_string());
        tx.execute(
            "INSERT INTO events (task_id, timestamp, event_type, detail, metadata)
             VALUES (?1, ?2, ?3, ?4, ?5)",
            params![
                event.task_id.as_str(),
                event.timestamp.to_rfc3339(),
                event.event_kind.as_str(),
                event.detail,
                metadata_str,
            ],
        )?;
        tx.commit()?;
        drop(conn);
        Ok(rows > 0)
    }

    fn guard_completion_transition(&self, id: &str, next: TaskStatus) -> Result<bool> {
        let Some(current) = self.current_task_status(id)? else {
            return Ok(false);
        };
        if matches!(current, TaskStatus::Failed | TaskStatus::Stopped) {
            return Ok(false);
        }
        self.guard_known_status_transition(id, current, next, false)
    }

    pub(crate) fn guard_current_status(
        &self,
        id: &str,
        expected: &[TaskStatus],
        next: TaskStatus,
    ) -> Result<bool> {
        let Some(current) = self.current_task_status(id)? else {
            return Ok(false);
        };
        if !expected.contains(&current) {
            return Ok(false);
        }
        self.guard_known_status_transition(id, current, next, false)
    }

    fn guard_status_transition(
        &self,
        id: &str,
        next: TaskStatus,
        allow_rescue: bool,
    ) -> Result<bool> {
        let Some(current) = self.current_task_status(id)? else {
            return Ok(false);
        };
        self.guard_known_status_transition(id, current, next, allow_rescue)
    }

    fn guard_known_status_transition(
        &self,
        id: &str,
        current: TaskStatus,
        next: TaskStatus,
        allow_rescue: bool,
    ) -> Result<bool> {
        if current.can_transition_to(next) || (allow_rescue && current.can_rescue_to_done(next)) {
            return Ok(true);
        }
        if status_guard_warn_only() {
            aid_warn!(
                "[aid] Allowing illegal status transition for {id} due to AID_STATUS_GUARD=warn: {} -> {}",
                current.as_str(),
                next.as_str()
            );
            return Ok(true);
        }
        aid_warn!(
            "[aid] Rejected illegal status transition for {id}: {} -> {}",
            current.as_str(),
            next.as_str()
        );
        Ok(false)
    }

    fn current_task_status(&self, id: &str) -> Result<Option<TaskStatus>> {
        let status = self
            .db()
            .query_row(
                "SELECT status FROM tasks WHERE id = ?1",
                params![id],
                |row| row.get::<_, String>(0),
            )
            .optional()?;
        Ok(status.and_then(|value| TaskStatus::parse_str(&value)))
    }

    pub fn save_completion_summary(&self, task_id: &str, summary_json: &str) -> Result<()> {
        self.db().execute(
            "UPDATE tasks SET completion_summary = ?1 WHERE id = ?2",
            params![summary_json, task_id],
        )?;
        Ok(())
    }

    pub fn update_task_audit(
        &self,
        task_id: &str,
        verdict: Option<&str>,
        report_path: Option<&str>,
    ) -> Result<()> {
        self.db().execute(
            "UPDATE tasks SET audit_verdict = ?1, audit_report_path = ?2 WHERE id = ?3",
            params![verdict, report_path, task_id],
        )?;
        Ok(())
    }

    pub fn save_peer_review(
        &self,
        task_id: &str,
        reviewer: &str,
        score: u8,
        feedback: &str,
    ) -> Result<()> {
        let review_json = serde_json::json!({
            "reviewer": reviewer,
            "score": score,
            "feedback": feedback,
        })
        .to_string();
        self.db().execute(
            "UPDATE tasks SET peer_review = ?1 WHERE id = ?2",
            params![review_json, task_id],
        )?;
        Ok(())
    }

    pub fn insert_event(&self, event: &TaskEvent) -> Result<()> {
        let metadata_str = event.metadata.as_ref().map(|m| m.to_string());
        self.db().execute(
            "INSERT INTO events (task_id, timestamp, event_type, detail, metadata)
             VALUES (?1, ?2, ?3, ?4, ?5)",
            params![
                event.task_id.as_str(),
                event.timestamp.to_rfc3339(),
                event.event_kind.as_str(),
                event.detail,
                metadata_str,
            ],
        )?;
        Ok(())
    }

    #[allow(clippy::too_many_arguments)]
    pub fn insert_finding(
        &self,
        workgroup_id: &str,
        content: &str,
        source_task_id: Option<&str>,
        severity: Option<&str>,
        title: Option<&str>,
        file: Option<&str>,
        lines: Option<&str>,
        category: Option<&str>,
        confidence: Option<&str>,
    ) -> Result<()> {
        let now = Local::now().to_rfc3339();
        self.db().execute(
            "INSERT INTO findings (workgroup_id, content, source_task_id, severity, title, file, lines, category, confidence, created_at)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
            params![
                workgroup_id,
                content,
                source_task_id,
                severity,
                title,
                file,
                lines,
                category,
                confidence,
                now,
            ],
        )?;
        Ok(())
    }

    pub fn insert_memory(&self, memory: &Memory) -> Result<()> {
        self.db().execute(
            "INSERT OR IGNORE INTO memories (id, memory_type, content, source_task_id, agent,
              project_path, content_hash, created_at, expires_at, supersedes, version,
              inject_count, last_injected_at, success_count, tier)
              VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)",
            params![
                memory.id.as_str(),
                memory.memory_type.as_str(),
                memory.content,
                memory.source_task_id,
                memory.agent,
                memory.project_path,
                memory.content_hash,
                memory.created_at.to_rfc3339(),
                memory.expires_at.map(|dt| dt.to_rfc3339()),
                memory.supersedes.as_ref().map(|id| id.as_str()),
                memory.version,
                memory.inject_count,
                memory.last_injected_at.map(|dt| dt.to_rfc3339()),
                memory.success_count,
                memory.tier.as_str(),
            ],
        )?;
        Ok(())
    }

    pub fn update_memory(&self, id: &str, content: &str) -> Result<bool> {
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        std::hash::Hash::hash(content, &mut hasher);
        let hash = format!("{:016x}", std::hash::Hasher::finish(&hasher));
        let now = chrono::Local::now().to_rfc3339();
        let conn = self.db();
        let existing = match conn.query_row(
            "SELECT id, memory_type, content, source_task_id, agent, project_path, content_hash,
             created_at, expires_at, supersedes, version, inject_count, last_injected_at, success_count, tier
             FROM memories WHERE id = ?1",
            params![id],
            row_to_memory,
        ) {
            Ok(row) => row?,
            Err(rusqlite::Error::QueryReturnedNoRows) => return Ok(false),
            Err(err) => return Err(err.into()),
        };
        let Memory {
            id: old_id,
            memory_type,
            tier,
            source_task_id,
            agent,
            project_path,
            expires_at,
            version,
            inject_count,
            last_injected_at,
            success_count,
            ..
        } = existing;
        let supersedes_id = old_id.as_str().to_string();
        let expires_at_str = expires_at.map(|dt| dt.to_rfc3339());
        let last_injected_at_str = last_injected_at.map(|dt| dt.to_rfc3339());
        let new_id = MemoryId::generate();
        conn.execute(
            "INSERT INTO memories (id, memory_type, content, source_task_id, agent, project_path,
             content_hash, created_at, expires_at, supersedes, version, inject_count, last_injected_at,
             success_count, tier)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)",
            params![
                new_id.as_str(),
                memory_type.as_str(),
                content,
                source_task_id,
                agent,
                project_path,
                hash,
                now,
                expires_at_str,
                supersedes_id,
                version + 1,
                inject_count,
                last_injected_at_str,
                success_count,
                tier.as_str(),
            ],
        )?;
        Ok(true)
    }

    pub fn increment_memory_inject(&self, id: &str) -> Result<bool> {
        let now = Local::now().to_rfc3339();
        let rows = self.db().execute(
            "UPDATE memories SET inject_count = inject_count + 1, last_injected_at = ?1 WHERE id = ?2",
            params![now, id],
        )?;
        Ok(rows > 0)
    }

    pub fn increment_memory_success(&self, id: &str) -> Result<bool> {
        let rows = self.db().execute(
            "UPDATE memories SET success_count = success_count + 1 WHERE id = ?1",
            params![id],
        )?;
        Ok(rows > 0)
    }

    pub fn delete_memory(&self, id: &str) -> Result<()> {
        self.db()
            .execute("DELETE FROM memories WHERE id = ?1", params![id])?;
        Ok(())
    }

    pub fn update_verify_status(&self, id: &str, verify_status: VerifyStatus) -> Result<()> {
        self.db().execute(
            "UPDATE tasks SET verify_status = ?1 WHERE id = ?2",
            params![verify_status.as_str(), id],
        )?;
        Ok(())
    }

    pub fn update_delivery_assessment(
        &self,
        id: &str,
        delivery_assessment: Option<DeliveryAssessment>,
    ) -> Result<()> {
        self.db().execute(
            "UPDATE tasks SET delivery_assessment = ?1 WHERE id = ?2",
            params![delivery_assessment.map(|value| value.as_str()), id],
        )?;
        Ok(())
    }

    pub fn update_principal_merge_override(&self, id: &str, reason: &str) -> Result<()> {
        self.db().execute(
            "UPDATE tasks SET principal_merge_override = ?1 WHERE id = ?2",
            params![reason, id],
        )?;
        Ok(())
    }

    pub fn get_principal_merge_override(&self, id: &str) -> Result<Option<String>> {
        let reason = self
            .db()
            .query_row(
                "SELECT principal_merge_override FROM tasks WHERE id = ?1",
                params![id],
                |row| row.get::<_, Option<String>>(0),
            )
            .optional()?
            .flatten();
        Ok(reason)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::store::Store;

    fn insert_task_status(store: &Store, task_id: &str, status: TaskStatus) {
        let conn = store.db();
        conn.execute(
            "INSERT INTO tasks (id, agent, prompt, status, created_at)
             VALUES (?1, 'codex', 'test prompt', ?2, '2026-03-18T00:00:00Z')",
            params![task_id, status.as_str()],
        )
        .unwrap();
    }

    #[test]
    fn complete_task_atomic_writes_both_task_and_event() {
        let store = Store::open_memory().unwrap();
        insert_task_status(&store, "t-atomic", TaskStatus::Running);

        let event = TaskEvent {
            task_id: TaskId("t-atomic".to_string()),
            timestamp: Local::now(),
            event_kind: EventKind::Completion,
            detail: "completed atomically".to_string(),
            metadata: None,
        };
        store
            .complete_task_atomic(
                TaskCompletionUpdate {
                    id: "t-atomic",
                    status: TaskStatus::Done,
                    tokens: Some(1234),
                    duration_ms: 5000,
                    observed_model: Some("test-model"),
                    attribution_source: None,
                    cost_usd: Some(0.05),
                    exit_code: Some(0),
                },
                &event,
            )
            .unwrap();

        let task = store.get_task("t-atomic").unwrap().unwrap();
        assert_eq!(task.status, TaskStatus::Done);
        assert_eq!(task.tokens, Some(1234));
        assert_eq!(task.duration_ms, Some(5000));

        let events = store.get_events("t-atomic").unwrap();
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_kind, EventKind::Completion);
        assert_eq!(events[0].detail, "completed atomically");
    }

    #[test]
    fn complete_task_atomic_does_not_override_failed_status() {
        let store = Store::open_memory().unwrap();
        insert_task_status(&store, "t-atomic-failed", TaskStatus::Failed);

        let event = TaskEvent {
            task_id: TaskId("t-atomic-failed".to_string()),
            timestamp: Local::now(),
            event_kind: EventKind::Completion,
            detail: "completed after interrupt".to_string(),
            metadata: None,
        };
        store
            .complete_task_atomic(
                TaskCompletionUpdate {
                    id: "t-atomic-failed",
                    status: TaskStatus::Done,
                    tokens: Some(1234),
                    duration_ms: 5000,
                    observed_model: Some("test-model"),
                    attribution_source: None,
                    cost_usd: Some(0.05),
                    exit_code: Some(0),
                },
                &event,
            )
            .unwrap();

        let task = store.get_task("t-atomic-failed").unwrap().unwrap();
        assert_eq!(task.status, TaskStatus::Failed);
        assert_eq!(task.tokens, None);
        assert_eq!(task.completed_at, None);
    }

    #[test]
    fn update_task_status_rejects_illegal_failed_to_done() {
        let store = Store::open_memory().unwrap();
        insert_task_status(&store, "t-guard-failed", TaskStatus::Failed);

        let changed = store
            .update_task_status("t-guard-failed", TaskStatus::Done)
            .unwrap();

        let task = store.get_task("t-guard-failed").unwrap().unwrap();
        assert!(!changed);
        assert_eq!(task.status, TaskStatus::Failed);
    }

    #[test]
    fn rescue_task_to_done_allows_named_failed_to_done_exception() {
        let store = Store::open_memory().unwrap();
        insert_task_status(&store, "t-rescue", TaskStatus::Failed);

        let changed = store.rescue_task_to_done("t-rescue").unwrap();

        let task = store.get_task("t-rescue").unwrap().unwrap();
        assert!(changed);
        assert_eq!(task.status, TaskStatus::Done);
    }

    #[test]
    fn complete_task_atomic_rejects_illegal_transition_without_event() {
        let store = Store::open_memory().unwrap();
        insert_task_status(&store, "t-atomic-merged", TaskStatus::Merged);
        let event = TaskEvent {
            task_id: TaskId("t-atomic-merged".to_string()),
            timestamp: Local::now(),
            event_kind: EventKind::Error,
            detail: "late failure".to_string(),
            metadata: None,
        };

        let changed = store
            .complete_task_atomic(
                TaskCompletionUpdate {
                    id: "t-atomic-merged",
                    status: TaskStatus::Failed,
                    tokens: None,
                    duration_ms: 5000,
                    observed_model: None,
                    attribution_source: None,
                    cost_usd: None,
                    exit_code: Some(1),
                },
                &event,
            )
            .unwrap();

        assert!(!changed);
        assert_eq!(store.get_events("t-atomic-merged").unwrap().len(), 0);
    }

    #[test]
    fn update_principal_merge_override_persists_reason() {
        let store = Store::open_memory().unwrap();
        insert_task_status(&store, "t-override", TaskStatus::Failed);

        store
            .update_principal_merge_override("t-override", "verification command failed")
            .unwrap();

        let loaded = store.get_task("t-override").unwrap().unwrap();
        assert_eq!(loaded.status, TaskStatus::Failed);
        assert_eq!(
            store.get_principal_merge_override("t-override").unwrap(),
            Some("verification command failed".to_string())
        );
    }

    #[test]
    fn get_principal_merge_override_returns_none_when_not_set() {
        let store = Store::open_memory().unwrap();
        insert_task_status(&store, "t-none", TaskStatus::Failed);

        assert_eq!(store.get_principal_merge_override("t-none").unwrap(), None);
    }
}