bones-cli 0.24.0

CLI binary for bones issue tracker
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
//! `bn bone tag` and `bn bone untag` — add/remove labels from bones.

use crate::agent;
use crate::itc_state::assign_next_itc;
use crate::output::{CliError, OutputMode, render_error, render_mode};
use crate::validate;
use bones_core::db::query::{get_labels, try_open_projection};
use bones_core::event::data::UpdateData;
use bones_core::event::writer::write_event;
use bones_core::event::{Event, EventData, EventType};
use bones_core::model::item_id::ItemId;
use bones_core::shard::ShardManager;
use clap::Args;
use rusqlite::Connection;
use serde_json::json;
use std::collections::BTreeMap;
use std::time::Duration;

#[derive(Args, Debug)]
pub struct TagArgs {
    /// Bone ID to tag.
    pub id: String,

    /// Labels to add.
    #[arg(required = true)]
    pub labels: Vec<String>,

    /// Additional bone IDs to tag with the same labels.
    #[arg(long = "ids", value_name = "ID", num_args = 1..)]
    pub additional_ids: Vec<String>,
}

#[derive(Args, Debug)]
pub struct UntagArgs {
    /// Bone ID to untag.
    pub id: String,

    /// Labels to remove.
    #[arg(required = true)]
    pub labels: Vec<String>,

    /// Additional bone IDs to untag with the same labels.
    #[arg(long = "ids", value_name = "ID", num_args = 1..)]
    pub additional_ids: Vec<String>,
}

/// Normalize a label into canonical storage form.
///
/// Rules:
/// - trim surrounding whitespace
/// - convert to lowercase
/// - collapse internal whitespace to `-`
/// - allow at most one namespace separator `:` (not at start/end)
/// - reject `/`
/// - segments must start with ASCII alphanumeric and then contain only
///   ASCII alphanumeric, `-`, or `_`
pub fn normalize_label(input: &str) -> Result<String, validate::ValidationError> {
    let trimmed = input.trim();
    if trimmed.is_empty() {
        return Err(validate::ValidationError::new(
            "label",
            input,
            "must not be empty",
            "provide a non-empty label",
            "invalid_label",
        ));
    }

    let normalized = trimmed
        .split_whitespace()
        .collect::<Vec<_>>()
        .join("-")
        .to_ascii_lowercase();

    if normalized.chars().count() > validate::MAX_LABEL_LEN {
        return Err(validate::ValidationError::new(
            "label",
            input,
            format!("must be <= {} characters", validate::MAX_LABEL_LEN),
            "shorten the label",
            "invalid_label",
        ));
    }

    if normalized.contains('/') {
        return Err(validate::ValidationError::new(
            "label",
            input,
            "must not contain '/'",
            "remove '/' from the label",
            "invalid_label",
        ));
    }

    let colon_count = normalized.matches(':').count();
    if colon_count > 1 || normalized.starts_with(':') || normalized.ends_with(':') {
        return Err(validate::ValidationError::new(
            "label",
            input,
            "namespace separator ':' may appear at most once and not at start/end",
            "use labels like backend or area:frontend",
            "invalid_label",
        ));
    }

    for segment in normalized.split(':') {
        let mut chars = segment.chars();
        let Some(first) = chars.next() else {
            return Err(validate::ValidationError::new(
                "label",
                input,
                "namespace segment must not be empty",
                "use labels like backend or area:frontend",
                "invalid_label",
            ));
        };

        if !first.is_ascii_alphanumeric() {
            return Err(validate::ValidationError::new(
                "label",
                input,
                "must start with an ASCII letter or number",
                "start each label segment with [a-z0-9]",
                "invalid_label",
            ));
        }

        if !chars.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
            return Err(validate::ValidationError::new(
                "label",
                input,
                "may only contain ASCII letters, numbers, '-', '_', and a single ':' separator",
                "remove spaces or punctuation from the label",
                "invalid_label",
            ));
        }
    }

    Ok(normalized)
}

fn normalize_labels(inputs: &[String]) -> Result<Vec<String>, validate::ValidationError> {
    let mut out = Vec::new();
    for label in inputs {
        let normalized = normalize_label(label)?;
        if !out.contains(&normalized) {
            out.push(normalized);
        }
    }
    Ok(out)
}

/// Open the projection DB, returning a helpful error if it doesn't exist.
fn open_db(project_root: &std::path::Path) -> anyhow::Result<Connection> {
    let db_path = project_root.join(".bones").join("bones.db");
    match try_open_projection(&db_path)? {
        Some(conn) => Ok(conn),
        None => anyhow::bail!(
            "projection database not found or corrupt at {}.\n  Run `bn admin rebuild` to initialize it.",
            db_path.display()
        ),
    }
}

/// Read the current labels for an item from the projection DB.
fn read_current_labels(conn: &Connection, item_id: &str) -> anyhow::Result<Vec<String>> {
    // Check that the item exists
    if !bones_core::db::query::item_exists(conn, item_id)? {
        anyhow::bail!("item not found: {item_id}");
    }
    let labels = get_labels(conn, item_id)?;
    Ok(labels.into_iter().map(|l| l.label).collect())
}

/// Emit an `item.update` event for a single label add/remove action.
fn emit_label_event(
    project_root: &std::path::Path,
    agent: &str,
    item_id: &ItemId,
    action: &str,
    label: &str,
) -> anyhow::Result<String> {
    let bones_dir = project_root.join(".bones");
    let shard_mgr = ShardManager::new(&bones_dir);

    let mut event = Event {
        wall_ts_us: 0,
        agent: agent.to_string(),
        itc: String::new(),
        parents: vec![],
        event_type: EventType::Update,
        item_id: item_id.clone(),
        data: EventData::Update(UpdateData {
            field: "labels".into(),
            value: json!({
                "action": action,
                "label": label,
            }),
            extra: BTreeMap::new(),
        }),
        event_hash: String::new(),
    };

    {
        use bones_core::lock::ShardLock;
        let lock_path = shard_mgr.lock_path();
        let _lock = ShardLock::acquire(&lock_path, Duration::from_secs(5))
            .map_err(|e| anyhow::anyhow!("failed to acquire lock: {e}"))?;

        let (year, month) = shard_mgr
            .rotate_if_needed()
            .map_err(|e| anyhow::anyhow!("failed to rotate shards: {e}"))?;

        event.wall_ts_us = shard_mgr
            .next_timestamp()
            .map_err(|e| anyhow::anyhow!("failed to get timestamp: {e}"))?;

        assign_next_itc(project_root, &mut event)?;

        let line = write_event(&mut event)
            .map_err(|e| anyhow::anyhow!("failed to serialize event: {e}"))?;

        shard_mgr
            .append_raw(year, month, &line)
            .map_err(|e| anyhow::anyhow!("failed to write event: {e}"))?;
    }

    Ok(event.event_hash)
}

fn run_tag_single(
    project_root: &std::path::Path,
    agent: &str,
    raw_id: &str,
    normalized_labels: &[String],
) -> anyhow::Result<serde_json::Value> {
    let item_id =
        ItemId::parse(raw_id).map_err(|e| anyhow::anyhow!("invalid item ID '{raw_id}': {e}"))?;

    let conn = open_db(project_root)?;

    let current_labels = read_current_labels(&conn, item_id.as_str())?;

    let mut added = Vec::new();
    for label in normalized_labels {
        if !current_labels.contains(label) {
            emit_label_event(project_root, agent, &item_id, "add", label)?;
            added.push(label.clone());
        }
    }

    let mut new_labels = current_labels;
    for label in &added {
        new_labels.push(label.clone());
    }
    new_labels.sort();

    Ok(json!({
        "ok": true,
        "item_id": item_id.as_str(),
        "labels": new_labels,
        "added": added,
    }))
}

fn tag_item_ids(args: &TagArgs) -> impl Iterator<Item = &str> {
    std::iter::once(args.id.as_str()).chain(args.additional_ids.iter().map(String::as_str))
}

pub fn run_tag(
    args: &TagArgs,
    agent_flag: Option<&str>,
    output: OutputMode,
    project_root: &std::path::Path,
) -> anyhow::Result<()> {
    let agent = match agent::require_agent(agent_flag) {
        Ok(a) => a,
        Err(e) => {
            render_error(
                output,
                &CliError::with_details(&e.message, "Set --agent, BONES_AGENT, or AGENT", e.code),
            )?;
            anyhow::bail!("{}", e.message);
        }
    };

    if let Err(e) = validate::validate_agent(&agent) {
        render_error(output, &e.to_cli_error())?;
        anyhow::bail!("{}", e.reason);
    }

    let normalized_labels = match normalize_labels(&args.labels) {
        Ok(labels) => labels,
        Err(e) => {
            render_error(output, &e.to_cli_error())?;
            anyhow::bail!("{}", e.reason);
        }
    };

    let mut all_results = Vec::new();
    let mut failures = Vec::new();

    for raw_id in tag_item_ids(args) {
        match run_tag_single(project_root, &agent, raw_id, &normalized_labels) {
            Ok(val) => all_results.push(val),
            Err(err) => {
                failures.push(err.to_string());
                all_results.push(json!({
                    "ok": false,
                    "item_id": raw_id,
                    "error": err.to_string(),
                }));
            }
        }
    }

    let payload = json!({ "results": all_results });
    render_mode(
        output,
        &payload,
        |v, w| {
            for result in v["results"].as_array().unwrap_or(&vec![]) {
                let item = result["item_id"].as_str().unwrap_or("");
                if result["ok"].as_bool().unwrap_or(false) {
                    let added_list: Vec<&str> = result["added"]
                        .as_array()
                        .map(|a| a.iter().filter_map(|x| x.as_str()).collect())
                        .unwrap_or_default();
                    let all_labels: Vec<&str> = result["labels"]
                        .as_array()
                        .map(|a| a.iter().filter_map(|x| x.as_str()).collect())
                        .unwrap_or_default();
                    writeln!(
                        w,
                        "ok=true  item={}  added={}  labels={}",
                        item,
                        if added_list.is_empty() {
                            "(none)".to_string()
                        } else {
                            added_list.join(",")
                        },
                        if all_labels.is_empty() {
                            "(none)".to_string()
                        } else {
                            all_labels.join(",")
                        }
                    )?;
                } else {
                    writeln!(
                        w,
                        "ok=false  item={}  error={}",
                        item,
                        result["error"].as_str().unwrap_or("unknown error")
                    )?;
                }
            }
            Ok(())
        },
        |v, w| {
            for result in v["results"].as_array().unwrap_or(&vec![]) {
                let item = result["item_id"].as_str().unwrap_or("");
                if result["ok"].as_bool().unwrap_or(false) {
                    let added_list: Vec<&str> = result["added"]
                        .as_array()
                        .map(|a| a.iter().filter_map(|x| x.as_str()).collect())
                        .unwrap_or_default();
                    let all_labels: Vec<&str> = result["labels"]
                        .as_array()
                        .map(|a| a.iter().filter_map(|x| x.as_str()).collect())
                        .unwrap_or_default();
                    if added_list.is_empty() {
                        writeln!(
                            w,
                            "{item}: labels unchanged (all already present): {}",
                            all_labels.join(", ")
                        )?;
                    } else {
                        writeln!(
                            w,
                            "{item}: added {} → labels: {}",
                            added_list.join(", "),
                            all_labels.join(", ")
                        )?;
                    }
                } else {
                    writeln!(
                        w,
                        "{item}: {}",
                        result["error"].as_str().unwrap_or("unknown error")
                    )?;
                }
            }
            Ok(())
        },
    )?;

    if failures.is_empty() {
        Ok(())
    } else if failures.len() == 1 {
        anyhow::bail!("{}", failures[0]);
    } else {
        anyhow::bail!("{} item(s) failed", failures.len());
    }
}

fn run_untag_single(
    project_root: &std::path::Path,
    agent: &str,
    raw_id: &str,
    normalized_labels: &[String],
) -> anyhow::Result<serde_json::Value> {
    let item_id =
        ItemId::parse(raw_id).map_err(|e| anyhow::anyhow!("invalid item ID '{raw_id}': {e}"))?;

    let conn = open_db(project_root)?;

    let current_labels = read_current_labels(&conn, item_id.as_str())?;

    let mut removed = Vec::new();
    for label in normalized_labels {
        if current_labels.contains(label) {
            emit_label_event(project_root, agent, &item_id, "remove", label)?;
            removed.push(label.clone());
        }
    }

    let labels_to_remove: std::collections::HashSet<&str> =
        removed.iter().map(String::as_str).collect();
    let mut new_labels: Vec<String> = current_labels
        .into_iter()
        .filter(|l| !labels_to_remove.contains(l.as_str()))
        .collect();
    new_labels.sort();

    Ok(json!({
        "ok": true,
        "item_id": item_id.as_str(),
        "labels": new_labels,
        "removed": removed,
    }))
}

fn untag_item_ids(args: &UntagArgs) -> impl Iterator<Item = &str> {
    std::iter::once(args.id.as_str()).chain(args.additional_ids.iter().map(String::as_str))
}

pub fn run_untag(
    args: &UntagArgs,
    agent_flag: Option<&str>,
    output: OutputMode,
    project_root: &std::path::Path,
) -> anyhow::Result<()> {
    let agent = match agent::require_agent(agent_flag) {
        Ok(a) => a,
        Err(e) => {
            render_error(
                output,
                &CliError::with_details(&e.message, "Set --agent, BONES_AGENT, or AGENT", e.code),
            )?;
            anyhow::bail!("{}", e.message);
        }
    };

    if let Err(e) = validate::validate_agent(&agent) {
        render_error(output, &e.to_cli_error())?;
        anyhow::bail!("{}", e.reason);
    }

    let normalized_labels = match normalize_labels(&args.labels) {
        Ok(labels) => labels,
        Err(e) => {
            render_error(output, &e.to_cli_error())?;
            anyhow::bail!("{}", e.reason);
        }
    };

    let mut all_results = Vec::new();
    let mut failures = Vec::new();

    for raw_id in untag_item_ids(args) {
        match run_untag_single(project_root, &agent, raw_id, &normalized_labels) {
            Ok(val) => all_results.push(val),
            Err(err) => {
                failures.push(err.to_string());
                all_results.push(json!({
                    "ok": false,
                    "item_id": raw_id,
                    "error": err.to_string(),
                }));
            }
        }
    }

    let payload = json!({ "results": all_results });
    render_mode(
        output,
        &payload,
        |v, w| {
            for result in v["results"].as_array().unwrap_or(&vec![]) {
                let item = result["item_id"].as_str().unwrap_or("");
                if result["ok"].as_bool().unwrap_or(false) {
                    let removed_list: Vec<&str> = result["removed"]
                        .as_array()
                        .map(|a| a.iter().filter_map(|x| x.as_str()).collect())
                        .unwrap_or_default();
                    let all_labels: Vec<&str> = result["labels"]
                        .as_array()
                        .map(|a| a.iter().filter_map(|x| x.as_str()).collect())
                        .unwrap_or_default();
                    writeln!(
                        w,
                        "ok=true  item={}  removed={}  labels={}",
                        item,
                        if removed_list.is_empty() {
                            "(none)".to_string()
                        } else {
                            removed_list.join(",")
                        },
                        if all_labels.is_empty() {
                            "(none)".to_string()
                        } else {
                            all_labels.join(",")
                        }
                    )?;
                } else {
                    writeln!(
                        w,
                        "ok=false  item={}  error={}",
                        item,
                        result["error"].as_str().unwrap_or("unknown error")
                    )?;
                }
            }
            Ok(())
        },
        |v, w| {
            for result in v["results"].as_array().unwrap_or(&vec![]) {
                let item = result["item_id"].as_str().unwrap_or("");
                if result["ok"].as_bool().unwrap_or(false) {
                    let removed_list: Vec<&str> = result["removed"]
                        .as_array()
                        .map(|a| a.iter().filter_map(|x| x.as_str()).collect())
                        .unwrap_or_default();
                    let all_labels: Vec<&str> = result["labels"]
                        .as_array()
                        .map(|a| a.iter().filter_map(|x| x.as_str()).collect())
                        .unwrap_or_default();
                    if removed_list.is_empty() {
                        writeln!(
                            w,
                            "{item}: labels unchanged (none present): {}",
                            if all_labels.is_empty() {
                                "(none)".to_string()
                            } else {
                                all_labels.join(", ")
                            }
                        )?;
                    } else {
                        writeln!(
                            w,
                            "{item}: removed {} → labels: {}",
                            removed_list.join(", "),
                            if all_labels.is_empty() {
                                "(none)".to_string()
                            } else {
                                all_labels.join(", ")
                            }
                        )?;
                    }
                } else {
                    writeln!(
                        w,
                        "{item}: {}",
                        result["error"].as_str().unwrap_or("unknown error")
                    )?;
                }
            }
            Ok(())
        },
    )?;

    if failures.is_empty() {
        Ok(())
    } else if failures.len() == 1 {
        anyhow::bail!("{}", failures[0]);
    } else {
        anyhow::bail!("{} item(s) failed", failures.len());
    }
}

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

    #[test]
    fn tag_args_parses() {
        use clap::Parser;

        #[derive(Parser)]
        struct Wrapper {
            #[command(flatten)]
            args: TagArgs,
        }
        let w = Wrapper::parse_from(["test", "item-1", "bug", "urgent"]);
        assert_eq!(w.args.id, "item-1");
        assert_eq!(w.args.labels, vec!["bug", "urgent"]);
    }

    #[test]
    fn untag_args_parses() {
        use clap::Parser;

        #[derive(Parser)]
        struct Wrapper {
            #[command(flatten)]
            args: UntagArgs,
        }
        let w = Wrapper::parse_from(["test", "item-1", "stale"]);
        assert_eq!(w.args.id, "item-1");
        assert_eq!(w.args.labels, vec!["stale"]);
    }

    #[test]
    fn normalize_label_lowercases_and_hyphenates_spaces() {
        let normalized = normalize_label(" Area:Needs Triage ").expect("normalize");
        assert_eq!(normalized, "area:needs-triage");
    }

    #[test]
    fn normalize_label_rejects_bad_namespace_and_slash() {
        assert!(normalize_label("area:team:backend").is_err());
        assert!(normalize_label("docs/readme").is_err());
    }

    #[test]
    fn tag_deduplicates_labels() {
        // Simulate: current = ["a", "b"], adding ["b", "c"] -> ["a", "b", "c"]
        let current = vec!["a".to_string(), "b".to_string()];
        let to_add = vec!["b".to_string(), "c".to_string()];
        let mut new_labels = current.clone();
        for label in &to_add {
            if !new_labels.contains(label) {
                new_labels.push(label.clone());
            }
        }
        assert_eq!(new_labels, vec!["a", "b", "c"]);
    }

    #[test]
    fn untag_removes_specified_labels() {
        // Simulate: current = ["a", "b", "c"], removing ["b", "d"] -> ["a", "c"]
        let current = vec!["a".to_string(), "b".to_string(), "c".to_string()];
        let to_remove: std::collections::HashSet<&str> = ["b", "d"].iter().copied().collect();
        let new_labels: Vec<String> = current
            .iter()
            .filter(|l| !to_remove.contains(l.as_str()))
            .cloned()
            .collect();
        assert_eq!(new_labels, vec!["a", "c"]);
    }

    #[test]
    fn tag_idempotent_same_labels() {
        // Adding already-present labels should not change the set
        let current = vec!["a".to_string(), "b".to_string()];
        let to_add = vec!["a".to_string(), "b".to_string()];
        let mut new_labels = current.clone();
        for label in &to_add {
            if !new_labels.contains(label) {
                new_labels.push(label.clone());
            }
        }
        assert_eq!(new_labels, current);
    }

    #[test]
    fn untag_missing_labels_idempotent() {
        // Removing non-existent labels should leave the set unchanged
        let current = vec!["a".to_string(), "b".to_string()];
        let to_remove: std::collections::HashSet<&str> = ["x", "y"].iter().copied().collect();
        let new_labels: Vec<String> = current
            .iter()
            .filter(|l| !to_remove.contains(l.as_str()))
            .cloned()
            .collect();
        assert_eq!(new_labels, current);
    }

    #[test]
    fn untag_all_labels_produces_empty() {
        let current = vec!["a".to_string(), "b".to_string()];
        let to_remove: std::collections::HashSet<&str> = ["a", "b"].iter().copied().collect();
        let new_labels: Vec<String> = current
            .iter()
            .filter(|l| !to_remove.contains(l.as_str()))
            .cloned()
            .collect();
        assert!(new_labels.is_empty());
    }

    #[test]
    fn emit_labels_event_data_structure() {
        // Verify the UpdateData structure is built correctly
        let labels = vec!["bug".to_string(), "urgent".to_string()];
        let data = UpdateData {
            field: "labels".into(),
            value: json!(labels),
            extra: BTreeMap::new(),
        };
        assert_eq!(data.field, "labels");
        assert_eq!(data.value, json!(["bug", "urgent"]));
    }

    // -----------------------------------------------------------------------
    // Integration tests
    // -----------------------------------------------------------------------

    /// Set up a minimal bones project in a temp dir: initialize shard, create
    /// an item event, rebuild the projection DB.
    #[cfg(test)]
    fn setup_test_project() -> (tempfile::TempDir, std::path::PathBuf, String) {
        use bones_core::db::rebuild;
        use bones_core::event::data::CreateData;
        use bones_core::event::writer::write_event;
        use bones_core::event::{Event, EventData, EventType};
        use bones_core::model::item::Kind;
        use bones_core::model::item_id::ItemId;
        use bones_core::shard::ShardManager;
        use std::time::Duration;

        let dir = tempfile::tempdir().expect("create temp dir");
        let root = dir.path().to_path_buf();
        let bones_dir = root.join(".bones");
        let shard_mgr = ShardManager::new(&bones_dir);
        shard_mgr.ensure_dirs().expect("ensure dirs");
        shard_mgr.init().expect("init shard");

        // Create a test item via event
        let item_id = "bn-tst1";
        let ts = shard_mgr.next_timestamp().expect("get timestamp");
        let mut create_event = Event {
            wall_ts_us: ts,
            agent: "test-agent".to_string(),
            itc: "itc:AQ".into(),
            parents: vec![],
            event_type: EventType::Create,
            item_id: ItemId::new_unchecked(item_id),
            data: EventData::Create(CreateData {
                title: "Test item".into(),
                kind: Kind::Task,
                size: None,
                urgency: bones_core::model::item::Urgency::Default,
                labels: vec!["initial".into()],
                parent: None,
                causation: None,
                description: None,
                extra: BTreeMap::new(),
            }),
            event_hash: String::new(),
        };
        let line = write_event(&mut create_event).expect("write event");
        shard_mgr
            .append(&line, false, Duration::from_secs(5))
            .expect("append create event");

        // Rebuild the projection DB
        let events_dir = bones_dir.join("events");
        let db_path = bones_dir.join("bones.db");
        rebuild::rebuild(&events_dir, &db_path).expect("rebuild projection");

        (dir, root, item_id.to_string())
    }

    #[test]
    fn run_tag_adds_labels_to_item() {
        use crate::output::OutputMode;
        use bones_core::db::query::{get_labels, try_open_projection};

        let (_dir, root, item_id) = setup_test_project();

        // Add "bug" and "urgent" labels
        let args = TagArgs {
            id: item_id.clone(),
            labels: vec!["bug".to_string(), "urgent".to_string()],
            additional_ids: vec![],
        };
        run_tag(&args, Some("test-agent"), OutputMode::Pretty, &root)
            .expect("run_tag should succeed");

        // Rebuild projection to pick up the new event
        let bones_dir = root.join(".bones");
        let events_dir = bones_dir.join("events");
        let db_path = bones_dir.join("bones.db");
        bones_core::db::rebuild::rebuild(&events_dir, &db_path).expect("rebuild");

        // Verify labels in projection
        let conn = try_open_projection(&db_path)
            .expect("open db")
            .expect("db should exist");
        let labels = get_labels(&conn, &item_id).expect("get labels");
        let label_names: Vec<&str> = labels.iter().map(|l| l.label.as_str()).collect();
        assert!(label_names.contains(&"bug"), "should contain 'bug'");
        assert!(label_names.contains(&"urgent"), "should contain 'urgent'");
        assert!(
            label_names.contains(&"initial"),
            "should contain original 'initial' label"
        );
    }

    #[test]
    fn run_tag_is_idempotent() {
        use crate::output::OutputMode;
        use bones_core::db::query::{get_labels, try_open_projection};
        use bones_core::db::rebuild;

        let (_dir, root, item_id) = setup_test_project();

        // Add the same label twice
        let args = TagArgs {
            id: item_id.clone(),
            labels: vec!["initial".to_string()], // already present
            additional_ids: vec![],
        };
        run_tag(&args, Some("test-agent"), OutputMode::Pretty, &root)
            .expect("run_tag should succeed even for existing labels");

        // Rebuild and verify no duplicates
        let bones_dir = root.join(".bones");
        let events_dir = bones_dir.join("events");
        let db_path = bones_dir.join("bones.db");
        rebuild::rebuild(&events_dir, &db_path).expect("rebuild");

        let conn = try_open_projection(&db_path)
            .expect("open db")
            .expect("db should exist");
        let labels = get_labels(&conn, &item_id).expect("get labels");
        let initial_count = labels.iter().filter(|l| l.label == "initial").count();
        assert_eq!(
            initial_count, 1,
            "label 'initial' should appear exactly once"
        );
    }

    #[test]
    fn run_untag_removes_labels() {
        use crate::output::OutputMode;
        use bones_core::db::query::{get_labels, try_open_projection};
        use bones_core::db::rebuild;

        let (_dir, root, item_id) = setup_test_project();

        // First add some labels
        let tag_args = TagArgs {
            id: item_id.clone(),
            labels: vec!["a".to_string(), "b".to_string()],
            additional_ids: vec![],
        };
        run_tag(&tag_args, Some("test-agent"), OutputMode::Pretty, &root)
            .expect("run_tag should succeed");

        // Rebuild to pick up the tags
        let bones_dir = root.join(".bones");
        let events_dir = bones_dir.join("events");
        let db_path = bones_dir.join("bones.db");
        rebuild::rebuild(&events_dir, &db_path).expect("rebuild");

        // Now remove "a"
        let untag_args = UntagArgs {
            id: item_id.clone(),
            labels: vec!["a".to_string()],
            additional_ids: vec![],
        };
        run_untag(&untag_args, Some("test-agent"), OutputMode::Pretty, &root)
            .expect("run_untag should succeed");

        // Rebuild again and verify
        rebuild::rebuild(&events_dir, &db_path).expect("rebuild");

        let conn = try_open_projection(&db_path)
            .expect("open db")
            .expect("db should exist");
        let labels = get_labels(&conn, &item_id).expect("get labels");
        let label_names: Vec<&str> = labels.iter().map(|l| l.label.as_str()).collect();
        assert!(!label_names.contains(&"a"), "'a' should be removed");
        assert!(label_names.contains(&"b"), "'b' should remain");
    }

    #[test]
    fn run_tag_fails_on_missing_db() {
        use crate::output::OutputMode;

        let dir = tempfile::tempdir().expect("create temp dir");
        let root = dir.path();

        // No .bones/ directory at all
        let args = TagArgs {
            id: "bn-a7x".to_string(),
            labels: vec!["bug".to_string()],
            additional_ids: vec![],
        };
        let result = run_tag(&args, Some("test-agent"), OutputMode::Pretty, root);
        assert!(result.is_err(), "should fail when no projection DB exists");
    }

    #[test]
    fn run_tag_fails_on_nonexistent_item() {
        use crate::output::OutputMode;
        use bones_core::db::rebuild;
        use bones_core::shard::ShardManager;

        let dir = tempfile::tempdir().expect("create temp dir");
        let root = dir.path();
        let bones_dir = root.join(".bones");
        let shard_mgr = ShardManager::new(&bones_dir);
        shard_mgr.ensure_dirs().expect("ensure dirs");
        shard_mgr.init().expect("init shard");

        // Rebuild to create an empty projection DB
        let events_dir = bones_dir.join("events");
        let db_path = bones_dir.join("bones.db");
        rebuild::rebuild(&events_dir, &db_path).expect("rebuild");

        // Try to tag a non-existent item
        let args = TagArgs {
            id: "bn-tst9".to_string(),
            labels: vec!["bug".to_string()],
            additional_ids: vec![],
        };
        let result = run_tag(&args, Some("test-agent"), OutputMode::Pretty, root);
        assert!(result.is_err(), "should fail when item does not exist");
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("not found"),
            "error should mention item not found"
        );
    }
}