tix-tracker 0.2.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
//! End-to-end CLI contract tests (`contracts/cli.md`), driven through the
//! compiled binary only — never through library calls. Deterministic within
//! run time: filenames are asserted on their slug suffix (the date prefix is
//! dynamic), and every interaction avoids stdin TTYs (assert_cmd pipes).

use std::fs;
use std::path::PathBuf;

use assert_cmd::Command;
use predicates::prelude::*;
use tempfile::TempDir;

fn tix() -> Command {
    Command::cargo_bin("tix").unwrap()
}

/// Run `tix init` in dir and fetch the single issue file created by the next
/// `create`. Returns the issue file path.
///
/// Post-WP02 the layout is assignee-grouped: files live one level deep
/// (`docs/issues/<segment>/<stem>.md`, `unassigned/` for no assignee), with
/// legacy flat files at the top level still supported (C-010). The scan walks
/// exactly that one segment level plus the flat root, so a create landing in
/// `alice/…` and one landing in `unassigned/…` are both found.
fn issue_file(dir: &std::path::Path) -> PathBuf {
    let issues = dir.join("docs").join("issues");
    let mut md: Vec<PathBuf> = Vec::new();
    for entry in fs::read_dir(&issues).unwrap() {
        let path = entry.unwrap().path();
        if path.is_dir() {
            for child in fs::read_dir(&path).unwrap() {
                let child = child.unwrap().path();
                if child.extension().map(|e| e == "md").unwrap_or(false) {
                    md.push(child);
                }
            }
        } else if path.extension().map(|e| e == "md").unwrap_or(false) {
            md.push(path);
        }
    }
    assert_eq!(md.len(), 1, "expected exactly one issue file in {issues:?}");
    md.swap_remove(0)
}

/// The relative issue path `tix create` prints on success (`Created <rel>`),
/// e.g. `alice/2026-09-13-fix-login.md` (IC-03).
fn created_relative(out: &[u8]) -> String {
    let stdout = String::from_utf8(out.to_vec()).unwrap();
    stdout
        .lines()
        .map(str::trim)
        .find_map(|l| l.strip_prefix("Created "))
        .unwrap_or_else(|| panic!("no `Created ` line in {stdout:?}"))
        .to_string()
}

/// Run `git` inside `dir` for a hermetic local author identity, and assert it
/// succeeded. Local repo config always beats any global config, so the test
/// is deterministic regardless of the machine's ~/.gitconfig.
fn git(dir: &std::path::Path, args: &[&str]) {
    let status = std::process::Command::new("git")
        .current_dir(dir)
        .args(args)
        .status()
        .expect("`git` must be available to run the CLI tests");
    assert!(status.success(), "git {args:?} failed");
}

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

    // init
    tix()
        .current_dir(dir)
        .arg("init")
        .assert()
        .success()
        .stdout(predicate::str::contains("Created"));
    assert!(dir.join("tix.toml").is_file());

    // create
    tix()
        .current_dir(dir)
        .arg("create")
        .args(["--title", "Fix login bug"])
        .args(["--body", "Users can't log in"])
        .args(["--priority", "high"])
        .args(["--labels", "bug,auth"])
        .args(["--assignee", "@alice"])
        .args(["--estimate", "2"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Created "));
    let file = issue_file(dir);
    let filename = file.file_name().unwrap().to_string_lossy().to_string();
    assert!(
        filename.ends_with("-fix-login-bug.md"),
        "expected slug filename, got {filename}"
    );

    // list: header row first, issue row present
    let out = tix()
        .current_dir(dir)
        .arg("list")
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let list = String::from_utf8(out).unwrap();
    let first = list.lines().next().unwrap();
    assert!(
        first.contains("NUM") && first.contains("TITLE") && first.contains("STATUS"),
        "header row must be first: {list}"
    );
    assert!(
        list.lines()
            .any(|l| l.contains("Fix login bug") && l.contains("high")),
        "issue row missing: {list}"
    );

    // list --status filter (nothing is done yet → header only)
    let out = tix()
        .current_dir(dir)
        .args(["list", "--status", "done"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    assert_eq!(String::from_utf8(out).unwrap().lines().count(), 1);

    // view by number: frontmatter + verbatim body, nothing else on stdout
    tix()
        .current_dir(dir)
        .args(["view", "0"])
        .assert()
        .success()
        .stdout(
            predicate::str::starts_with("---\n").and(
                predicate::str::contains("number: 0")
                    .and(predicate::str::contains("title: Fix login bug"))
                    .and(predicate::str::contains("status: todo"))
                    .and(predicate::str::contains("priority: high"))
                    .and(predicate::str::contains("labels:"))
                    .and(predicate::str::contains("assignee:"))
                    .and(predicate::str::contains("@alice"))
                    .and(predicate::str::contains("estimate:"))
                    .and(predicate::str::contains("Users can't log in")),
            ),
        );

    // status board summary: header row, per-column counts, Total row
    let out = tix()
        .current_dir(dir)
        .arg("status")
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let status = String::from_utf8(out).unwrap();
    let header = status.lines().next().unwrap();
    assert!(
        header.contains("COLUMN") && header.contains("COUNT"),
        "status header first: {status}"
    );
    assert!(
        status
            .lines()
            .any(|l| l.trim().starts_with("todo") && l.contains('1')),
        "todo count missing: {status}"
    );
    assert!(
        status
            .lines()
            .any(|l| l.trim().starts_with("Total") && l.contains('1')),
        "total row missing: {status}"
    );

    // move into done with --commit: hash recorded in frontmatter
    tix()
        .current_dir(dir)
        .args(["move", "0", "done"])
        .arg("--commit")
        .arg("abc123")
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args(["view", "0"])
        .assert()
        .success()
        .stdout(predicate::str::contains("status: done").and(predicate::str::contains("abc123")));

    // move out of done: commit hash cleared
    tix()
        .current_dir(dir)
        .args(["move", "0", "in progress"])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args(["view", "0"])
        .assert()
        .success()
        .stdout(
            predicate::str::contains("status: in progress")
                .and(predicate::str::contains("abc123").not()),
        );

    // move into done without --commit on a pipe: hard error with guidance
    tix()
        .current_dir(dir)
        .args(["move", "0", "done"])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("--commit"));

    // move to an unknown column: error listing the valid columns
    tix()
        .current_dir(dir)
        .args(["move", "0", "bogus"])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("valid columns"));

    // edit: invalid priority rejected, valid flags merged
    tix()
        .current_dir(dir)
        .args(["edit", "0"])
        .args(["--priority", "bogus"])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("invalid priority"));
    tix()
        .current_dir(dir)
        .args(["edit", "0"])
        .args(["--priority", "medium"])
        .args(["--title", "Fix login bug v2"])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args(["view", "0"])
        .assert()
        .success()
        .stdout(
            predicate::str::contains("priority: medium")
                .and(predicate::str::contains("Fix login bug v2")),
        );

    // edit --commit set and clear
    tix()
        .current_dir(dir)
        .args(["edit", "0", "--commit", "abc123"])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args(["view", "0"])
        .assert()
        .success()
        .stdout(predicate::str::contains("abc123"));
    tix()
        .current_dir(dir)
        .args(["edit", "0", "--commit", "clear"])
        .assert()
        .success();
    tix()
        .current_dir(dir)
        .args(["view", "0"])
        .assert()
        .success()
        .stdout(predicate::str::contains("abc123").not());

    // delete --yes, then leftover scans
    tix()
        .current_dir(dir)
        .args(["delete", "0"])
        .arg("--yes")
        .assert()
        .success()
        .stdout(predicate::str::contains("Deleted "));
    assert!(!file.exists());
    let out = tix()
        .current_dir(dir)
        .arg("list")
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    assert_eq!(String::from_utf8(out).unwrap().lines().count(), 1);

    // viewing a deleted issue → exit 2 (target-not-found)
    tix()
        .current_dir(dir)
        .args(["view", "0"])
        .assert()
        .failure()
        .code(2)
        .stderr(predicate::str::contains("not found"));
}

#[test]
fn init_refuses_overwrite() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    tix()
        .current_dir(dir)
        .arg("init")
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("refusing to overwrite"));
    // existing config preserved
    let toml = fs::read_to_string(dir.join("tix.toml")).unwrap();
    assert!(toml.contains("issues_dir"));
}

#[test]
fn missing_config_notice_on_stderr_but_subcommand_succeeds() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix()
        .current_dir(dir)
        .arg("list")
        .assert()
        .success()
        .code(0)
        .stdout(predicate::str::contains("NUM"))
        .stderr(predicate::str::contains(
            "no tix.toml found (run 'tix init' to create one)",
        ));
}

#[test]
fn no_argv_without_config_is_contract_error() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix()
        .current_dir(dir)
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains(
            "no tix.toml found — run \"tix init\" first",
        ));
}

#[test]
fn create_without_title_on_pipe_is_usage_error() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    tix()
        .current_dir(dir)
        .arg("create")
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("--title"));
}

#[cfg(unix)]
#[test]
fn edit_invokes_real_editor_on_copy_and_commits_changes() {
    use std::os::unix::fs::PermissionsExt;

    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    tix()
        .current_dir(dir)
        .arg("create")
        .args(["--title", "Editor target"])
        .args(["--priority", "high"])
        .assert()
        .success();

    let editor = dir.join("editor.sh");
    fs::write(
        &editor,
        "#!/bin/sh\nsed -i 's/priority: high/priority: low/' \"$1\"\n",
    )
    .unwrap();
    fs::set_permissions(&editor, fs::Permissions::from_mode(0o755)).unwrap();

    tix()
        .current_dir(dir)
        .args(["edit", "0"])
        .env("EDITOR", editor.to_str().unwrap())
        .assert()
        .success();

    // The editor flip persisted to the issue file on disk (not just the copy)
    tix()
        .current_dir(dir)
        .args(["view", "0"])
        .assert()
        .success()
        .stdout(predicate::str::contains("priority: low"));
}

#[test]
fn view_by_slug_prefix_and_title_fragment_resolve() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    tix()
        .current_dir(dir)
        .arg("create")
        .args(["--title", "Refactor auth module"])
        .assert()
        .success();
    let file = issue_file(dir);
    let stem = file.file_stem().unwrap().to_string_lossy().to_string();
    // slug prefix (without the dynamic date prefix)
    tix()
        .current_dir(dir)
        .arg("view")
        .arg("refactor-auth")
        .assert()
        .success()
        .stdout(predicate::str::contains("title: Refactor auth module"));
    // unique title fragment
    tix()
        .current_dir(dir)
        .arg("view")
        .arg("auth")
        .assert()
        .success()
        .stdout(predicate::str::contains("title: Refactor auth module"));
    let _ = stem;
}

// -----------------------------------------------------------------------
// T011 — create defaults the assignee from the git identity (FR-028)
// -----------------------------------------------------------------------

/// create without `--assignee` in a *git-less* repo (global config
/// neutralized) never errors and lands in `unassigned/` (FR-028 fallback).
#[test]
fn create_without_assignee_without_git_identity_lands_in_unassigned() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();

    // Neutralize system + global git config so no identity can resolve —
    // the create must still succeed and fall back to `unassigned/`.
    let out = tix()
        .current_dir(dir)
        .arg("create")
        .args(["--title", "No git task"])
        .env("GIT_CONFIG_GLOBAL", "/dev/null")
        .env("GIT_CONFIG_NOSYSTEM", "1")
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let rel = created_relative(&out);
    assert!(
        rel.starts_with("unassigned/"),
        "expected unassigned/<stem>.md relative path, got {rel}"
    );
    assert!(
        rel.ends_with("-no-git-task.md"),
        "expected slug stem, got {rel}"
    );
    assert!(
        dir.join("docs").join("issues").join(&rel).is_file(),
        "file must exist at docs/issues/{rel}"
    );
}

/// create without `--assignee` inside a configured git repo defaults the
/// assignee to the full git identity and lands in its derived segment (FR-028).
#[test]
fn create_without_assignee_defaults_to_git_identity_segment() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    git(dir, &["init", "-q"]);
    git(dir, &["config", "user.name", "Herb Mason"]);
    git(dir, &["config", "user.email", "herb@example.com"]);

    tix().current_dir(dir).arg("init").assert().success();
    let out = tix()
        .current_dir(dir)
        .arg("create")
        .args(["--title", "Git task"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let rel = created_relative(&out);
    assert!(
        rel.starts_with("herb-mason/"),
        "expected identity segment, got {rel}"
    );
    assert!(
        dir.join("docs").join("issues").join(&rel).is_file(),
        "file must exist at docs/issues/{rel}"
    );

    // The full identity is stored verbatim in the frontmatter — never
    // @-prefixed (the raw view contract stays byte-true).
    tix()
        .current_dir(dir)
        .args(["view", "0"])
        .assert()
        .success()
        .stdout(
            predicate::str::contains("assignee:")
                .and(predicate::str::contains("Herb Mason <herb@example.com>"))
                .and(predicate::str::contains("@Herb").not()),
        );
}

// -----------------------------------------------------------------------
// T012 — edit --assignee physically moves the file (FR-031)
// -----------------------------------------------------------------------

/// `tix edit <n> --assignee <other>` migrates the file into the new assignee
/// segment: old relative path gone, new one present, `number` unchanged.
#[test]
fn edit_assignee_moves_file_and_keeps_number() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    let created = tix()
        .current_dir(dir)
        .arg("create")
        .args(["--title", "Reassign me"])
        .args(["--assignee", "@alice"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let rel = created_relative(&created);
    assert!(
        rel.starts_with("alice/"),
        "explicit --assignee must win, got {rel}"
    );
    let issues = dir.join("docs").join("issues");
    assert!(issues.join(&rel).is_file(), "{rel} must exist before edit");

    // edit: alice -> bob (bare handle, no @)
    tix()
        .current_dir(dir)
        .args(["edit", "0", "--assignee", "bob"])
        .assert()
        .success();
    assert!(
        !issues.join(&rel).exists(),
        "old path {rel} must be gone after reassign"
    );
    let new_rel = rel.replacen("alice/", "bob/", 1);
    assert!(
        issues.join(&new_rel).is_file(),
        "new path {new_rel} must exist after reassign"
    );
    // number stable; new assignee persisted
    tix()
        .current_dir(dir)
        .args(["view", "0"])
        .assert()
        .success()
        .stdout(
            predicate::str::contains("number: 0")
                .and(predicate::str::contains("assignee:"))
                .and(predicate::str::contains("bob")),
        );
}

/// `tix edit <n> --assignee ""` clears the assignee and moves the file to
/// `unassigned/` (FR-031).
#[test]
fn edit_assignee_empty_moves_to_unassigned() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    let created = tix()
        .current_dir(dir)
        .arg("create")
        .args(["--title", "Clear me"])
        .args(["--assignee", "alice"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let rel = created_relative(&created);
    let issues = dir.join("docs").join("issues");
    assert!(issues.join(&rel).is_file());

    tix()
        .current_dir(dir)
        .args(["edit", "0", "--assignee", ""])
        .assert()
        .success();
    assert!(
        !issues.join(&rel).exists(),
        "old path {rel} must be gone after clearing the assignee"
    );
    let new_rel = rel.replacen("alice/", "unassigned/", 1);
    assert!(
        issues.join(&new_rel).is_file(),
        "new path {new_rel} must exist under unassigned/"
    );
    // assignee cleared from the frontmatter (omitted when None)
    tix()
        .current_dir(dir)
        .args(["view", "0"])
        .assert()
        .success()
        .stdout(
            predicate::str::contains("number: 0").and(predicate::str::contains("assignee").not()),
        );
}

// -----------------------------------------------------------------------
// WP04 — `tix search` (FR-012, contract cli.md §search) and `tix lint`
// (FR-015..FR-018, contract cli.md §lint)
// -----------------------------------------------------------------------

/// Write a synthetic issue file into the store with full frontmatter control.
///
/// Returns the issues dir. The store layout accepts both flat legacy files
/// (C-010) and `segment/` grouped files; these helpers write flat files so
/// the search/lint corpus shape is fully deterministic.
fn with_store() -> (TempDir, std::path::PathBuf) {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    let issues = dir.join("docs").join("issues");
    std::fs::create_dir_all(&issues).unwrap();
    (tmp, issues)
}

fn write_frontmatter(path: &std::path::Path, fm: &str) {
    let contents = format!("---\n{fm}\n---\n\nbody text\n");
    std::fs::write(path, contents).unwrap();
}

/// Default valid frontmatter key/value pairs; individual tests override.
const GOOD_FM: &[&str] = &[
    "number: '1'",
    "title: \"Synthetic issue\"",
    "labels: []",
    "status: \"todo\"",
    "priority: \"medium\"",
    "created: \"2026-01-01\"",
    "updated: \"2026-01-01\"",
];

fn fm_line(number: u32, title: &str, extra: &[(&str, &str)]) -> Vec<String> {
    let mut parts: Vec<String> = vec![format!("number: {number}"), format!("title: \"{title}\"")];
    for line in GOOD_FM {
        if line.starts_with("number:") || line.starts_with("title:") {
            continue;
        }
        parts.push(line.to_string());
    }
    for (key, val) in extra {
        let rendered = if val.starts_with('[') || val.starts_with('{') || *val == "null" {
            format!("{key}: {val}")
        } else {
            format!("{key}: '{val}'")
        };
        if let Some(slot) = parts.iter_mut().find(|l| l.starts_with(&format!("{key}:"))) {
            *slot = rendered;
        } else {
            parts.push(rendered);
        }
    }
    parts
}

#[test]
fn search_matches_assignee_field() {
    let (_tmp, issues) = with_store();
    write_frontmatter(
        &issues.join("2026-01-01-alice-task.md"),
        &fm_line(1, "Config work", &[("assignee", "@alice")]).join("\n"),
    );
    tix()
        .current_dir(issues.parent().unwrap())
        .args(["search", "alice"])
        .assert()
        .success()
        .code(0)
        .stdout(
            predicate::str::contains("#1 Config work — todo (2026-01-01-alice-task.md)")
                .and(predicate::str::contains("@alice")),
        );
}

#[test]
fn search_matches_comment_text_only() {
    let (_tmp, issues) = with_store();
    let contents = format!(
        "---\n{}\n---\n\nbody\n\n## Comments\n\n### alice (2026-01-03)\n\nNeed a hotfix for the timeout.\n",
        fm_line(1, "Timeout investigation", &[]).join("\n")
    );
    std::fs::write(issues.join("2026-01-01-timeout.md"), contents).unwrap();
    tix()
        .current_dir(issues.parent().unwrap())
        .args(["search", "hotfix"])
        .assert()
        .success()
        .code(0)
        .stdout(
            predicate::str::contains("#1 Timeout investigation — todo (2026-01-01-timeout.md)")
                .and(predicate::str::contains("hotfix for the timeout")),
        );
}

#[test]
fn search_matches_frontmatter_label() {
    let (_tmp, issues) = with_store();
    write_frontmatter(
        &issues.join("2026-01-02-bug-repro.md"),
        &fm_line(1, "Repro steps", &[("labels", "[bug]")]).join("\n"),
    );
    tix()
        .current_dir(issues.parent().unwrap())
        .args(["search", "bug"])
        .assert()
        .success()
        .stdout(predicate::str::contains("#1 Repro steps"));
}

#[test]
fn search_is_case_insensitive() {
    let (_tmp, issues) = with_store();
    write_frontmatter(
        &issues.join("2026-01-01-case-test.md"),
        &fm_line(1, "Login flow", &[]).join("\n"),
    );
    let out = tix()
        .current_dir(issues.parent().unwrap())
        .args(["search", "LOGIN"])
        .assert()
        .success()
        .code(0)
        .get_output()
        .stdout
        .clone();
    assert!(String::from_utf8(out).unwrap().contains("#1 Login flow"));
}

#[test]
fn search_orders_hits_by_number() {
    let (_tmp, issues) = with_store();
    // Written out of numeric order on purpose; results must be #1, #2, #3.
    // All three share a label so the query matches every issue.
    let shared = [("labels", "[shared-word]")];
    write_frontmatter(
        &issues.join("2026-01-01-c.md"),
        &fm_line(3, "Third", &shared).join("\n"),
    );
    write_frontmatter(
        &issues.join("2026-01-02-a.md"),
        &fm_line(1, "First", &shared).join("\n"),
    );
    write_frontmatter(
        &issues.join("2026-01-03-b.md"),
        &fm_line(2, "Second", &shared).join("\n"),
    );
    let out = tix()
        .current_dir(issues.parent().unwrap())
        .args(["search", "shared-word"])
        .assert()
        .success()
        .code(0)
        .get_output()
        .stdout
        .clone();
    let stdout = String::from_utf8(out).unwrap();
    let idx1 = stdout.find("#1 First").expect("hit #1 missing");
    let idx2 = stdout.find("#2 Second").expect("hit #2 missing");
    let idx3 = stdout.find("#3 Third").expect("hit #3 missing");
    assert!(idx1 < idx2 && idx2 < idx3, "hits not ordered: {stdout}");
}

#[test]
fn search_zero_matches_prints_message_and_exits_zero() {
    let (_tmp, issues) = with_store();
    write_frontmatter(
        &issues.join("2026-01-01-foo.md"),
        &fm_line(1, "Foo", &[]).join("\n"),
    );
    tix()
        .current_dir(issues.parent().unwrap())
        .args(["search", "zzz-nothing"])
        .assert()
        .success()
        .code(0)
        .stdout("No issues found.\n");
}

#[test]
fn search_empty_query_is_usage_error_exit_2() {
    let (_tmp, issues) = with_store();
    tix()
        .current_dir(issues.parent().unwrap())
        .args(["search", ""])
        .assert()
        .failure()
        .code(2);
}

#[test]
fn search_store_io_failure_exits_1() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    // Replace the issues store with a plain file: `Store::open` sees the
    // path exists, so `list` hits `read_dir` on a file (ENOTDIR), a real
    // I/O error that search must surface with exit 1 (contract cli.md §search).
    std::fs::create_dir_all(dir.join("docs")).unwrap();
    std::fs::write(dir.join("docs/issues"), "not a directory").unwrap();
    let assert = tix()
        .current_dir(dir)
        .args(["search", "anything"])
        .assert()
        .failure()
        .code(1);
    assert!(
        !assert.get_output().stderr.is_empty(),
        "io failure must surface on stderr"
    );
}

#[test]
fn lint_flags_bad_status_with_valid_columns() {
    let (_tmp, issues) = with_store();
    let fm = fm_line(1, "Bad status", &[("status", "donex")]).join("\n");
    write_frontmatter(&issues.join("2026-01-01-bad-status.md"), &fm);
    tix()
        .current_dir(issues.parent().unwrap())
        .arg("lint")
        .assert()
        .failure()
        .code(1)
        .stderr(
            predicate::str::contains("error[E-tix-lint]")
                .and(predicate::str::contains("2026-01-01-bad-status.md"))
                .and(predicate::str::contains("donex"))
                .and(predicate::str::contains(
                    "valid options: todo, in progress, in review, done",
                )),
        );
}

#[test]
fn lint_flags_unknown_priority() {
    let (_tmp, issues) = with_store();
    let fm = fm_line(1, "Urgent", &[("priority", "urgent")]).join("\n");
    write_frontmatter(&issues.join("2026-01-01-urgent.md"), &fm);
    tix()
        .current_dir(issues.parent().unwrap())
        .arg("lint")
        .assert()
        .failure()
        .code(1)
        .stderr(
            predicate::str::contains("error[E-tix-lint]")
                .and(predicate::str::contains("priority"))
                .and(predicate::str::contains("urgent"))
                .and(predicate::str::contains("low, medium, high")),
        );
}

#[test]
fn lint_flags_malformed_created_date() {
    let (_tmp, issues) = with_store();
    let fm = fm_line(1, "Date issue", &[("created", "2026-13-99")]).join("\n");
    write_frontmatter(&issues.join("2026-01-01-date.md"), &fm);
    tix()
        .current_dir(issues.parent().unwrap())
        .arg("lint")
        .assert()
        .failure()
        .code(1)
        .stderr(
            predicate::str::contains("error[E-tix-lint]")
                .and(predicate::str::contains("created"))
                .and(predicate::str::contains("2026-13-99"))
                .and(predicate::str::contains("YYYY-MM-DD")),
        );
}

#[test]
fn lint_flags_non_numeric_estimate() {
    let (_tmp, issues) = with_store();
    let fm = fm_line(1, "Estimate", &[("estimate", "3d")]).join("\n");
    write_frontmatter(&issues.join("2026-01-01-estimate.md"), &fm);
    tix()
        .current_dir(issues.parent().unwrap())
        .arg("lint")
        .assert()
        .failure()
        .code(1)
        .stderr(
            predicate::str::contains("error[E-tix-lint]")
                .and(predicate::str::contains("estimate"))
                .and(predicate::str::contains("3d")),
        );
}

#[test]
fn lint_flags_non_integer_number() {
    let (_tmp, issues) = with_store();
    write_frontmatter(
        &issues.join("2026-01-01-bad-number.md"),
        "number: 'abc'\ntitle: \"Bad number\"",
    );
    tix()
        .current_dir(issues.parent().unwrap())
        .arg("lint")
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("error[E-tix-lint]"));
}

#[test]
fn lint_ignores_unknown_keys() {
    let (_tmp, issues) = with_store();
    let fm = fm_line(1, "Clean", &[("custom_key", "custom_value")]).join("\n");
    write_frontmatter(&issues.join("2026-01-03-clean.md"), &fm);
    tix()
        .current_dir(issues.parent().unwrap())
        .arg("lint")
        .assert()
        .success()
        .code(0)
        .stdout(predicate::str::contains("Lint OK: 1 issues checked."))
        .stderr(predicate::str::is_empty());
}

#[test]
fn lint_clean_store_summary() {
    let (_tmp, issues) = with_store();
    write_frontmatter(
        &issues.join("2026-01-01-a.md"),
        &fm_line(1, "A", &[]).join("\n"),
    );
    write_frontmatter(
        &issues.join("2026-01-02-b.md"),
        &fm_line(2, "B", &[]).join("\n"),
    );
    tix()
        .current_dir(issues.parent().unwrap())
        .arg("lint")
        .assert()
        .success()
        .code(0)
        .stdout(predicate::str::contains("Lint OK: 2 issues checked."));
}

#[test]
fn lint_missing_frontmatter_diagnostic_no_crash() {
    let (_tmp, issues) = with_store();
    std::fs::write(issues.join("2026-01-01-naked.md"), "no frontmatter here\n").unwrap();
    tix()
        .current_dir(issues.parent().unwrap())
        .arg("lint")
        .assert()
        .failure()
        .code(1)
        .stderr(
            predicate::str::contains("error[E-tix-lint]")
                .and(predicate::str::contains("2026-01-01-naked.md")),
        );
}

#[test]
fn lint_unparsable_yaml_diagnostic_no_crash() {
    let (_tmp, issues) = with_store();
    write_frontmatter(&issues.join("2026-01-01-broken.md"), "number 0x\n");
    tix()
        .current_dir(issues.parent().unwrap())
        .arg("lint")
        .assert()
        .failure()
        .code(1)
        .stderr(
            predicate::str::contains("error[E-tix-lint]")
                .and(predicate::str::contains("2026-01-01-broken.md")),
        );
}

#[test]
fn lint_non_utf8_diagnostic_no_crash() {
    let (_tmp, issues) = with_store();
    std::fs::write(issues.join("2026-01-01-binary.md"), b"\xff\xfe\x00\x01\xff").unwrap();
    tix()
        .current_dir(issues.parent().unwrap())
        .arg("lint")
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("error[E-tix-lint]"));
}
#[test]
fn edit_assignee_same_segment_is_noop_success() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path();
    tix().current_dir(dir).arg("init").assert().success();
    let created = tix()
        .current_dir(dir)
        .arg("create")
        .args(["--title", "Stay put"])
        .args(["--assignee", "alice"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let rel = created_relative(&created);
    let issues = dir.join("docs").join("issues");

    tix()
        .current_dir(dir)
        .args(["edit", "0", "--assignee", "@alice"])
        .assert()
        .success();
    assert!(
        issues.join(&rel).is_file(),
        "file must stay at {rel} when the segment is unchanged"
    );
}