agent-kanban 0.1.1

Kanban CLI for multiple concurrent LLM agents to coordinate on tasks, backed by SQLite
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
//! Black-box integration tests that exercise the compiled `agent-kanban` binary as
//! a subprocess, using `assert_cmd`. Every test gets its own `TempDir` and
//! runs all commands with `.current_dir(&dir)` so tests never interfere with
//! each other or with the repo's own working directory.

use assert_cmd::Command;
use predicates::str::contains;
use serde_json::Value;
use std::path::Path;
use tempfile::TempDir;

/// Build a `kanban` command rooted at `dir`.
fn kanban(dir: &TempDir) -> Command {
    let mut cmd = Command::cargo_bin("agent-kanban").unwrap();
    cmd.current_dir(dir);
    cmd
}

/// Build a `kanban` command rooted at an arbitrary path (not necessarily a
/// `TempDir` root), for tests that need to run from a subdirectory.
fn kanban_at(dir: impl AsRef<Path>) -> Command {
    let mut cmd = Command::cargo_bin("agent-kanban").unwrap();
    cmd.current_dir(dir.as_ref());
    cmd
}

/// Run a kanban command rooted at an arbitrary path and parse its stdout as
/// JSON, asserting success.
fn run_json_at(dir: impl AsRef<Path>, args: &[&str]) -> Value {
    let output = kanban_at(dir.as_ref()).args(args).output().unwrap();
    assert!(
        output.status.success(),
        "command {:?} failed: stdout={} stderr={}",
        args,
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    serde_json::from_slice(&output.stdout).unwrap_or_else(|e| {
        panic!(
            "invalid JSON from {:?}: {e}\nstdout={}",
            args,
            String::from_utf8_lossy(&output.stdout)
        )
    })
}

/// Run a kanban command and parse its stdout as JSON, asserting success.
fn run_json(dir: &TempDir, args: &[&str]) -> Value {
    let output = kanban(dir).args(args).output().unwrap();
    assert!(
        output.status.success(),
        "command {:?} failed: stdout={} stderr={}",
        args,
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    serde_json::from_slice(&output.stdout).unwrap_or_else(|e| {
        panic!(
            "invalid JSON from {:?}: {e}\nstdout={}",
            args,
            String::from_utf8_lossy(&output.stdout)
        )
    })
}

fn init(dir: &TempDir) {
    kanban(dir).arg("init").assert().success();
}

fn register(dir: &TempDir, name: &str) {
    kanban(dir)
        .args(["agent", "register", name])
        .assert()
        .success();
}

#[test]
fn golden_path_full_lifecycle() {
    let dir = TempDir::new().unwrap();

    // init
    kanban(&dir)
        .arg("init")
        .assert()
        .success()
        .stdout(contains("initialized"));

    // agent register
    register(&dir, "agent-alpha");

    // add (with tags + a test)
    let test_json = r#"{"describe":"basic add","input":"2+2","output":"4"}"#;
    let created = run_json(
        &dir,
        &[
            "add",
            "--title",
            "Implement feature X",
            "--priority",
            "high",
            "--tag",
            "backend",
            "--tag",
            "urgent-fix",
            "--test",
            test_json,
        ],
    );
    let task_id = created["id"].as_i64().unwrap();
    assert_eq!(created["title"], "Implement feature X");
    assert_eq!(created["priority"], "high");
    assert_eq!(created["status"], "todo");
    assert_eq!(created["executor"], Value::Null);
    assert_eq!(created["tags"].as_array().unwrap().len(), 2);
    assert_eq!(created["tests"].as_array().unwrap().len(), 1);

    // list shows it
    let listed = run_json(&dir, &["list"]);
    let arr = listed.as_array().unwrap();
    assert_eq!(arr.len(), 1);
    assert_eq!(arr[0]["id"].as_i64().unwrap(), task_id);

    // show round-trips it
    let shown = run_json(&dir, &["show", &task_id.to_string()]);
    assert_eq!(shown["title"], "Implement feature X");
    assert_eq!(shown["tags"][0], "backend");
    assert_eq!(shown["tags"][1], "urgent-fix");
    assert_eq!(shown["tests"][0]["describe"], "basic add");

    // claim succeeds and flips status to in_progress
    let claimed = run_json(
        &dir,
        &["claim", &task_id.to_string(), "--agent", "agent-alpha"],
    );
    assert_eq!(claimed["executor"], "agent-alpha");
    assert_eq!(claimed["status"], "in_progress");

    // move to review
    let moved = run_json(&dir, &["move", &task_id.to_string(), "--status", "review"]);
    assert_eq!(moved["status"], "review");

    // edit fails while claimed
    kanban(&dir)
        .args(["edit", &task_id.to_string(), "--title", "renamed"])
        .assert()
        .failure()
        .stderr(contains("claimed"));

    // release clears executor and resets status
    let released = run_json(&dir, &["release", &task_id.to_string()]);
    assert_eq!(released["executor"], Value::Null);
    assert_eq!(released["status"], "todo");

    // edit succeeds now
    let edited = run_json(
        &dir,
        &["edit", &task_id.to_string(), "--title", "renamed task"],
    );
    assert_eq!(edited["title"], "renamed task");

    // remove succeeds
    let removed = run_json(&dir, &["remove", &task_id.to_string()]);
    assert_eq!(removed["removed"].as_i64().unwrap(), task_id);

    kanban(&dir)
        .args(["show", &task_id.to_string()])
        .assert()
        .failure()
        .stderr(contains("not found"));

    // agent remove on an agent with no remaining claims
    let agent_removed = run_json(&dir, &["agent", "remove", "agent-alpha"]);
    assert_eq!(agent_removed["removed"], "agent-alpha");
    assert_eq!(agent_removed["released_tasks"].as_array().unwrap().len(), 0);
}

#[test]
fn registering_duplicate_agent_fails_cleanly() {
    let dir = TempDir::new().unwrap();
    init(&dir);
    register(&dir, "dup-agent");

    kanban(&dir)
        .args(["agent", "register", "dup-agent"])
        .assert()
        .failure()
        .stderr(contains("already exists"));
}

#[test]
fn add_with_invalid_priority_fails() {
    let dir = TempDir::new().unwrap();
    init(&dir);

    kanban(&dir)
        .args([
            "add",
            "--title",
            "bad task",
            "--priority",
            "urgentish",
            "--test",
            r#"{"describe":"d","input":"i","output":"o"}"#,
        ])
        .assert()
        .failure()
        .stderr(contains("invalid priority"));
}

#[test]
fn add_with_test_missing_required_field_fails() {
    let dir = TempDir::new().unwrap();
    init(&dir);

    kanban(&dir)
        .args([
            "add",
            "--title",
            "bad task",
            "--priority",
            "low",
            "--test",
            r#"{"describe":"d","input":"i"}"#, // missing "output"
        ])
        .assert()
        .failure()
        .stderr(contains("output"));
}

#[test]
fn claim_unregistered_agent_fails_and_leaves_executor_null() {
    let dir = TempDir::new().unwrap();
    init(&dir);
    let created = run_json(
        &dir,
        &[
            "add",
            "--title",
            "t1",
            "--priority",
            "low",
            "--test",
            r#"{"describe":"d","input":"i","output":"o"}"#,
        ],
    );
    let id = created["id"].as_i64().unwrap();

    kanban(&dir)
        .args(["claim", &id.to_string(), "--agent", "ghost-agent"])
        .assert()
        .failure()
        .stderr(contains("not registered"));

    // Critical: task's executor is still null afterward.
    let shown = run_json(&dir, &["show", &id.to_string()]);
    assert_eq!(shown["executor"], Value::Null);
    assert_eq!(shown["status"], "todo");
}

#[test]
fn claim_on_already_claimed_task_fails() {
    let dir = TempDir::new().unwrap();
    init(&dir);
    register(&dir, "agent-a");
    register(&dir, "agent-b");
    let created = run_json(
        &dir,
        &[
            "add",
            "--title",
            "t1",
            "--priority",
            "low",
            "--test",
            r#"{"describe":"d","input":"i","output":"o"}"#,
        ],
    );
    let id = created["id"].as_i64().unwrap();

    run_json(&dir, &["claim", &id.to_string(), "--agent", "agent-a"]);

    kanban(&dir)
        .args(["claim", &id.to_string(), "--agent", "agent-b"])
        .assert()
        .failure()
        .stderr(contains("already claimed"));

    let shown = run_json(&dir, &["show", &id.to_string()]);
    assert_eq!(shown["executor"], "agent-a");
}

#[test]
fn edit_and_remove_blocked_while_claimed() {
    let dir = TempDir::new().unwrap();
    init(&dir);
    register(&dir, "agent-a");
    let created = run_json(
        &dir,
        &[
            "add",
            "--title",
            "t1",
            "--priority",
            "low",
            "--test",
            r#"{"describe":"d","input":"i","output":"o"}"#,
        ],
    );
    let id = created["id"].as_i64().unwrap();
    run_json(&dir, &["claim", &id.to_string(), "--agent", "agent-a"]);

    kanban(&dir)
        .args(["edit", &id.to_string(), "--title", "x"])
        .assert()
        .failure()
        .stderr(contains("claimed"));

    kanban(&dir)
        .args(["remove", &id.to_string()])
        .assert()
        .failure()
        .stderr(contains("claimed"));
}

#[test]
fn edit_and_remove_blocked_when_done() {
    let dir = TempDir::new().unwrap();
    init(&dir);
    let created = run_json(
        &dir,
        &[
            "add",
            "--title",
            "t1",
            "--priority",
            "low",
            "--test",
            r#"{"describe":"d","input":"i","output":"o"}"#,
        ],
    );
    let id = created["id"].as_i64().unwrap();
    run_json(&dir, &["move", &id.to_string(), "--status", "done"]);

    kanban(&dir)
        .args(["edit", &id.to_string(), "--title", "x"])
        .assert()
        .failure()
        .stderr(contains("immutable"));

    kanban(&dir)
        .args(["remove", &id.to_string()])
        .assert()
        .failure()
        .stderr(contains("can't be removed"));
}

#[test]
fn commands_before_init_fail_cleanly() {
    let dir = TempDir::new().unwrap();
    // no init() call here

    kanban(&dir)
        .args(["agent", "list"])
        .assert()
        .failure()
        .stderr(contains("agent-kanban init"));

    kanban(&dir)
        .args(["list"])
        .assert()
        .failure()
        .stderr(contains("agent-kanban init"));
}

#[test]
fn agent_remove_cascade_releases_claimed_task() {
    let dir = TempDir::new().unwrap();
    init(&dir);
    register(&dir, "agent-a");
    let created = run_json(
        &dir,
        &[
            "add",
            "--title",
            "t1",
            "--priority",
            "low",
            "--test",
            r#"{"describe":"d","input":"i","output":"o"}"#,
        ],
    );
    let id = created["id"].as_i64().unwrap();
    run_json(&dir, &["claim", &id.to_string(), "--agent", "agent-a"]);

    let removed = run_json(&dir, &["agent", "remove", "agent-a"]);
    assert_eq!(removed["removed"], "agent-a");
    assert_eq!(removed["released_tasks"][0].as_i64().unwrap(), id);

    let shown = run_json(&dir, &["show", &id.to_string()]);
    assert_eq!(shown["executor"], Value::Null);
    assert_eq!(shown["status"], "todo");
}

#[test]
fn list_filtering_and_sorting() {
    let dir = TempDir::new().unwrap();
    init(&dir);
    register(&dir, "agent-a");

    // t1: urgent, tag "alpha"
    let t1 = run_json(
        &dir,
        &[
            "add",
            "--title",
            "t1",
            "--priority",
            "urgent",
            "--tag",
            "alpha",
            "--test",
            r#"{"describe":"d","input":"i","output":"o"}"#,
        ],
    );
    // t2: low, tag "beta"
    run_json(
        &dir,
        &[
            "add",
            "--title",
            "t2",
            "--priority",
            "low",
            "--tag",
            "beta",
            "--test",
            r#"{"describe":"d","input":"i","output":"o"}"#,
        ],
    );
    // t3: medium, tag "alpha"
    run_json(
        &dir,
        &[
            "add",
            "--title",
            "t3",
            "--priority",
            "medium",
            "--tag",
            "alpha",
            "--test",
            r#"{"describe":"d","input":"i","output":"o"}"#,
        ],
    );
    // t4: high
    run_json(
        &dir,
        &[
            "add",
            "--title",
            "t4",
            "--priority",
            "high",
            "--test",
            r#"{"describe":"d","input":"i","output":"o"}"#,
        ],
    );

    let t1_id = t1["id"].as_i64().unwrap();
    run_json(&dir, &["claim", &t1_id.to_string(), "--agent", "agent-a"]);

    // --status
    let by_status = run_json(&dir, &["list", "--status", "in_progress"]);
    let arr = by_status.as_array().unwrap();
    assert_eq!(arr.len(), 1);
    assert_eq!(arr[0]["title"], "t1");

    // --tag
    let by_tag = run_json(&dir, &["list", "--tag", "alpha"]);
    let arr = by_tag.as_array().unwrap();
    let titles: Vec<&str> = arr.iter().map(|t| t["title"].as_str().unwrap()).collect();
    assert_eq!(titles.len(), 2);
    assert!(titles.contains(&"t1"));
    assert!(titles.contains(&"t3"));

    // --priority
    let by_priority = run_json(&dir, &["list", "--priority", "medium"]);
    let arr = by_priority.as_array().unwrap();
    assert_eq!(arr.len(), 1);
    assert_eq!(arr[0]["title"], "t3");

    // --executor
    let by_executor = run_json(&dir, &["list", "--executor", "agent-a"]);
    let arr = by_executor.as_array().unwrap();
    assert_eq!(arr.len(), 1);
    assert_eq!(arr[0]["title"], "t1");

    // --sort priority: urgent, high, medium, low (not alphabetical)
    let sorted = run_json(&dir, &["list", "--sort", "priority"]);
    let arr = sorted.as_array().unwrap();
    let titles: Vec<&str> = arr.iter().map(|t| t["title"].as_str().unwrap()).collect();
    assert_eq!(titles, vec!["t1", "t4", "t3", "t2"]);
}

/// Discovery must find the *closest* `.kanban/` walking up from cwd, and must
/// not merge with or fall through to a parent project's `.kanban/`.
#[test]
fn nested_project_discovery_child_wins() {
    let root = TempDir::new().unwrap();

    // init at the root and add a distinctive task there.
    init(&root);
    run_json(
        &root,
        &[
            "add",
            "--title",
            "parent task",
            "--priority",
            "low",
            "--test",
            r#"{"describe":"d","input":"i","output":"o"}"#,
        ],
    );

    // A separate, independently-initialized project nested inside the root's
    // directory tree.
    let child = root.path().join("child");
    std::fs::create_dir_all(&child).unwrap();
    run_json_at(&child, &["init"]);
    run_json_at(
        &child,
        &[
            "add",
            "--title",
            "child task",
            "--priority",
            "low",
            "--test",
            r#"{"describe":"d","input":"i","output":"o"}"#,
        ],
    );

    // Run `list` from an even deeper, un-initialized directory. Discovery
    // should walk up only as far as `child/.kanban`, not the parent's.
    let deeper = child.join("deeper");
    std::fs::create_dir_all(&deeper).unwrap();

    let listed = run_json_at(&deeper, &["list"]);
    let arr = listed.as_array().unwrap();
    let titles: Vec<&str> = arr.iter().map(|t| t["title"].as_str().unwrap()).collect();
    assert_eq!(titles, vec!["child task"]);
    assert!(!titles.contains(&"parent task"));
}

/// Commands must work from any subdirectory of an initialized project, not
/// just its root, by walking up to find the nearest `.kanban/`.
#[test]
fn runs_from_subdirectory_of_initialized_project() {
    let root = TempDir::new().unwrap();
    init(&root);
    let created = run_json(
        &root,
        &[
            "add",
            "--title",
            "root task",
            "--priority",
            "low",
            "--test",
            r#"{"describe":"d","input":"i","output":"o"}"#,
        ],
    );
    let id = created["id"].as_i64().unwrap();

    let sub = root.path().join("subdir");
    std::fs::create_dir_all(&sub).unwrap();

    let listed = run_json_at(&sub, &["list"]);
    let arr = listed.as_array().unwrap();
    assert_eq!(arr.len(), 1);
    assert_eq!(arr[0]["id"].as_i64().unwrap(), id);
    assert_eq!(arr[0]["title"], "root task");
}

/// `--pretty` is a global flag that must precede the subcommand. It should
/// produce indented, multi-line JSON, unlike the default compact output.
#[test]
fn pretty_flag_produces_indented_output() {
    let dir = TempDir::new().unwrap();
    init(&dir);

    let test_json = r#"{"describe":"d","input":"i","output":"o"}"#;

    // Compact (default) output: a single line of JSON plus one trailing
    // newline from `println!`.
    let compact_output = kanban(&dir)
        .args([
            "add",
            "--title",
            "t",
            "--priority",
            "low",
            "--test",
            test_json,
        ])
        .output()
        .unwrap();
    assert!(compact_output.status.success());
    let compact_stdout = String::from_utf8_lossy(&compact_output.stdout).to_string();
    assert_eq!(
        compact_stdout.matches('\n').count(),
        1,
        "compact JSON should have exactly one trailing newline, got: {compact_stdout:?}"
    );

    // Pretty output: `--pretty` must come before the subcommand.
    let pretty_output = kanban(&dir)
        .args([
            "--pretty",
            "add",
            "--title",
            "t2",
            "--priority",
            "low",
            "--test",
            test_json,
        ])
        .output()
        .unwrap();
    assert!(pretty_output.status.success());
    let pretty_stdout = String::from_utf8_lossy(&pretty_output.stdout).to_string();
    assert!(
        pretty_stdout.matches('\n').count() > 1,
        "pretty JSON should be multi-line, got: {pretty_stdout:?}"
    );
    // The indentation itself: a newline followed by leading whitespace.
    assert!(
        pretty_stdout.contains("\n ") || pretty_stdout.contains("\n\t"),
        "pretty JSON should contain indented lines, got: {pretty_stdout:?}"
    );
}

/// Running `init` a second time on an already-initialized project must
/// succeed (exit 0) and must not wipe existing data.
#[test]
fn init_twice_is_idempotent_and_preserves_data() {
    let dir = TempDir::new().unwrap();
    init(&dir);
    register(&dir, "agent-a");

    // Second init should still succeed.
    kanban(&dir).arg("init").assert().success();

    // The agent registered before the second init must still be present.
    let agents = run_json(&dir, &["agent", "list"]);
    let arr = agents.as_array().unwrap();
    let has_agent_a = arr.iter().any(|a| {
        a.get("name")
            .and_then(|n| n.as_str())
            .unwrap_or_else(|| a.as_str().unwrap())
            == "agent-a"
    });
    assert!(
        has_agent_a,
        "expected agent-a to survive a second init, got: {arr:?}"
    );
}

/// Every error must be `{"error": "..."}` JSON on stderr per this tool's
/// documented contract -- including clap's own parse-level failures (bad
/// argument types, missing required flags, unknown subcommands), which by
/// default would otherwise print clap's plain multi-line human-readable
/// text instead of going through the rest of the program's error handling.
#[test]
fn clap_parse_errors_are_still_json() {
    let dir = TempDir::new().unwrap();
    init(&dir);

    // Non-numeric id: fails clap's i64 value parser.
    let output = kanban(&dir).args(["show", "abc"]).output().unwrap();
    assert!(!output.status.success());
    assert_eq!(output.status.code(), Some(2));
    let stderr: Value = serde_json::from_slice(&output.stderr).unwrap_or_else(|e| {
        panic!(
            "stderr was not valid JSON: {e}\nstderr={}",
            String::from_utf8_lossy(&output.stderr)
        )
    });
    assert!(stderr["error"].as_str().unwrap().contains("invalid digit"));

    // Missing a required argument.
    let output = kanban(&dir).args(["add", "--title", "t"]).output().unwrap();
    assert!(!output.status.success());
    let stderr: Value = serde_json::from_slice(&output.stderr).unwrap_or_else(|e| {
        panic!(
            "stderr was not valid JSON: {e}\nstderr={}",
            String::from_utf8_lossy(&output.stderr)
        )
    });
    assert!(stderr["error"].as_str().unwrap().contains("required"));

    // Unknown subcommand.
    let output = kanban(&dir).args(["bogus-command"]).output().unwrap();
    assert!(!output.status.success());
    let stderr: Value = serde_json::from_slice(&output.stderr).unwrap_or_else(|e| {
        panic!(
            "stderr was not valid JSON: {e}\nstderr={}",
            String::from_utf8_lossy(&output.stderr)
        )
    });
    assert!(
        stderr["error"]
            .as_str()
            .unwrap()
            .contains("unrecognized subcommand")
    );
}

/// `--help`/`--version` are not errors and must remain clap's normal
/// human-readable plain text (exit 0), not JSON -- this test guards against
/// the JSON-error fix above accidentally over-broadening to cover these too.
#[test]
fn help_flag_remains_plain_text_not_json() {
    let dir = TempDir::new().unwrap();
    init(&dir);

    let output = kanban(&dir).arg("--help").output().unwrap();
    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("Usage:"));
    assert!(
        serde_json::from_str::<Value>(&stdout).is_err(),
        "--help output should not be JSON: {stdout:?}"
    );
}

/// `--version` must be a registered flag (clap's `#[derive(Parser)]` needs
/// the bare `version` keyword in `#[command(...)]` to auto-populate it from
/// Cargo.toml once any other field is set explicitly -- confirmed missing
/// entirely before that fix: clap reported "unexpected argument" instead of
/// printing a version, since it was never registered as a valid flag at
/// all). Not an error, so it must remain plain text (exit 0), not JSON.
#[test]
fn version_flag_is_registered_and_plain_text() {
    let dir = TempDir::new().unwrap();
    init(&dir);

    let output = kanban(&dir).arg("--version").output().unwrap();
    assert!(
        output.status.success(),
        "stdout={} stderr={}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("agent-kanban"));
    assert!(
        serde_json::from_str::<Value>(&stdout).is_err(),
        "--version output should not be JSON: {stdout:?}"
    );
}

/// `--pretty` must apply to error output too (a command-logic failure after
/// a successful parse), not just success output -- otherwise the two output
/// paths are inconsistent about honoring the flag.
#[test]
fn pretty_flag_applies_to_error_output_too() {
    let dir = TempDir::new().unwrap();
    init(&dir);

    let compact = kanban(&dir).args(["show", "999"]).output().unwrap();
    assert!(!compact.status.success());
    let compact_stderr = String::from_utf8_lossy(&compact.stderr).to_string();
    assert_eq!(
        compact_stderr.matches('\n').count(),
        1,
        "compact error JSON should have exactly one trailing newline, got: {compact_stderr:?}"
    );

    let pretty = kanban(&dir)
        .args(["--pretty", "show", "999"])
        .output()
        .unwrap();
    assert!(!pretty.status.success());
    let pretty_stderr = String::from_utf8_lossy(&pretty.stderr).to_string();
    assert!(
        pretty_stderr.matches('\n').count() > 1,
        "pretty error JSON should be multi-line, got: {pretty_stderr:?}"
    );
    let parsed: Value = serde_json::from_str(&pretty_stderr).unwrap();
    assert_eq!(parsed["error"], "task 999 not found");
}

/// Every value that flows into a SQL statement (title, tags, filter values)
/// is bound via parameters rather than string-concatenated -- this proves
/// that empirically with adversarial-looking input, rather than relying on
/// "the code looks parameterized" from reading it. A naively-concatenated
/// query would corrupt/misbehave on these; a properly parameterized one
/// treats them as inert data.
#[test]
fn sql_special_characters_are_treated_as_inert_data() {
    let dir = TempDir::new().unwrap();
    init(&dir);

    let evil_title = "robert'); DROP TABLE tasks; --";
    let evil_tag = "'; DROP TABLE agents; --";
    let created = run_json(
        &dir,
        &[
            "add",
            "--title",
            evil_title,
            "--priority",
            "low",
            "--tag",
            evil_tag,
            "--test",
            r#"{"describe":"d","input":"i","output":"o"}"#,
        ],
    );
    assert_eq!(created["title"], evil_title);
    let id = created["id"].as_i64().unwrap();

    // Filtering by the exact adversarial tag value must find it, and the
    // tables must obviously still exist (both DROP TABLE attempts, if they
    // were ever interpreted as SQL rather than data, would have destroyed
    // the schema and every subsequent command in this test would fail).
    let by_tag = run_json(&dir, &["list", "--tag", evil_tag]);
    let arr = by_tag.as_array().unwrap();
    assert_eq!(arr.len(), 1);
    assert_eq!(arr[0]["id"].as_i64().unwrap(), id);

    let shown = run_json(&dir, &["show", &id.to_string()]);
    assert_eq!(shown["title"], evil_title);

    // Prove the tables are intact by continuing to use them normally.
    run_json(&dir, &["agent", "register", "alice"]);
    let all = run_json(&dir, &["list"]);
    assert_eq!(all.as_array().unwrap().len(), 1);
}

/// `list`'s filters and `--sort` must work correctly when combined in a
/// single call, not just independently -- the dynamic query builds a
/// `WHERE ... ORDER BY ...` clause from whichever flags are present.
#[test]
fn list_combines_filter_and_sort_in_one_call() {
    let dir = TempDir::new().unwrap();
    init(&dir);

    for (title, priority, status) in [
        ("backlog-low", "low", "backlog"),
        ("todo-urgent", "urgent", "todo"),
        ("todo-high", "high", "todo"),
        ("todo-low", "low", "todo"),
    ] {
        let created = run_json(
            &dir,
            &[
                "add",
                "--title",
                title,
                "--priority",
                priority,
                "--test",
                r#"{"describe":"d","input":"i","output":"o"}"#,
            ],
        );
        if status != "todo" {
            let id = created["id"].as_i64().unwrap().to_string();
            run_json(&dir, &["move", &id, "--status", status]);
        }
    }

    // --status todo (excludes backlog-low) AND --sort priority together:
    // must both filter out the backlog task and order the remaining three
    // by severity, not alphabetically and not unfiltered.
    let result = run_json(&dir, &["list", "--status", "todo", "--sort", "priority"]);
    let arr = result.as_array().unwrap();
    let titles: Vec<&str> = arr.iter().map(|t| t["title"].as_str().unwrap()).collect();
    assert_eq!(titles, vec!["todo-urgent", "todo-high", "todo-low"]);
}

/// `--table` on an array result (`list`) renders an aligned table with
/// uppercase column headers, not JSON.
#[test]
fn table_flag_renders_list_as_aligned_table() {
    let dir = TempDir::new().unwrap();
    init(&dir);
    run_json(
        &dir,
        &[
            "add",
            "--title",
            "fix bug",
            "--priority",
            "high",
            "--test",
            r#"{"describe":"d","input":"i","output":"o"}"#,
        ],
    );

    let output = kanban(&dir).args(["--table", "list"]).output().unwrap();
    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("TITLE"));
    assert!(stdout.contains("PRIORITY"));
    assert!(stdout.contains("fix bug"));
    assert!(stdout.contains("high"));
    assert!(
        serde_json::from_str::<Value>(&stdout).is_err(),
        "--table output should not be JSON: {stdout:?}"
    );
}

/// `--table` on a single-object result (`show`) renders a FIELD/VALUE table.
#[test]
fn table_flag_renders_single_object_as_key_value_table() {
    let dir = TempDir::new().unwrap();
    init(&dir);
    let created = run_json(
        &dir,
        &[
            "add",
            "--title",
            "fix bug",
            "--priority",
            "high",
            "--test",
            r#"{"describe":"d","input":"i","output":"o"}"#,
        ],
    );
    let id = created["id"].as_i64().unwrap().to_string();

    let output = kanban(&dir)
        .args(["--table", "show", &id])
        .output()
        .unwrap();
    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("FIELD"));
    assert!(stdout.contains("VALUE"));
    assert!(stdout.contains("title"));
    assert!(stdout.contains("fix bug"));
}

/// `status` returns a flat object, same shape as `show`/`add`, so `--table`
/// renders it through the same FIELD/VALUE path -- including the nested
/// `agents` object, which must render as inline compact JSON within its
/// cell rather than a nested table.
#[test]
fn table_flag_renders_status_as_key_value_table_with_inline_agents() {
    let dir = TempDir::new().unwrap();
    init(&dir);
    register(&dir, "alice");

    let output = kanban(&dir).args(["--table", "status"]).output().unwrap();
    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("FIELD"));
    assert!(stdout.contains("VALUE"));
    assert!(stdout.contains("total"));
    assert!(stdout.contains("agents"));
    assert!(stdout.contains(r#"{"alice":0}"#));
}

/// `--table` on an empty `list` result prints a friendly message rather
/// than an empty/malformed table (there are no rows to infer columns from).
#[test]
fn table_flag_renders_empty_list_as_friendly_message() {
    let dir = TempDir::new().unwrap();
    init(&dir);

    kanban(&dir)
        .args(["--table", "list"])
        .assert()
        .success()
        .stdout(contains("no results"));
}

/// `--table` applies to error output too, consistently with `--pretty`.
#[test]
fn table_flag_renders_error_as_table() {
    let dir = TempDir::new().unwrap();
    init(&dir);

    let output = kanban(&dir)
        .args(["--table", "show", "999"])
        .output()
        .unwrap();
    assert!(!output.status.success());
    let stdout_and_stderr = format!(
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(stdout_and_stderr.contains("error"));
    assert!(stdout_and_stderr.contains("not found"));
    assert!(
        serde_json::from_str::<Value>(&stdout_and_stderr).is_err(),
        "--table error output should not be JSON: {stdout_and_stderr:?}"
    );
}

/// `--pretty` and `--table` are mutually exclusive output modes; combining
/// them must be a clean, clap-level usage error (still JSON, per the
/// clap-parse-error contract established earlier).
#[test]
fn pretty_and_table_are_mutually_exclusive() {
    let dir = TempDir::new().unwrap();
    init(&dir);

    let output = kanban(&dir)
        .args(["--pretty", "--table", "list"])
        .output()
        .unwrap();
    assert!(!output.status.success());
    assert_eq!(output.status.code(), Some(2));
    let stderr: Value = serde_json::from_slice(&output.stderr).unwrap();
    assert!(
        stderr["error"]
            .as_str()
            .unwrap()
            .contains("cannot be used with")
    );
}

/// `agent-kanban init` must stamp the schema version via `PRAGMA user_version`,
/// not leave it at `SQLite`'s default of 0.
#[test]
fn init_sets_schema_version_pragma() {
    let dir = TempDir::new().unwrap();
    init(&dir);

    let db_path = dir.path().join(".kanban").join("board.db");
    let conn = rusqlite::Connection::open(&db_path).unwrap();
    let version: i32 = conn
        .query_row("PRAGMA user_version", [], |row| row.get(0))
        .unwrap();
    assert_eq!(version, 1);
}

/// Opening a project whose schema version is newer than this binary
/// understands must fail cleanly, rather than silently misinterpreting a
/// schema shape it doesn't actually know about.
#[test]
fn opening_project_with_newer_schema_version_fails_cleanly() {
    let dir = TempDir::new().unwrap();
    init(&dir);

    let db_path = dir.path().join(".kanban").join("board.db");
    let conn = rusqlite::Connection::open(&db_path).unwrap();
    conn.execute_batch("PRAGMA user_version = 999;").unwrap();
    drop(conn);

    kanban(&dir)
        .args(["agent", "list"])
        .assert()
        .failure()
        .stderr(contains("newer than this build"));
}

/// `status` reports per-status task counts (all five columns, even at zero)
/// and per-agent claimed-task counts (all registered agents, even at zero),
/// exercised end to end through the real binary and a real board.
#[test]
fn status_reports_task_counts_and_agent_workload() {
    let dir = TempDir::new().unwrap();
    init(&dir);
    register(&dir, "alice");
    register(&dir, "bob");
    register(&dir, "carol");

    let test_json = r#"{"describe":"d","input":"i","output":"o"}"#;
    for title in ["t1", "t2", "t3"] {
        run_json(
            &dir,
            &[
                "add",
                "--title",
                title,
                "--priority",
                "low",
                "--test",
                test_json,
            ],
        );
    }
    kanban(&dir)
        .args(["claim", "1", "--agent", "alice"])
        .assert()
        .success();
    kanban(&dir)
        .args(["claim", "2", "--agent", "bob"])
        .assert()
        .success();
    kanban(&dir)
        .args(["move", "2", "--status", "done"])
        .assert()
        .success();

    let status = run_json(&dir, &["status"]);
    assert_eq!(status["backlog"], 0);
    assert_eq!(status["todo"], 1);
    assert_eq!(status["in_progress"], 1);
    assert_eq!(status["review"], 0);
    assert_eq!(status["done"], 1);
    assert_eq!(status["total"], 3);
    assert_eq!(status["agents"]["alice"], 1);
    assert_eq!(status["agents"]["bob"], 1);
    assert_eq!(status["agents"]["carol"], 0);
}