grite-daemon 0.5.3

Background daemon for grite providing concurrent access and performance
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
//! Worker module - handles commands for a single repo.
//!
//! Each worker owns exclusive access to the shared sled database for its
//! repository. Commands are processed concurrently using tokio tasks, with
//! sled's internal MVCC handling concurrent access safely.
//!
//! Actor ID is supplied per-command rather than being fixed at worker
//! creation time, reflecting the shared-sled model where actor identity
//! is authorship metadata rather than a storage partition.

use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;

use libgrite_core::config::repo_sled_path;
use libgrite_core::store::IssueFilter;
use libgrite_core::types::ids::{hex_to_id, ActorId};
use libgrite_core::{GriteError, GriteStore, LockedStore};
use libgrite_ipc::{DaemonLock, IpcCommand, IpcResponse, Notification};
use tokio::sync::mpsc;
use tracing::{debug, error, info, warn};

use crate::error::DaemonError;
use crate::state::{AtomicWorkerState, WorkerState};

/// Message sent to a worker
pub enum WorkerMessage {
    /// Execute a command
    Command {
        request_id: String,
        /// Actor ID (hex) for event authorship
        actor_id: String,
        command: IpcCommand,
        response_tx: tokio::sync::oneshot::Sender<IpcResponse>,
    },
    /// Refresh the heartbeat
    Heartbeat,
    /// Shutdown the worker
    Shutdown,
}

/// Worker state for a single repository
pub struct Worker {
    /// Repository root path
    pub repo_root: PathBuf,
    /// Git directory (.git or worktree commondir)
    git_dir: PathBuf,
    /// Grite data directory (.git/grite) — used for daemon lock
    grite_dir: PathBuf,
    /// Sled store path
    sled_path: PathBuf,
    /// Sled store with filesystem lock (shared for concurrent access)
    store: Arc<LockedStore>,
    /// Channel for receiving messages
    rx: mpsc::Receiver<WorkerMessage>,
    /// Notification sender
    notify_tx: mpsc::Sender<Notification>,
    /// Host ID for this daemon
    host_id: String,
    /// IPC endpoint
    ipc_endpoint: String,
    /// Owner actor ID used when acquiring the daemon lock
    owner_actor_id: String,
    /// Current lifecycle state
    pub state: Arc<AtomicWorkerState>,
}

impl Worker {
    /// Create a new worker
    pub fn new(
        repo_root: PathBuf,
        owner_actor_id: String,
        rx: mpsc::Receiver<WorkerMessage>,
        notify_tx: mpsc::Sender<Notification>,
        host_id: String,
        ipc_endpoint: String,
    ) -> Result<Self, DaemonError> {
        let git_dir = repo_root.join(".git");
        let grite_dir = git_dir.join("grite");
        let sled_path = repo_sled_path(&git_dir);

        // Open store with filesystem lock (blocking with timeout)
        // This ensures exclusive process-level access to the sled database
        let state = Arc::new(AtomicWorkerState::new(WorkerState::Initializing));

        let store = Arc::new(GriteStore::open_locked_blocking(
            &sled_path,
            Duration::from_secs(5),
        )?);

        state.store(WorkerState::Idle, Ordering::SeqCst);

        Ok(Self {
            repo_root,
            git_dir,
            grite_dir,
            sled_path,
            store,
            rx,
            notify_tx,
            host_id,
            ipc_endpoint,
            owner_actor_id,
            state,
        })
    }

    /// Acquire the daemon lock
    pub fn acquire_lock(&self) -> Result<DaemonLock, DaemonError> {
        DaemonLock::acquire(
            &self.grite_dir,
            self.repo_root.to_string_lossy().to_string(),
            self.owner_actor_id.clone(),
            self.host_id.clone(),
            self.ipc_endpoint.clone(),
        )
        .map_err(|e| DaemonError::LockFailed(e.to_string()))
    }

    /// Refresh the daemon lock heartbeat
    pub fn refresh_lock(&self) -> Result<(), DaemonError> {
        if let Ok(Some(mut lock)) = DaemonLock::read(&self.grite_dir) {
            if lock.is_owned_by_current_process() {
                lock.refresh();
                lock.write(&self.grite_dir)?;
            }
        }
        Ok(())
    }

    /// Run the worker event loop
    pub async fn run(mut self) {
        info!(
            repo = %self.repo_root.display(),
            "Worker started"
        );

        // Acquire lock
        match self.acquire_lock() {
            Ok(_lock) => {
                debug!("Daemon lock acquired");
            }
            Err(e) => {
                error!("Failed to acquire lock: {}", e);
                return;
            }
        }

        // Notify worker started
        let _ = self
            .notify_tx
            .send(Notification::WorkerStarted {
                repo_root: self.repo_root.to_string_lossy().to_string(),
                actor_id: self.owner_actor_id.clone(),
            })
            .await;

        // Track in-flight commands so we can wait for them on shutdown
        let in_flight = Arc::new(AtomicUsize::new(0));
        let worker_state = Arc::clone(&self.state);

        // Event loop - commands are spawned as concurrent tasks
        while let Some(msg) = self.rx.recv().await {
            match msg {
                WorkerMessage::Command {
                    request_id,
                    actor_id,
                    command,
                    response_tx,
                } => {
                    // Parse actor ID bytes for event authorship
                    let actor_id_bytes: ActorId = match hex_to_id(&actor_id) {
                        Ok(b) => b,
                        Err(e) => {
                            let resp = IpcResponse::error(
                                request_id,
                                "invalid_actor".to_string(),
                                format!("Invalid actor ID: {}", e),
                            );
                            let _ = response_tx.send(resp);
                            continue;
                        }
                    };

                    // Clone data needed for the spawned task
                    let store = Arc::clone(&self.store);
                    let sled_path = self.sled_path.clone();
                    let git_dir = self.git_dir.clone();
                    let in_flight = Arc::clone(&in_flight);
                    let state = Arc::clone(&worker_state);

                    let was_idle = in_flight.load(Ordering::SeqCst) == 0;
                    in_flight.fetch_add(1, Ordering::SeqCst);
                    if was_idle {
                        state.store(WorkerState::Busy, Ordering::SeqCst);
                    }

                    // Run on the blocking thread pool — sled and git2 do
                    // synchronous I/O that must not starve the async runtime.
                    tokio::task::spawn_blocking(move || {
                        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                            execute_command(
                                &store,
                                actor_id_bytes,
                                &sled_path,
                                &git_dir,
                                &request_id,
                                &command,
                            )
                        }));
                        let response = match result {
                            Ok(resp) => resp,
                            Err(_) => IpcResponse::error(
                                request_id,
                                "panic".to_string(),
                                "Command handler panicked".to_string(),
                            ),
                        };
                        let _ = response_tx.send(response);
                        let remaining = in_flight.fetch_sub(1, Ordering::SeqCst);
                        if remaining == 1 {
                            state.store(WorkerState::Idle, Ordering::SeqCst);
                        }
                    });
                }
                WorkerMessage::Heartbeat => {
                    if let Err(e) = self.refresh_lock() {
                        warn!("Failed to refresh lock: {}", e);
                    }
                }
                WorkerMessage::Shutdown => {
                    worker_state.store(WorkerState::ShuttingDown, Ordering::SeqCst);
                    info!("Worker shutdown requested");
                    break;
                }
            }
        }

        // Wait for in-flight commands to complete (with timeout)
        let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
        while in_flight.load(Ordering::SeqCst) > 0 {
            if tokio::time::Instant::now() >= deadline {
                warn!(
                    "Timed out waiting for {} in-flight commands",
                    in_flight.load(Ordering::SeqCst)
                );
                break;
            }
            tokio::time::sleep(Duration::from_millis(50)).await;
        }

        // Cleanup
        self.shutdown();
        self.state.store(WorkerState::Stopped, Ordering::SeqCst);
    }

    /// Shutdown cleanup
    fn shutdown(&self) {
        // Release lock
        if let Err(e) = DaemonLock::release(&self.grite_dir) {
            warn!("Failed to release lock: {}", e);
        }

        // Flush store
        if let Err(e) = self.store.flush() {
            warn!("Failed to flush store: {}", e);
        }

        info!(
            repo = %self.repo_root.display(),
            "Worker stopped"
        );
    }
}

/// Execute a command with the given context.
///
/// This is a standalone function to enable concurrent execution via tokio::spawn.
fn execute_command(
    store: &LockedStore,
    actor_id_bytes: ActorId,
    sled_path: &Path,
    git_dir: &Path,
    request_id: &str,
    command: &IpcCommand,
) -> IpcResponse {
    let result = execute_command_inner(store, actor_id_bytes, sled_path, git_dir, command);

    match result {
        Ok(data) => IpcResponse::success(request_id.to_string(), data),
        Err(e) => {
            let (code, message) = error_to_code_message(&e);
            IpcResponse::error(request_id.to_string(), code, message)
        }
    }
}

/// Inner command execution logic
fn execute_command_inner(
    store: &LockedStore,
    actor_id_bytes: ActorId,
    sled_path: &Path,
    git_dir: &Path,
    command: &IpcCommand,
) -> Result<Option<String>, DaemonError> {
    use libgrite_core::export::{export_json, export_markdown, ExportSince};
    use libgrite_core::hash::compute_event_id;
    use libgrite_core::types::event::{Event, EventKind, IssueState};
    use libgrite_core::types::ids::{generate_issue_id, id_to_hex};
    use libgrite_core::types::issue::IssueProjection;
    use libgrite_git::{SyncManager, WalManager};

    // Open WAL (best-effort — sled operations work without it)
    let wal = match WalManager::open(git_dir) {
        Ok(w) => Some(w),
        Err(e) => {
            warn!("WAL open failed (sled-only mode): {}", e);
            None
        }
    };

    /// Persist events to both sled store and WAL.
    /// WAL append is best-effort — failures are logged but don't fail the operation.
    fn persist_events(
        store: &LockedStore,
        wal: Option<&WalManager>,
        actor_id: &ActorId,
        events: &[Event],
    ) -> Result<(), DaemonError> {
        for event in events {
            store.insert_event(event)?;
        }
        store.flush()?;

        if let Some(w) = wal {
            if let Err(e) = w.append(actor_id, events) {
                warn!("Failed to append to WAL: {}", e);
            }
        }

        Ok(())
    }

    match command {
        IpcCommand::IssueList { state, label } => {
            let filter = IssueFilter {
                state: state.as_ref().map(|s| match s.as_str() {
                    "open" => IssueState::Open,
                    "closed" => IssueState::Closed,
                    _ => IssueState::Open,
                }),
                label: label.clone(),
            };
            let issues = store.list_issues(&filter)?;
            let summaries: Vec<serde_json::Value> = issues
                .iter()
                .map(|s| {
                    serde_json::json!({
                        "issue_id": id_to_hex(&s.issue_id),
                        "title": s.title,
                        "state": format!("{:?}", s.state).to_lowercase(),
                        "labels": s.labels,
                        "assignees": s.assignees,
                        "created_ts": s.created_ts,
                        "updated_ts": s.updated_ts,
                        "comment_count": s.comment_count,
                    })
                })
                .collect();
            let json = serde_json::to_string(&serde_json::json!({ "issues": summaries }))?;
            Ok(Some(json))
        }

        IpcCommand::IssueShow { issue_id } => {
            let id = store
                .resolve_issue_id(issue_id)
                .map_err(DaemonError::Core)?;
            let p = store.get_issue(&id)?.ok_or_else(|| {
                DaemonError::Core(GriteError::NotFound(format!(
                    "Issue {} not found",
                    issue_id
                )))
            })?;

            let json = serde_json::to_string(&projection_to_json(&p))?;
            Ok(Some(json))
        }

        IpcCommand::IssueCreate {
            title,
            body,
            labels,
        } => {
            let issue_id = generate_issue_id();
            let ts = current_time_ms();
            let kind = EventKind::IssueCreated {
                title: title.clone(),
                body: body.clone(),
                labels: labels.clone(),
            };
            let event_id = compute_event_id(&issue_id, &actor_id_bytes, ts, None, &kind);
            let event = Event::new(event_id, issue_id, actor_id_bytes, ts, None, kind);

            persist_events(
                store,
                wal.as_ref(),
                &actor_id_bytes,
                std::slice::from_ref(&event),
            )?;

            let projection = IssueProjection::from_event(&event)?;
            let mut json_val = projection_to_json(&projection);
            json_val["event_id"] = serde_json::Value::String(id_to_hex(&event_id));
            json_val["action"] =
                serde_json::Value::String(libgrite_ipc::issue_action::CREATED.to_string());
            let json = serde_json::to_string(&json_val)?;
            Ok(Some(json))
        }

        IpcCommand::IssueUpdate {
            issue_id,
            title,
            body,
        } => {
            if title.is_none() && body.is_none() {
                return Err(DaemonError::Core(GriteError::InvalidArgs(
                    "At least one of title or body must be provided".to_string(),
                )));
            }

            let id = store
                .resolve_issue_id(issue_id)
                .map_err(DaemonError::Core)?;
            store.get_issue(&id)?.ok_or_else(|| {
                DaemonError::Core(GriteError::NotFound(format!(
                    "Issue {} not found",
                    issue_id
                )))
            })?;

            let ts = current_time_ms();
            let kind = EventKind::IssueUpdated {
                title: title.clone(),
                body: body.clone(),
            };
            let event_id = compute_event_id(&id, &actor_id_bytes, ts, None, &kind);
            let event = Event::new(event_id, id, actor_id_bytes, ts, None, kind);

            persist_events(
                store,
                wal.as_ref(),
                &actor_id_bytes,
                std::slice::from_ref(&event),
            )?;

            let json = serde_json::to_string(&serde_json::json!({
                "issue_id": issue_id,
                "event_id": id_to_hex(&event_id),
            }))?;
            Ok(Some(json))
        }

        IpcCommand::IssueComment { issue_id, body } => {
            let id = store
                .resolve_issue_id(issue_id)
                .map_err(DaemonError::Core)?;
            store.get_issue(&id)?.ok_or_else(|| {
                DaemonError::Core(GriteError::NotFound(format!(
                    "Issue {} not found",
                    issue_id
                )))
            })?;

            let ts = current_time_ms();
            let kind = EventKind::CommentAdded { body: body.clone() };
            let event_id = compute_event_id(&id, &actor_id_bytes, ts, None, &kind);
            let event = Event::new(event_id, id, actor_id_bytes, ts, None, kind);

            persist_events(
                store,
                wal.as_ref(),
                &actor_id_bytes,
                std::slice::from_ref(&event),
            )?;

            let json = serde_json::to_string(&serde_json::json!({
                "issue_id": issue_id,
                "event_id": id_to_hex(&event_id),
            }))?;
            Ok(Some(json))
        }

        IpcCommand::IssueClose { issue_id } => {
            let id = store
                .resolve_issue_id(issue_id)
                .map_err(DaemonError::Core)?;
            store.get_issue(&id)?.ok_or_else(|| {
                DaemonError::Core(GriteError::NotFound(format!(
                    "Issue {} not found",
                    issue_id
                )))
            })?;

            let ts = current_time_ms();
            let kind = EventKind::StateChanged {
                state: IssueState::Closed,
            };
            let event_id = compute_event_id(&id, &actor_id_bytes, ts, None, &kind);
            let event = Event::new(event_id, id, actor_id_bytes, ts, None, kind);

            persist_events(
                store,
                wal.as_ref(),
                &actor_id_bytes,
                std::slice::from_ref(&event),
            )?;

            let json = serde_json::to_string(&serde_json::json!({
                "issue_id": issue_id,
                "event_id": id_to_hex(&event_id),
                "state": "closed",
                "action": libgrite_ipc::issue_action::CLOSED,
            }))?;
            Ok(Some(json))
        }

        IpcCommand::IssueReopen { issue_id } => {
            let id = store
                .resolve_issue_id(issue_id)
                .map_err(DaemonError::Core)?;
            store.get_issue(&id)?.ok_or_else(|| {
                DaemonError::Core(GriteError::NotFound(format!(
                    "Issue {} not found",
                    issue_id
                )))
            })?;

            let ts = current_time_ms();
            let kind = EventKind::StateChanged {
                state: IssueState::Open,
            };
            let event_id = compute_event_id(&id, &actor_id_bytes, ts, None, &kind);
            let event = Event::new(event_id, id, actor_id_bytes, ts, None, kind);

            persist_events(
                store,
                wal.as_ref(),
                &actor_id_bytes,
                std::slice::from_ref(&event),
            )?;

            let json = serde_json::to_string(&serde_json::json!({
                "issue_id": issue_id,
                "event_id": id_to_hex(&event_id),
                "state": "open",
                "action": libgrite_ipc::issue_action::REOPENED,
            }))?;
            Ok(Some(json))
        }

        IpcCommand::IssueLabel {
            issue_id,
            add,
            remove,
        } => {
            let id = store
                .resolve_issue_id(issue_id)
                .map_err(DaemonError::Core)?;
            store.get_issue(&id)?.ok_or_else(|| {
                DaemonError::Core(GriteError::NotFound(format!(
                    "Issue {} not found",
                    issue_id
                )))
            })?;

            let mut event_ids = Vec::new();
            let mut events = Vec::new();
            let ts = current_time_ms();

            for label in add {
                let kind = EventKind::LabelAdded {
                    label: label.clone(),
                };
                let event_id = compute_event_id(&id, &actor_id_bytes, ts, None, &kind);
                let event = Event::new(event_id, id, actor_id_bytes, ts, None, kind);
                event_ids.push(id_to_hex(&event_id));
                events.push(event);
            }

            for label in remove {
                let kind = EventKind::LabelRemoved {
                    label: label.clone(),
                };
                let event_id = compute_event_id(&id, &actor_id_bytes, ts, None, &kind);
                let event = Event::new(event_id, id, actor_id_bytes, ts, None, kind);
                event_ids.push(id_to_hex(&event_id));
                events.push(event);
            }

            persist_events(store, wal.as_ref(), &actor_id_bytes, &events)?;

            let json = serde_json::to_string(&serde_json::json!({
                "issue_id": issue_id,
                "event_ids": event_ids,
            }))?;
            Ok(Some(json))
        }

        IpcCommand::IssueAssign {
            issue_id,
            add,
            remove,
        } => {
            let id = store
                .resolve_issue_id(issue_id)
                .map_err(DaemonError::Core)?;
            store.get_issue(&id)?.ok_or_else(|| {
                DaemonError::Core(GriteError::NotFound(format!(
                    "Issue {} not found",
                    issue_id
                )))
            })?;

            let mut event_ids = Vec::new();
            let mut events = Vec::new();
            let ts = current_time_ms();

            for user in add {
                let kind = EventKind::AssigneeAdded { user: user.clone() };
                let event_id = compute_event_id(&id, &actor_id_bytes, ts, None, &kind);
                let event = Event::new(event_id, id, actor_id_bytes, ts, None, kind);
                event_ids.push(id_to_hex(&event_id));
                events.push(event);
            }

            for user in remove {
                let kind = EventKind::AssigneeRemoved { user: user.clone() };
                let event_id = compute_event_id(&id, &actor_id_bytes, ts, None, &kind);
                let event = Event::new(event_id, id, actor_id_bytes, ts, None, kind);
                event_ids.push(id_to_hex(&event_id));
                events.push(event);
            }

            persist_events(store, wal.as_ref(), &actor_id_bytes, &events)?;

            let json = serde_json::to_string(&serde_json::json!({
                "issue_id": issue_id,
                "event_ids": event_ids,
            }))?;
            Ok(Some(json))
        }

        IpcCommand::IssueLink {
            issue_id,
            url,
            note,
        } => {
            let id = store
                .resolve_issue_id(issue_id)
                .map_err(DaemonError::Core)?;
            store.get_issue(&id)?.ok_or_else(|| {
                DaemonError::Core(GriteError::NotFound(format!(
                    "Issue {} not found",
                    issue_id
                )))
            })?;

            let ts = current_time_ms();
            let kind = EventKind::LinkAdded {
                url: url.clone(),
                note: note.clone(),
            };
            let event_id = compute_event_id(&id, &actor_id_bytes, ts, None, &kind);
            let event = Event::new(event_id, id, actor_id_bytes, ts, None, kind);

            persist_events(
                store,
                wal.as_ref(),
                &actor_id_bytes,
                std::slice::from_ref(&event),
            )?;

            let json = serde_json::to_string(&serde_json::json!({
                "issue_id": issue_id,
                "event_id": id_to_hex(&event_id),
            }))?;
            Ok(Some(json))
        }

        IpcCommand::IssueAttach {
            issue_id,
            file_path,
        } => {
            let id = store
                .resolve_issue_id(issue_id)
                .map_err(DaemonError::Core)?;
            store.get_issue(&id)?.ok_or_else(|| {
                DaemonError::Core(GriteError::NotFound(format!(
                    "Issue {} not found",
                    issue_id
                )))
            })?;

            let parts: Vec<&str> = file_path.splitn(3, ':').collect();
            if parts.len() != 3 {
                return Err(DaemonError::Core(GriteError::InvalidArgs(
                    "file_path must be in format 'name:sha256:mime'".to_string(),
                )));
            }

            let name = parts[0].to_string();
            let sha256: [u8; 32] = hex_to_id(parts[1])
                .map_err(|e| DaemonError::Core(GriteError::InvalidArgs(e.to_string())))?;
            let mime = parts[2].to_string();

            let ts = current_time_ms();
            let kind = EventKind::AttachmentAdded { name, sha256, mime };
            let event_id = compute_event_id(&id, &actor_id_bytes, ts, None, &kind);
            let event = Event::new(event_id, id, actor_id_bytes, ts, None, kind);

            persist_events(
                store,
                wal.as_ref(),
                &actor_id_bytes,
                std::slice::from_ref(&event),
            )?;

            let json = serde_json::to_string(&serde_json::json!({
                "issue_id": issue_id,
                "event_id": id_to_hex(&event_id),
            }))?;
            Ok(Some(json))
        }

        IpcCommand::DbStats => {
            let stats = store.stats(sled_path)?;
            let json = serde_json::to_string(&serde_json::json!({
                "path": stats.path,
                "size_bytes": stats.size_bytes,
                "event_count": stats.event_count,
                "issue_count": stats.issue_count,
                "last_rebuild_ts": stats.last_rebuild_ts,
            }))?;
            Ok(Some(json))
        }

        IpcCommand::Rebuild => {
            let stats = store.rebuild()?;
            let json = serde_json::to_string(&serde_json::json!({
                "event_count": stats.event_count,
                "issue_count": stats.issue_count,
            }))?;
            Ok(Some(json))
        }

        IpcCommand::Export { format, since } => {
            let since_opt = since
                .as_ref()
                .and_then(|s| s.parse::<u64>().ok())
                .map(ExportSince::Timestamp);

            let output = match format.as_str() {
                "json" => {
                    let export = export_json(store, since_opt)?;
                    serde_json::to_string(&export)?
                }
                "md" | "markdown" => export_markdown(store, since_opt)?,
                _ => {
                    return Err(DaemonError::Core(GriteError::InvalidArgs(format!(
                        "Unknown format: {}",
                        format
                    ))))
                }
            };
            Ok(Some(output))
        }

        IpcCommand::IssueDepAdd {
            issue_id,
            target_id,
            dep_type,
        } => {
            use libgrite_core::hash::compute_event_id;
            use libgrite_core::types::event::{DependencyType, Event, EventKind};
            use libgrite_core::types::ids::id_to_hex;

            let id = store
                .resolve_issue_id(issue_id)
                .map_err(DaemonError::Core)?;
            let target = store
                .resolve_issue_id(target_id)
                .map_err(DaemonError::Core)?;
            let dep = DependencyType::from_str(dep_type).ok_or_else(|| {
                DaemonError::Core(GriteError::InvalidArgs(format!(
                    "Invalid dep type: {}",
                    dep_type
                )))
            })?;

            store.get_issue(&id)?.ok_or_else(|| {
                DaemonError::Core(GriteError::NotFound(format!(
                    "Issue {} not found",
                    issue_id
                )))
            })?;
            store.get_issue(&target)?.ok_or_else(|| {
                DaemonError::Core(GriteError::NotFound(format!(
                    "Target {} not found",
                    target_id
                )))
            })?;

            if store.would_create_cycle(&id, &target, &dep)? {
                return Err(DaemonError::Core(GriteError::InvalidArgs(format!(
                    "Adding this dependency would create a cycle in the {} graph",
                    dep.as_str()
                ))));
            }

            let ts = current_time_ms();
            let kind = EventKind::DependencyAdded {
                target,
                dep_type: dep,
            };
            let event_id = compute_event_id(&id, &actor_id_bytes, ts, None, &kind);
            let event = Event::new(event_id, id, actor_id_bytes, ts, None, kind);
            persist_events(
                store,
                wal.as_ref(),
                &actor_id_bytes,
                std::slice::from_ref(&event),
            )?;

            let json = serde_json::to_string(&serde_json::json!({
                "event_id": id_to_hex(&event_id),
                "issue_id": issue_id,
                "target": target_id,
                "dep_type": dep_type,
                "action": "added",
            }))?;
            Ok(Some(json))
        }

        IpcCommand::IssueDepRemove {
            issue_id,
            target_id,
            dep_type,
        } => {
            use libgrite_core::hash::compute_event_id;
            use libgrite_core::types::event::{DependencyType, Event, EventKind};
            use libgrite_core::types::ids::id_to_hex;

            let id = store
                .resolve_issue_id(issue_id)
                .map_err(DaemonError::Core)?;
            let target = store
                .resolve_issue_id(target_id)
                .map_err(DaemonError::Core)?;
            let dep = DependencyType::from_str(dep_type).ok_or_else(|| {
                DaemonError::Core(GriteError::InvalidArgs(format!(
                    "Invalid dep type: {}",
                    dep_type
                )))
            })?;

            let ts = current_time_ms();
            let kind = EventKind::DependencyRemoved {
                target,
                dep_type: dep,
            };
            let event_id = compute_event_id(&id, &actor_id_bytes, ts, None, &kind);
            let event = Event::new(event_id, id, actor_id_bytes, ts, None, kind);
            persist_events(
                store,
                wal.as_ref(),
                &actor_id_bytes,
                std::slice::from_ref(&event),
            )?;

            let json = serde_json::to_string(&serde_json::json!({
                "event_id": id_to_hex(&event_id),
                "issue_id": issue_id,
                "target": target_id,
                "dep_type": dep_type,
                "action": "removed",
            }))?;
            Ok(Some(json))
        }

        IpcCommand::IssueDepList { issue_id, reverse } => {
            use libgrite_core::types::ids::id_to_hex;

            let id = store
                .resolve_issue_id(issue_id)
                .map_err(DaemonError::Core)?;
            let deps = if *reverse {
                store.get_dependents(&id)?
            } else {
                store.get_dependencies(&id)?
            };
            let dep_list: Vec<serde_json::Value> = deps
                .iter()
                .map(|(target, dep_type)| {
                    let title = match store.get_issue(target) {
                        Ok(Some(p)) => p.title.clone(),
                        Ok(None) => "?".to_string(),
                        Err(e) => return Err(DaemonError::Core(e)),
                    };
                    Ok(serde_json::json!({
                        "issue_id": id_to_hex(target),
                        "dep_type": dep_type.as_str(),
                        "title": title,
                    }))
                })
                .collect::<Result<Vec<_>, DaemonError>>()?;
            let json = serde_json::to_string(&serde_json::json!({
                "issue_id": issue_id,
                "direction": if *reverse { "dependents" } else { "dependencies" },
                "deps": dep_list,
            }))?;
            Ok(Some(json))
        }

        IpcCommand::IssueDepTopo { state, label } => {
            use libgrite_core::types::event::IssueState;
            use libgrite_core::types::ids::id_to_hex;

            let filter = IssueFilter {
                state: state.as_deref().map(|s| match s {
                    "closed" => IssueState::Closed,
                    _ => IssueState::Open,
                }),
                label: label.clone(),
            };
            let sorted = store.topological_order(&filter)?;
            let issues: Vec<serde_json::Value> = sorted
                .iter()
                .map(|s| {
                    serde_json::json!({
                        "issue_id": id_to_hex(&s.issue_id),
                        "title": s.title,
                        "state": format!("{:?}", s.state).to_lowercase(),
                        "labels": s.labels,
                    })
                })
                .collect();
            let json = serde_json::to_string(&serde_json::json!({
                "issues": issues,
                "order": "topological",
            }))?;
            Ok(Some(json))
        }

        // DaemonStatus and DaemonStop are handled at the supervisor level
        // in process_request() and never reach the worker.
        IpcCommand::DaemonStatus | IpcCommand::DaemonStop => Err(DaemonError::Core(
            GriteError::Internal("supervisor-only command received by worker".to_string()),
        )),

        IpcCommand::Sync { remote, pull, push } => {
            let sync_mgr = SyncManager::open(git_dir)?;

            // If neither flag is set, do both pull and push
            let do_pull = *pull || !*push;
            let do_push = *push || !*pull;

            // Auto-backfill WAL from sled if WAL is empty
            if do_push {
                if let Some(w) = wal.as_ref() {
                    if w.head().unwrap_or(None).is_none() {
                        let events = store.get_all_events().unwrap_or_default();
                        if !events.is_empty() {
                            let mut sorted = events;
                            sorted.sort_by_key(|e| e.ts_unix_ms);
                            match w.append(&actor_id_bytes, &sorted) {
                                Ok(_) => info!("Auto-backfilled WAL with {} events", sorted.len()),
                                Err(e) => warn!("WAL backfill failed: {}", e),
                            }
                        }
                    }
                }
            }

            let result = if do_pull && !do_push {
                // Pull only
                let pull_result = sync_mgr.pull(remote)?;
                let wal_head: Option<String> = pull_result.new_wal_head.map(|oid| oid.to_string());
                serde_json::json!({
                    "pulled": true,
                    "pushed": false,
                    "pull_events": pull_result.events_pulled,
                    "pull_wal_head": wal_head,
                    "message": pull_result.message,
                })
            } else if do_push && !do_pull {
                // Push only with auto-rebase
                let push_result = sync_mgr.push_with_rebase(remote, &actor_id_bytes)?;
                serde_json::json!({
                    "pulled": false,
                    "pushed": true,
                    "push_success": push_result.success,
                    "push_rebased": push_result.rebased,
                    "push_events_rebased": push_result.events_rebased,
                    "message": push_result.message,
                })
            } else {
                // Full sync: pull then push with auto-rebase
                let (pull_result, push_result) =
                    sync_mgr.sync_with_rebase(remote, &actor_id_bytes)?;
                let wal_head: Option<String> = pull_result.new_wal_head.map(|oid| oid.to_string());
                serde_json::json!({
                    "pulled": true,
                    "pushed": true,
                    "pull_events": pull_result.events_pulled,
                    "pull_wal_head": wal_head,
                    "push_success": push_result.success,
                    "push_rebased": push_result.rebased,
                    "push_events_rebased": push_result.events_rebased,
                    "message": format!("{} / {}", pull_result.message, push_result.message),
                })
            };

            Ok(Some(result.to_string()))
        }

        IpcCommand::SnapshotCreate | IpcCommand::SnapshotList | IpcCommand::SnapshotGc { .. } => {
            Err(DaemonError::Core(GriteError::Internal(
                "Snapshot through daemon not yet implemented - use --no-daemon".to_string(),
            )))
        }
    }
}

/// Convert an IssueProjection to a JSON value with hex-encoded IDs
fn projection_to_json(p: &libgrite_core::types::issue::IssueProjection) -> serde_json::Value {
    use libgrite_core::types::ids::id_to_hex;

    let comments: Vec<serde_json::Value> = p
        .comments
        .iter()
        .map(|c| {
            serde_json::json!({
                "event_id": id_to_hex(&c.event_id),
                "actor": id_to_hex(&c.actor),
                "ts_unix_ms": c.ts_unix_ms,
                "body": c.body,
            })
        })
        .collect();
    let links: Vec<serde_json::Value> = p
        .links
        .iter()
        .map(|l| {
            serde_json::json!({
                "event_id": id_to_hex(&l.event_id),
                "url": l.url,
                "note": l.note,
            })
        })
        .collect();
    let attachments: Vec<serde_json::Value> = p
        .attachments
        .iter()
        .map(|a| {
            serde_json::json!({
                "event_id": id_to_hex(&a.event_id),
                "name": a.name,
                "sha256": hex::encode(a.sha256),
                "mime": a.mime,
            })
        })
        .collect();
    let deps: Vec<serde_json::Value> = p
        .dependencies
        .iter()
        .map(|d| {
            serde_json::json!({
                "target": id_to_hex(&d.target),
                "dep_type": d.dep_type.as_str(),
            })
        })
        .collect();

    serde_json::json!({
        "issue_id": id_to_hex(&p.issue_id),
        "title": p.title,
        "body": p.body,
        "state": format!("{:?}", p.state).to_lowercase(),
        "labels": p.labels,
        "assignees": p.assignees,
        "comments": comments,
        "links": links,
        "attachments": attachments,
        "dependencies": deps,
        "created_ts": p.created_ts,
        "updated_ts": p.updated_ts,
    })
}

/// Get current time in milliseconds since Unix epoch
fn current_time_ms() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as u64
}

/// Convert error to (code, message) for IPC response
fn error_to_code_message(e: &DaemonError) -> (String, String) {
    use libgrite_ipc::error::codes;

    match e {
        DaemonError::Core(GriteError::NotFound(_)) => (codes::NOT_FOUND.to_string(), e.to_string()),
        DaemonError::Core(GriteError::InvalidArgs(_)) => {
            (codes::INVALID_INPUT.to_string(), e.to_string())
        }
        DaemonError::Core(GriteError::Io(_)) => (codes::IO_ERROR.to_string(), e.to_string()),
        DaemonError::Git(_) => (codes::GIT_ERROR.to_string(), e.to_string()),
        DaemonError::Ipc(_) => (codes::IPC_ERROR.to_string(), e.to_string()),
        _ => (codes::INTERNAL.to_string(), e.to_string()),
    }
}