qctl 0.4.7

Control in-repo YAML work queues
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
//! Binary contract: init, check, add, start, archive, park, promote.

mod common;

use common::{LedgerDir, MINIMAL, qctl, stderr, stdout};
use indoc::indoc;

#[test]
fn init_writes_ledger_without_schema_copy() {
    let dir = LedgerDir::empty();
    let output = qctl(&["init", "-p", "omx", "-f", dir.path.to_str().unwrap()]);
    assert!(output.status.success(), "{}", stderr(&output));
    let body = dir.read();
    assert!(body.contains("prefix: OMX"));
    assert!(body.contains("horizon: []"));
    assert!(body.contains("$schema="));
    assert!(!dir.parent().join("tasks.schema.json").exists());
}

#[test]
fn init_refuses_overwrite_without_force() {
    let dir = LedgerDir::empty();
    dir.write(MINIMAL);
    let output = qctl(&["init", "-p", "QCTL", "-f", dir.path.to_str().unwrap()]);
    assert!(!output.status.success());
    assert!(stderr(&output).contains("already exists"));
}

#[test]
fn check_accepts_own_repo_shape() {
    let dir = LedgerDir::empty();
    dir.write(MINIMAL);
    let output = qctl(&["check", "-f", dir.path.to_str().unwrap(), "--no-git"]);
    assert!(output.status.success(), "{}", stderr(&output));
    assert!(stdout(&output).contains("ok"));
}

#[test]
fn a_schema_error_from_check_names_its_line() {
    let (ok, complaint) = common::check(&common::queued(indoc! {"
        - id: Q-1
          title: t
          scope: s
          outcome: o
          blocked_by: []
          acceptance: [a]
    "}));
    assert!(!ok, "{complaint}");
    assert!(
        complaint.contains("tasks.yaml:5:9: /queue/0/id:"),
        "{complaint}"
    );
}

#[test]
fn a_value_error_from_a_verb_names_its_line() {
    let dir = LedgerDir::empty();
    dir.write(&MINIMAL.replace("prefix: QCTL", "prefix: q"));
    let output = qctl(&["status", "-f", dir.path.to_str().unwrap()]);
    assert!(!output.status.success());
    assert!(
        stderr(&output).contains("tasks.yaml:2:9: prefix:"),
        "{}",
        stderr(&output)
    );
}

#[test]
fn a_duplicate_key_is_refused_on_its_line() {
    let dir = LedgerDir::empty();
    dir.write(&common::queued(indoc! {"
        - id: QCTL-001
          title: t
          title: again
          scope: s
          outcome: o
          blocked_by: []
          acceptance: [a]
    "}));
    let output = qctl(&["status", "-f", dir.path.to_str().unwrap()]);
    assert!(!output.status.success());
    assert!(
        stderr(&output).contains("tasks.yaml:7:"),
        "{}",
        stderr(&output)
    );
}

#[test]
fn check_accepts_archive_notes() {
    let dir = LedgerDir::empty();
    dir.write(indoc! {"
        schema_version: 4
        prefix: QCTL
        active: null
        queue: []
        archive:
          - id: QCTL-001
            title: done
            scope: s
            completed: 2026-08-17T09:12:00
            outcome: o
            evidence: [landed]
            notes:
              - Keep the context that would not fit in evidence.
    "});
    let output = qctl(&["check", "-f", dir.path.to_str().unwrap(), "--no-git"]);
    assert!(output.status.success(), "{}", stderr(&output));
}

/// The ledger declares its zone, so a stamp is already local and `show` must not
/// shift it — only separate the day from the time. This stamp sits late in the
/// evening on purpose: a version that converted it, in either direction, would
/// name a different day and not merely a different hour.
#[test]
fn show_reads_a_stamp_without_moving_it() {
    let dir = LedgerDir::empty();
    dir.write(indoc! {"
        schema_version: 4
        prefix: QCTL
        style:
          timezone: \"-03:00\"
        active: null
        queue: []
        archive:
          - id: QCTL-001
            title: Shipped late
            scope: qctl
            completed: 2026-08-16T23:08:28
            outcome: It shipped.
            evidence: [The tag exists.]
    "});
    let output = qctl(&["show", "QCTL-001", "-f", dir.path.to_str().unwrap()]);
    assert!(output.status.success(), "{}", stderr(&output));
    assert_eq!(
        stdout(&output).trim_end(),
        "QCTL-001  Shipped late  (archived 2026-08-16 23:08:28)"
    );
}

/// Agent and CI captures pipe every stream and set no `COLUMNS`, so the fallback
/// width is what keeps `show` inside a readable line there.
#[test]
fn piped_show_without_columns_stays_within_80_columns() {
    let dir = LedgerDir::empty();
    dir.write(indoc! {"
        schema_version: 4
        prefix: QCTL
        active: null
        queue: []
        archive:
          - id: QCTL-001
            title: Keep every piped line inside the fallback width even when a title runs far past what one line holds
            scope: qctl
            completed: 2026-08-16T23:08:28
            outcome: It shipped.
            evidence: [The tag exists.]
    "});
    let output = std::process::Command::new(env!("CARGO_BIN_EXE_qctl"))
        .args(["show", "QCTL-001", "-f", dir.path.to_str().unwrap()])
        .env_remove("TASKS_LEDGER")
        .env_remove("COLUMNS")
        .output()
        .expect("spawn qctl");
    assert!(output.status.success(), "{}", stderr(&output));
    let out = stdout(&output);
    assert!(out.lines().count() > 1, "{out}");
    assert!(out.lines().all(|line| line.chars().count() <= 80), "{out}");
}

/// The zone a stamp is written in comes from the ledger, and the only way to see
/// that is to read the stamp back as the declared zone and land on now. Written
/// in UTC instead, it would be three hours out.
#[test]
fn archive_stamps_in_the_zone_the_ledger_declares() {
    let dir = LedgerDir::empty();
    dir.write(indoc! {"
        schema_version: 4
        prefix: QCTL
        style:
          timezone: \"-03:00\"
        active: QCTL-001
        queue:
          - id: QCTL-001
            title: About to close
            scope: qctl
            outcome: Something is true.
            blocked_by: []
            acceptance: [It holds.]
        archive: []
    "});
    let archived = qctl(&[
        "archive",
        "QCTL-001",
        "-f",
        dir.path.to_str().unwrap(),
        "-e",
        "It shipped.",
    ]);
    assert!(archived.status.success(), "{}", stderr(&archived));

    let body = dir.read();
    let stamp = body
        .lines()
        .find_map(|line| line.trim().strip_prefix("completed: "))
        .expect("a stamp");
    let written = time::PrimitiveDateTime::parse(
        stamp,
        time::macros::format_description!("[year]-[month]-[day]T[hour]:[minute]:[second]"),
    )
    .unwrap_or_else(|error| panic!("{stamp}: {error}"))
    .assume_offset(time::macros::offset!(-3));
    let drift = time::OffsetDateTime::now_utc() - written;
    assert!(
        drift.abs() < time::Duration::seconds(30),
        "{stamp} read as -03:00 is {drift} from now, so it was not written in that zone"
    );
}

/// `fmt --check` is for a hook: it writes nothing, exits non-zero, and says
/// which line to look at rather than only that something is out of style.
#[test]
fn fmt_check_names_the_line_and_writes_nothing() {
    let dir = LedgerDir::empty();
    let untidy = indoc! {"
        schema_version: 4
        prefix: QCTL
        active: null
        queue: []
        archive: []
        horizon: []


    "};
    dir.write(untidy);
    let output = qctl(&["fmt", "--check", "-f", dir.path.to_str().unwrap()]);
    assert!(!output.status.success(), "accepted an untidy ledger");
    assert!(
        stderr(&output).contains("is not in its declared style"),
        "{}",
        stderr(&output)
    );
    assert_eq!(dir.read(), untidy, "--check wrote to the file");

    let fixed = qctl(&["fmt", "-f", dir.path.to_str().unwrap()]);
    assert!(fixed.status.success(), "{}", stderr(&fixed));
    assert!(dir.read().ends_with("horizon: []\n"));
    assert!(
        qctl(&["fmt", "--check", "-f", dir.path.to_str().unwrap()])
            .status
            .success()
    );
}

/// A comment directly above a key belongs to that list and moves with it. One
/// with a blank line under it belongs to no list, so the lists trade places
/// around it and it stays where it was written.
#[test]
fn fmt_moves_lists_around_a_comment_that_belongs_to_none() {
    let dir = LedgerDir::empty();
    let orphaned = indoc! {"
        schema_version: 4
        prefix: QCTL
        style:
          section_order: [queue, horizon, archive]
        active: null
        queue: []

        # A note with a blank line under it, so it sits between the lists.

        archive: []
        horizon: []
    "};
    dir.write(orphaned);
    let output = qctl(&["fmt", "-f", dir.path.to_str().unwrap()]);
    assert!(output.status.success(), "{}", stderr(&output));
    let expected = indoc! {"
        schema_version: 4
        prefix: QCTL
        style:
          section_order: [queue, horizon, archive]
        active: null
        queue: []

        # A note with a blank line under it, so it sits between the lists.

        horizon: []
        archive: []
    "};
    assert_eq!(dir.read(), expected);
}

#[test]
fn check_rejects_unknown_field() {
    let dir = LedgerDir::empty();
    dir.write(indoc! {"
        schema_version: 4
        prefix: QCTL
        active: null
        queue: []
        archive: []
        nope: true
    "});
    let output = qctl(&["check", "-f", dir.path.to_str().unwrap(), "--no-git"]);
    assert!(!output.status.success());
}

#[test]
fn add_start_archive_round_trip() {
    let dir = LedgerDir::empty();
    assert!(
        qctl(&["init", "-p", "QCTL", "-f", dir.path.to_str().unwrap()])
            .status
            .success()
    );

    let add = qctl(&[
        "add",
        "-f",
        dir.path.to_str().unwrap(),
        "-t",
        "First",
        "-s",
        "qctl",
        "-o",
        "done",
        "-a",
        "shipped",
    ]);
    assert!(add.status.success(), "{}", stderr(&add));
    assert_eq!(stdout(&add).trim(), "QCTL-001");

    let start = qctl(&["start", "QCTL-001", "-f", dir.path.to_str().unwrap()]);
    assert!(start.status.success(), "{}", stderr(&start));

    let check = qctl(&["check", "-f", dir.path.to_str().unwrap(), "--no-git"]);
    assert!(check.status.success(), "{}", stderr(&check));

    let archive = qctl(&[
        "archive",
        "QCTL-001",
        "-f",
        dir.path.to_str().unwrap(),
        "-e",
        "landed",
    ]);
    assert!(archive.status.success(), "{}", stderr(&archive));

    let after = qctl(&["check", "-f", dir.path.to_str().unwrap(), "--no-git"]);
    assert!(after.status.success(), "{}", stderr(&after));
    let body = dir.read();
    assert!(body.contains("disposition: completed"));
    assert!(body.contains("QCTL-001"));
}

#[test]
fn add_writes_notes_blockers_plan_and_links() {
    let dir = LedgerDir::empty();
    assert!(
        qctl(&["init", "-p", "QCTL", "-f", dir.path.to_str().unwrap()])
            .status
            .success()
    );
    let first = qctl(&[
        "add",
        "-f",
        dir.path.to_str().unwrap(),
        "-t",
        "First",
        "-s",
        "qctl",
        "-o",
        "done",
        "-a",
        "shipped",
    ]);
    assert!(first.status.success(), "{}", stderr(&first));
    dir.plant("docs/plan.md", "# Plan\n");
    let second = qctl(&[
        "add",
        "-f",
        dir.path.to_str().unwrap(),
        "-t",
        "Second",
        "-s",
        "qctl",
        "-o",
        "done",
        "-a",
        "shipped",
        "--note",
        "Why this exists.",
        "--blocked-by",
        "QCTL-001",
        "--plan",
        "docs/plan.md",
        "--link",
        "https://example.com/x",
        "--after",
        "QCTL-001",
    ]);
    assert!(second.status.success(), "{}", stderr(&second));
    let body = dir.read();
    assert!(
        body.contains("notes:") && body.contains("Why this exists."),
        "{body}"
    );
    assert!(
        body.contains("blocked_by:\n      - QCTL-001") || body.contains("blocked_by: [QCTL-001]"),
        "{body}"
    );
    assert!(body.contains("plan: docs/plan.md"), "{body}");
    assert!(body.contains("https://example.com/x"), "{body}");
    let check = qctl(&["check", "-f", dir.path.to_str().unwrap(), "--no-git"]);
    assert!(check.status.success(), "{}", stderr(&check));
}

#[test]
fn add_refuses_a_blocker_that_would_not_sit_earlier() {
    let dir = LedgerDir::empty();
    dir.write(indoc! {"
        schema_version: 4
        prefix: QCTL
        active: QCTL-001
        queue:
          - id: QCTL-001
            title: First
            scope: s
            outcome: o
            blocked_by: []
            acceptance: [It holds.]
          - id: QCTL-002
            title: Second
            scope: s
            outcome: o
            blocked_by: []
            acceptance: [It holds.]
        archive: []
        horizon: []
    "});
    let output = qctl(&[
        "add",
        "-f",
        dir.path.to_str().unwrap(),
        "-t",
        "Third",
        "-s",
        "s",
        "-o",
        "o",
        "-a",
        "a",
        "--before",
        "QCTL-002",
        "--blocked-by",
        "QCTL-002",
    ]);
    assert!(!output.status.success());
    assert!(
        stderr(&output).contains("is not earlier"),
        "{}",
        stderr(&output)
    );
}

#[test]
fn add_refuses_to_become_queue_head_while_active_is_set() {
    let dir = LedgerDir::empty();
    dir.write(indoc! {"
        schema_version: 4
        prefix: QCTL
        active: QCTL-001
        queue:
          - id: QCTL-001
            title: First
            scope: s
            outcome: o
            blocked_by: []
            acceptance: [It holds.]
        archive: []
        horizon: []
    "});
    let output = qctl(&[
        "add",
        "-f",
        dir.path.to_str().unwrap(),
        "-t",
        "Ahead",
        "-s",
        "s",
        "-o",
        "o",
        "-a",
        "a",
        "--before",
        "QCTL-001",
    ]);
    assert!(!output.status.success());
    assert!(stderr(&output).contains("queue[0]"), "{}", stderr(&output));
}

#[test]
fn promote_refuses_a_queued_id() {
    let dir = LedgerDir::empty();
    dir.write(indoc! {"
        schema_version: 4
        prefix: QCTL
        active: QCTL-001
        queue:
          - id: QCTL-001
            title: First
            scope: s
            outcome: o
            blocked_by: []
            acceptance: [It holds.]
        archive: []
        horizon: []
    "});
    let output = qctl(&[
        "promote",
        "QCTL-001",
        "-f",
        dir.path.to_str().unwrap(),
        "-a",
        "a",
    ]);
    assert!(!output.status.success());
    assert!(
        stderr(&output).contains("not on the horizon"),
        "{}",
        stderr(&output)
    );
}

#[test]
fn promote_keeps_active_on_the_queue_head() {
    let dir = LedgerDir::empty();
    dir.write(indoc! {"
        schema_version: 4
        prefix: QCTL
        active: QCTL-001
        queue:
          - id: QCTL-001
            title: First
            scope: s
            outcome: o
            blocked_by: []
            acceptance: [It holds.]
        archive: []
        horizon:
          - id: QCTL-002
            title: Parked
            scope: s
            outcome: o
            kind: research
            open: missing
    "});
    let output = qctl(&[
        "promote",
        "QCTL-002",
        "-f",
        dir.path.to_str().unwrap(),
        "-a",
        "It holds.",
    ]);
    assert!(output.status.success(), "{}", stderr(&output));
    let body = dir.read();
    assert!(body.contains("active: QCTL-001"), "{body}");
    assert!(!body.contains("kind: research"), "{body}");
    let check = qctl(&["check", "-f", dir.path.to_str().unwrap(), "--no-git"]);
    assert!(check.status.success(), "{}", stderr(&check));
}

#[test]
fn start_refuses_blocked_or_horizon() {
    let dir = LedgerDir::empty();
    dir.write(indoc! {"
        schema_version: 4
        prefix: QCTL
        active: null
        queue:
          - id: QCTL-002
            title: blocked
            scope: s
            outcome: o
            blocked_by: [QCTL-001]
            acceptance: [a]
          - id: QCTL-001
            title: first
            scope: s
            outcome: o
            blocked_by: []
            acceptance: [a]
        archive: []
        horizon:
          - id: QCTL-009
            title: later
            scope: s
            outcome: o
            kind: research
            open: unknown
    "});
    let blocked = qctl(&["start", "QCTL-002", "-f", dir.path.to_str().unwrap()]);
    assert!(!blocked.status.success());
    assert!(stderr(&blocked).contains("blocked"));

    let horizon = qctl(&["start", "QCTL-009", "-f", dir.path.to_str().unwrap()]);
    assert!(!horizon.status.success());
    assert!(stderr(&horizon).contains("not queued"));
}

#[test]
fn instructions_prints_the_installed_contract_exactly() {
    let output = qctl(&["instructions"]);
    assert!(output.status.success(), "{}", stderr(&output));
    assert_eq!(output.stderr, &[] as &[u8]);
    let expected =
        std::fs::read(std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/instructions.md"))
            .unwrap();
    assert_eq!(output.stdout, expected);
}

#[test]
fn bundled_skill_names_the_package_version() {
    let skill = std::fs::read_to_string(
        std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("skills/qctl/SKILL.md"),
    )
    .unwrap();
    let version = skill
        .lines()
        .find_map(|line| line.strip_prefix("version: "))
        .unwrap_or_else(|| panic!("skill has no version:\n{skill}"));
    assert_eq!(version, env!("CARGO_PKG_VERSION"));
}

#[test]
fn status_lists_horizon() {
    let dir = LedgerDir::empty();
    dir.write(indoc! {"
        schema_version: 4
        prefix: QCTL
        active: QCTL-001
        queue:
          - id: QCTL-001
            title: now
            scope: s
            outcome: o
            blocked_by: []
            acceptance: [a]
        archive: []
        horizon:
          - id: QCTL-008
            title: later
            scope: s
            outcome: o
            kind: evaluation
            open: wait
    "});
    let output = qctl(&["status", "-f", dir.path.to_str().unwrap()]);
    assert!(output.status.success(), "{}", stderr(&output));
    let text = stdout(&output);
    assert!(text.contains("QCTL-001"));
    assert!(text.contains("QCTL-008"));
    assert!(text.contains("evaluation"));
}

#[test]
fn park_demotes_a_queued_row_and_writes_a_missing_horizon_key() {
    let dir = LedgerDir::empty();
    dir.write(indoc! {"
        schema_version: 4
        prefix: QCTL
        active: QCTL-001
        queue:
          - id: QCTL-001
            title: later
            scope: s
            outcome: o
            blocked_by: []
            acceptance: [It holds.]
        archive: []
    "});
    let output = qctl(&[
        "park",
        "QCTL-001",
        "-f",
        dir.path.to_str().unwrap(),
        "-k",
        "research",
        "-O",
        "wait",
    ]);
    assert!(output.status.success(), "{}", stderr(&output));
    let body = dir.read();
    assert!(body.contains("horizon:"), "{body}");
    assert!(body.contains("kind: research"), "{body}");
    assert!(body.contains("active: null"), "{body}");
    assert!(!body.contains("acceptance:"), "{body}");
}

#[test]
fn add_refuses_a_plan_that_is_not_a_file() {
    let dir = LedgerDir::empty();
    dir.write(MINIMAL);
    let output = qctl(&[
        "add",
        "-f",
        dir.path.to_str().unwrap(),
        "-t",
        "t",
        "-s",
        "s",
        "-o",
        "o",
        "-a",
        "a",
        "--plan",
        "docs/nope.md",
    ]);
    assert!(!output.status.success());
    assert!(
        stderr(&output).contains("missing plan docs/nope.md"),
        "{}",
        stderr(&output)
    );
    assert_eq!(dir.read(), MINIMAL);
}

#[test]
fn add_refuses_an_empty_plan() {
    let dir = LedgerDir::empty();
    dir.write(MINIMAL);
    let output = qctl(&[
        "add",
        "-f",
        dir.path.to_str().unwrap(),
        "-t",
        "t",
        "-s",
        "s",
        "-o",
        "o",
        "-a",
        "a",
        "--plan",
        "",
    ]);
    assert!(!output.status.success());
    assert!(
        stderr(&output).contains("--plan needs a path"),
        "{}",
        stderr(&output)
    );
    assert_eq!(dir.read(), MINIMAL);
}

#[test]
fn add_refuses_a_plan_outside_the_repository() {
    let dir = LedgerDir::empty();
    dir.write(MINIMAL);
    let output = qctl(&[
        "add",
        "-f",
        dir.path.to_str().unwrap(),
        "-t",
        "t",
        "-s",
        "s",
        "-o",
        "o",
        "-a",
        "a",
        "--plan",
        "../elsewhere.md",
    ]);
    assert!(!output.status.success());
    assert!(
        stderr(&output).contains("must stay inside the repository"),
        "{}",
        stderr(&output)
    );
    assert_eq!(dir.read(), MINIMAL);
}

#[test]
fn add_refuses_a_plan_that_is_not_markdown() {
    let dir = LedgerDir::empty();
    dir.write(MINIMAL);
    dir.plant("docs/plan.txt", "not markdown\n");
    let output = qctl(&[
        "add",
        "-f",
        dir.path.to_str().unwrap(),
        "-t",
        "t",
        "-s",
        "s",
        "-o",
        "o",
        "-a",
        "a",
        "--plan",
        "docs/plan.txt",
    ]);
    assert!(!output.status.success());
    assert!(
        stderr(&output).contains("must be a markdown document"),
        "{}",
        stderr(&output)
    );
    assert_eq!(dir.read(), MINIMAL);
}

#[test]
fn add_accepts_a_plan_whose_name_contains_dotdot() {
    let dir = LedgerDir::empty();
    dir.write(MINIMAL);
    dir.plant("docs/foo..bar.md", "# Plan\n");
    let output = qctl(&[
        "add",
        "-f",
        dir.path.to_str().unwrap(),
        "-t",
        "t",
        "-s",
        "s",
        "-o",
        "o",
        "-a",
        "a",
        "--plan",
        "docs/foo..bar.md",
    ]);
    assert!(output.status.success(), "{}", stderr(&output));
    let check = qctl(&["check", "-f", dir.path.to_str().unwrap(), "--no-git"]);
    assert!(check.status.success(), "{}", stderr(&check));
    assert!(dir.read().contains("plan: docs/foo..bar.md"));
}

#[test]
fn add_to_an_empty_queue_does_not_invent_before() {
    let dir = LedgerDir::empty();
    dir.write(indoc! {"
        schema_version: 4
        prefix: QCTL
        active: QCTL-099
        queue: []
        archive: []
        horizon: []
    "});
    let output = qctl(&[
        "add",
        "-f",
        dir.path.to_str().unwrap(),
        "-t",
        "t",
        "-s",
        "s",
        "-o",
        "o",
        "-a",
        "a",
    ]);
    assert!(output.status.success(), "{}", stderr(&output));
    assert!(!stderr(&output).contains("--before"), "{}", stderr(&output));
    assert!(dir.read().contains("QCTL-001"));
}

#[test]
fn status_and_check_share_typed_json_output() {
    let dir = LedgerDir::empty();
    dir.write(indoc! {"
        schema_version: 4
        prefix: QCTL
        active: QCTL-001
        queue:
          - id: QCTL-001
            title: now
            scope: qctl
            outcome: done
            blocked_by: []
            acceptance: [shipped]
        archive: []
        horizon:
          - id: QCTL-002
            title: later
            scope: qctl
            outcome: mapped
            kind: research
            open: missing fact
    "});
    let path = dir.path.to_str().unwrap();

    let status = qctl(&["status", "-f", path, "--format", "json"]);
    assert!(status.status.success(), "{}", stderr(&status));
    assert_eq!(status.stderr, &[] as &[u8]);
    assert!(!status.stdout.contains(&b'\x1b'));
    let status_json: serde_json::Value = serde_json::from_slice(&status.stdout).unwrap();
    assert_eq!(status_json["type"], "status");
    assert_eq!(status_json["ledger"]["active"], "QCTL-001");
    assert_eq!(status_json["ledger"]["queue"][0]["title"], "now");
    assert_eq!(status_json["ledger"]["horizon"][0]["kind"], "research");

    let check = qctl(&["check", "-f", path, "--no-git", "--format", "json"]);
    assert!(check.status.success(), "{}", stderr(&check));
    assert_eq!(check.stderr, &[] as &[u8]);
    let check_json: serde_json::Value = serde_json::from_slice(&check.stdout).unwrap();
    assert_eq!(check_json["type"], "check");
    assert_eq!(check_json["problems"], serde_json::json!([]));
}

#[test]
fn failed_check_is_a_json_problem_array_on_stdout() {
    let dir = LedgerDir::empty();
    dir.write(indoc! {"
        schema_version: 4
        prefix: QCTL
        active: null
        queue: []
        archive: []
        nope: true
    "});
    let output = qctl(&[
        "check",
        "-f",
        dir.path.to_str().unwrap(),
        "--no-git",
        "--format",
        "json",
    ]);
    assert!(!output.status.success());
    assert_eq!(output.stderr, &[] as &[u8]);
    assert!(!output.stdout.contains(&b'\x1b'));
    let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(report["type"], "check");
    let problems = report["problems"].as_array().unwrap();
    assert!(!problems.is_empty());
    assert!(
        problems
            .iter()
            .any(|problem| problem.as_str().unwrap().contains("nope"))
    );
}

#[test]
fn quiet_suppresses_only_successful_human_output() {
    let dir = LedgerDir::empty();
    dir.write(MINIMAL);
    let path = dir.path.to_str().unwrap();

    let quiet = qctl(&["status", "-f", path, "--quiet"]);
    assert!(quiet.status.success(), "{}", stderr(&quiet));
    assert_eq!(quiet.stdout, &[] as &[u8]);
    assert_eq!(quiet.stderr, &[] as &[u8]);

    let json = qctl(&["status", "-f", path, "--quiet", "--format", "json"]);
    assert!(json.status.success(), "{}", stderr(&json));
    assert_eq!(json.stderr, &[] as &[u8]);
    assert_eq!(
        serde_json::from_slice::<serde_json::Value>(&json.stdout).unwrap()["type"],
        "status"
    );

    let failed = qctl(&["show", "QCTL-999", "-f", path, "--quiet"]);
    assert!(!failed.status.success());
    assert_eq!(failed.stdout, &[] as &[u8]);
    assert!(stderr(&failed).contains("no task QCTL-999"));
}

#[test]
fn colorless_flags_render_the_same_document() {
    let dir = LedgerDir::empty();
    dir.write(MINIMAL);
    let path = dir.path.to_str().unwrap();
    let color = qctl(&["status", "-f", path, "--color", "never"]);
    let no_color = qctl(&["status", "-f", path, "--no-color"]);
    assert!(color.status.success(), "{}", stderr(&color));
    assert!(no_color.status.success(), "{}", stderr(&no_color));
    assert_eq!(color.stderr, &[] as &[u8]);
    assert_eq!(no_color.stderr, &[] as &[u8]);
    assert_eq!(color.stdout, no_color.stdout);
    assert!(!color.stdout.contains(&b'\x1b'));
}

#[test]
fn every_long_option_has_a_short() {
    ctl_core::Surface::new::<qctl::cli::Cli>("qctl")
        .require_shorts(["--format", "--color", "--no-color"])
        .expect("every other long option has an operator-visible short");
}

#[test]
fn notes_flag_is_note_not_notes() {
    let dir = LedgerDir::empty();
    dir.write(MINIMAL);
    let rejected = qctl(&[
        "add",
        "-f",
        dir.path.to_str().unwrap(),
        "-t",
        "t",
        "-s",
        "s",
        "-o",
        "o",
        "-a",
        "a",
        "--notes",
        "old",
    ]);
    assert!(!rejected.status.success());
}

#[test]
fn park_refuses_when_a_queued_row_still_names_it() {
    let dir = LedgerDir::empty();
    dir.write(indoc! {"
        schema_version: 4
        prefix: QCTL
        active: QCTL-001
        queue:
          - id: QCTL-001
            title: First
            scope: s
            outcome: o
            blocked_by: []
            acceptance: [It holds.]
          - id: QCTL-002
            title: Second
            scope: s
            outcome: o
            blocked_by: [QCTL-001]
            acceptance: [It holds.]
        archive: []
        horizon: []
    "});
    let output = qctl(&[
        "park",
        "QCTL-001",
        "-f",
        dir.path.to_str().unwrap(),
        "-k",
        "research",
        "-O",
        "wait",
    ]);
    assert!(!output.status.success());
    assert!(
        stderr(&output).contains("still blocks"),
        "{}",
        stderr(&output)
    );
}